@bemoje/cli 3.1.0 → 3.1.2
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/lib/index.cjs +1516 -59
- package/lib/index.d.cts +2658 -6
- package/lib/index.d.ts +2658 -6
- package/lib/index.js +1504 -8
- package/package.json +53 -85
- package/lib/lib/Command.cjs +0 -450
- package/lib/lib/Command.d.cts +0 -1
- package/lib/lib/Command.d.ts +0 -1
- package/lib/lib/Command.js +0 -443
- package/lib/lib/Help.cjs +0 -552
- package/lib/lib/Help.d.cts +0 -1
- package/lib/lib/Help.d.ts +0 -1
- package/lib/lib/Help.js +0 -545
- package/lib/lib/helpers/findCommand.cjs +0 -14
- package/lib/lib/helpers/findCommand.d.cts +0 -8
- package/lib/lib/helpers/findCommand.d.ts +0 -8
- package/lib/lib/helpers/findCommand.js +0 -11
- package/lib/lib/helpers/findOption.cjs +0 -16
- package/lib/lib/helpers/findOption.d.cts +0 -8
- package/lib/lib/helpers/findOption.d.ts +0 -8
- package/lib/lib/helpers/findOption.js +0 -14
- package/lib/lib/helpers/getCommandAncestors.cjs +0 -12
- package/lib/lib/helpers/getCommandAncestors.d.cts +0 -8
- package/lib/lib/helpers/getCommandAncestors.d.ts +0 -8
- package/lib/lib/helpers/getCommandAncestors.js +0 -9
- package/lib/lib/helpers/getCommandAndAncestors.cjs +0 -15
- package/lib/lib/helpers/getCommandAndAncestors.d.cts +0 -8
- package/lib/lib/helpers/getCommandAndAncestors.d.ts +0 -8
- package/lib/lib/helpers/getCommandAndAncestors.js +0 -13
- package/lib/lib/helpers/parseOptionFlags.cjs +0 -28
- package/lib/lib/helpers/parseOptionFlags.d.cts +0 -13
- package/lib/lib/helpers/parseOptionFlags.d.ts +0 -13
- package/lib/lib/helpers/parseOptionFlags.js +0 -26
- package/lib/lib/types.cjs +0 -2
- package/lib/lib/types.d.cts +0 -1
- package/lib/lib/types.d.ts +0 -1
- package/lib/lib/types.js +0 -1
package/lib/index.js
CHANGED
|
@@ -1,8 +1,1504 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import C from 'ansi-colors';
|
|
2
|
+
import { isFunction, isString, isPrimitive } from 'es-toolkit/predicate';
|
|
3
|
+
import memoizee from 'memoizee';
|
|
4
|
+
import { ms } from 'enhanced-ms';
|
|
5
|
+
import { inspect, parseArgs } from 'util';
|
|
6
|
+
import { kebabCase, upperFirst } from 'es-toolkit/string';
|
|
7
|
+
import { uniq, last } from 'es-toolkit/array';
|
|
8
|
+
import humanizeDuration from 'humanize-duration';
|
|
9
|
+
import { isPromise } from 'util/types';
|
|
10
|
+
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
13
|
+
|
|
14
|
+
// ../decorators/src/assertDescriptorValueIsFunction.ts
|
|
15
|
+
function assertDescriptorValueIsFunction(key, descriptor) {
|
|
16
|
+
if (!(typeof descriptor.value === "function" && descriptor.value !== Function.prototype)) {
|
|
17
|
+
throw new TypeError(`"value" not a function for ${key} with descriptor: ${JSON.stringify(descriptor)}.`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
__name(assertDescriptorValueIsFunction, "assertDescriptorValueIsFunction");
|
|
21
|
+
|
|
22
|
+
// ../object/src/entriesOf.ts
|
|
23
|
+
function entriesOf(obj) {
|
|
24
|
+
return Object.entries(obj);
|
|
25
|
+
}
|
|
26
|
+
__name(entriesOf, "entriesOf");
|
|
27
|
+
|
|
28
|
+
// ../object/src/keysOf.ts
|
|
29
|
+
function keysOf(obj) {
|
|
30
|
+
return Object.keys(obj);
|
|
31
|
+
}
|
|
32
|
+
__name(keysOf, "keysOf");
|
|
33
|
+
|
|
34
|
+
// ../object/src/filterObject.ts
|
|
35
|
+
function filterObject(obj, predicate) {
|
|
36
|
+
const accum = {};
|
|
37
|
+
for (const key of keysOf(obj)) {
|
|
38
|
+
if (predicate(obj[key], key, obj)) {
|
|
39
|
+
accum[key] = obj[key];
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return accum;
|
|
43
|
+
}
|
|
44
|
+
__name(filterObject, "filterObject");
|
|
45
|
+
|
|
46
|
+
// ../object/src/objSortKeys.ts
|
|
47
|
+
function objSortKeys(o, compare) {
|
|
48
|
+
const entries = Object.entries(o);
|
|
49
|
+
if (compare) {
|
|
50
|
+
entries.sort(compare);
|
|
51
|
+
} else {
|
|
52
|
+
entries.sort((a, b) => {
|
|
53
|
+
return a[0].localeCompare(b[0]);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return Object.fromEntries(entries);
|
|
57
|
+
}
|
|
58
|
+
__name(objSortKeys, "objSortKeys");
|
|
59
|
+
|
|
60
|
+
// ../object/src/valuesOf.ts
|
|
61
|
+
function valuesOf(obj) {
|
|
62
|
+
return Object.values(obj);
|
|
63
|
+
}
|
|
64
|
+
__name(valuesOf, "valuesOf");
|
|
65
|
+
|
|
66
|
+
// ../map/src/mapGetOrDefault.ts
|
|
67
|
+
function mapGetOrDefault(map, key, factory) {
|
|
68
|
+
let value = map.get(key);
|
|
69
|
+
if (value !== void 0 || map.has(key)) {
|
|
70
|
+
return value;
|
|
71
|
+
}
|
|
72
|
+
value = factory(key, map);
|
|
73
|
+
map.set(key, value);
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
__name(mapGetOrDefault, "mapGetOrDefault");
|
|
77
|
+
|
|
78
|
+
// ../map/src/TimeoutWeakMap.ts
|
|
79
|
+
var TimeoutWeakMap = class {
|
|
80
|
+
static {
|
|
81
|
+
__name(this, "TimeoutWeakMap");
|
|
82
|
+
}
|
|
83
|
+
timeoutMs;
|
|
84
|
+
wmap = /* @__PURE__ */ new WeakMap();
|
|
85
|
+
/**
|
|
86
|
+
* @param timeoutMs Default timeout in milliseconds for entries
|
|
87
|
+
*/
|
|
88
|
+
constructor(timeoutMs) {
|
|
89
|
+
this.timeoutMs = timeoutMs;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Retrieves the value for the given key and refreshes its timeout.
|
|
93
|
+
*
|
|
94
|
+
* @param key The key to retrieve
|
|
95
|
+
* @returns The value if found, undefined otherwise
|
|
96
|
+
*/
|
|
97
|
+
get(key) {
|
|
98
|
+
const vt = this.wmap.get(key);
|
|
99
|
+
if (!vt) {
|
|
100
|
+
return void 0;
|
|
101
|
+
}
|
|
102
|
+
const [value, timeout] = vt;
|
|
103
|
+
timeout.refresh();
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Sets a key-value pair with an optional custom timeout.
|
|
108
|
+
*
|
|
109
|
+
* @param key The key to set
|
|
110
|
+
* @param value The value to associate with the key
|
|
111
|
+
* @param timeoutMs Optional timeout override for this entry
|
|
112
|
+
* @returns This instance for chaining
|
|
113
|
+
*/
|
|
114
|
+
set(key, value, timeoutMs) {
|
|
115
|
+
this.wmap.set(key, [
|
|
116
|
+
value,
|
|
117
|
+
setTimeout(() => {
|
|
118
|
+
this.delete(key);
|
|
119
|
+
}, timeoutMs ?? this.timeoutMs).unref()
|
|
120
|
+
]);
|
|
121
|
+
return this;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Removes a key-value pair and clears its timeout.
|
|
125
|
+
*
|
|
126
|
+
* @param key The key to delete
|
|
127
|
+
* @returns True if the key existed and was deleted, false otherwise
|
|
128
|
+
*/
|
|
129
|
+
delete(key) {
|
|
130
|
+
const vt = this.wmap.get(key);
|
|
131
|
+
if (!vt) {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
const timeout = vt[1];
|
|
135
|
+
clearTimeout(timeout);
|
|
136
|
+
return this.wmap.delete(key);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Checks if a key exists in the map.
|
|
140
|
+
* Does not refresh the timeout.
|
|
141
|
+
*
|
|
142
|
+
* @param key The key to check
|
|
143
|
+
* @returns True if the key exists, false otherwise
|
|
144
|
+
*/
|
|
145
|
+
has(key) {
|
|
146
|
+
return this.wmap.has(key);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Loads multiple key-value pairs into the map.
|
|
150
|
+
*
|
|
151
|
+
* @param entries Iterable of key-value pairs to load
|
|
152
|
+
* @param timeoutMs Optional timeout override for all entries
|
|
153
|
+
* @returns This instance for chaining
|
|
154
|
+
*/
|
|
155
|
+
load(entries, timeoutMs) {
|
|
156
|
+
for (const [key, value] of entries) {
|
|
157
|
+
this.set(key, value, timeoutMs);
|
|
158
|
+
}
|
|
159
|
+
return this;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Updates an existing value or creates a new one using an update function.
|
|
163
|
+
*
|
|
164
|
+
* @param key The key to update
|
|
165
|
+
* @param update Function that receives the current value and returns the new value
|
|
166
|
+
* @returns This instance for chaining
|
|
167
|
+
*/
|
|
168
|
+
update(key, update) {
|
|
169
|
+
return this.set(key, update(this.get(key), key, this));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Gets a value or creates it using a factory function if it doesn't exist.
|
|
173
|
+
* Refreshes timeout if the value exists.
|
|
174
|
+
*
|
|
175
|
+
* @param key The key to get or create
|
|
176
|
+
* @param factory Function to create the value if it doesn't exist
|
|
177
|
+
* @param timeoutMs Optional timeout override for new entries
|
|
178
|
+
* @returns The existing or newly created value
|
|
179
|
+
*/
|
|
180
|
+
getOrDefault(key, factory, timeoutMs) {
|
|
181
|
+
const vt = this.wmap.get(key);
|
|
182
|
+
if (vt) {
|
|
183
|
+
const [value, timeout] = vt;
|
|
184
|
+
timeout.refresh();
|
|
185
|
+
return value;
|
|
186
|
+
} else {
|
|
187
|
+
const value = factory(key, this);
|
|
188
|
+
this.set(key, value, timeoutMs);
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
function memoizeSync(arg = {}) {
|
|
194
|
+
const opts = typeof arg === "object" ? arg : {
|
|
195
|
+
maxAge: typeof arg === "number" ? arg : ms(arg)
|
|
196
|
+
};
|
|
197
|
+
return /* @__PURE__ */ __name(function decorator(target, key, descriptor) {
|
|
198
|
+
if (!descriptor) {
|
|
199
|
+
throw new TypeError("descriptor is undefined");
|
|
200
|
+
}
|
|
201
|
+
const orig = descriptor.value;
|
|
202
|
+
assertDescriptorValueIsFunction(key, descriptor);
|
|
203
|
+
const options = {
|
|
204
|
+
length: false,
|
|
205
|
+
...opts
|
|
206
|
+
};
|
|
207
|
+
if (opts.instancesShareCache) {
|
|
208
|
+
Reflect.deleteProperty(options, "instancesShareCache");
|
|
209
|
+
descriptor.value = memoizee(orig, options);
|
|
210
|
+
} else {
|
|
211
|
+
const wmap = /* @__PURE__ */ new WeakMap();
|
|
212
|
+
descriptor.value = function(...args) {
|
|
213
|
+
const memoized = mapGetOrDefault(wmap, this, () => {
|
|
214
|
+
return memoizee(orig, options);
|
|
215
|
+
});
|
|
216
|
+
return memoized.apply(this, args);
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return descriptor;
|
|
220
|
+
}, "decorator");
|
|
221
|
+
}
|
|
222
|
+
__name(memoizeSync, "memoizeSync");
|
|
223
|
+
function lazyProp(targetOrTimeout, key, descriptor) {
|
|
224
|
+
if (typeof targetOrTimeout === "number" || typeof targetOrTimeout === "string") {
|
|
225
|
+
const maxAge = typeof targetOrTimeout === "number" ? targetOrTimeout : ms(targetOrTimeout);
|
|
226
|
+
return createLazyPropDecorator(new TimeoutWeakMap(maxAge));
|
|
227
|
+
} else {
|
|
228
|
+
const decorator = createLazyPropDecorator(/* @__PURE__ */ new WeakMap());
|
|
229
|
+
return decorator(targetOrTimeout, key, descriptor);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
__name(lazyProp, "lazyProp");
|
|
233
|
+
function createLazyPropDecorator(map) {
|
|
234
|
+
return function(target, key, descriptor) {
|
|
235
|
+
const { get, value } = descriptor;
|
|
236
|
+
if (isFunction(get)) {
|
|
237
|
+
descriptor.get = function() {
|
|
238
|
+
return mapGetOrDefault(map, this, () => {
|
|
239
|
+
return get.call(this);
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
return descriptor;
|
|
243
|
+
}
|
|
244
|
+
if (isFunction(value)) {
|
|
245
|
+
return memoizeSync()(target, key, descriptor);
|
|
246
|
+
}
|
|
247
|
+
throw new TypeError('neither "get" nor "value" are functions');
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
__name(createLazyPropDecorator, "createLazyPropDecorator");
|
|
251
|
+
|
|
252
|
+
// src/lib/Help.ts
|
|
253
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
254
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
255
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
256
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
257
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
258
|
+
}
|
|
259
|
+
__name(_ts_decorate, "_ts_decorate");
|
|
260
|
+
function _ts_metadata(k, v) {
|
|
261
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
262
|
+
}
|
|
263
|
+
__name(_ts_metadata, "_ts_metadata");
|
|
264
|
+
var Help = class {
|
|
265
|
+
static {
|
|
266
|
+
__name(this, "Help");
|
|
267
|
+
}
|
|
268
|
+
cmd;
|
|
269
|
+
/** output helpWidth, long lines are wrapped to fit */
|
|
270
|
+
helpWidth = process.stdout.isTTY ? process.stdout.columns : 80;
|
|
271
|
+
minWidthToWrap = 40;
|
|
272
|
+
sortSubcommands = true;
|
|
273
|
+
sortOptions = true;
|
|
274
|
+
usageDisplayOptionsAs = "[opts]";
|
|
275
|
+
usageDisplaySubcommandAs = "[cmd]";
|
|
276
|
+
constructor(cmd) {
|
|
277
|
+
this.cmd = cmd;
|
|
278
|
+
Object.defineProperty(this, "cmd", {
|
|
279
|
+
enumerable: false
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
284
|
+
*/
|
|
285
|
+
visibleCommands() {
|
|
286
|
+
const res = Object.values(this.cmd.commands).filter((c) => {
|
|
287
|
+
return !c.hidden;
|
|
288
|
+
});
|
|
289
|
+
if (this.sortSubcommands) {
|
|
290
|
+
res.sort((a, b) => {
|
|
291
|
+
return a.name.localeCompare(b.name);
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
return res;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Compare options for sort.
|
|
298
|
+
*/
|
|
299
|
+
compareOptions(a, b) {
|
|
300
|
+
const getSortKey = /* @__PURE__ */ __name((option) => {
|
|
301
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
302
|
+
}, "getSortKey");
|
|
303
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
307
|
+
*/
|
|
308
|
+
visibleOptions() {
|
|
309
|
+
const res = this.cmd.options.filter((option) => {
|
|
310
|
+
return !option.hidden;
|
|
311
|
+
});
|
|
312
|
+
if (this.sortOptions) {
|
|
313
|
+
res.sort(this.compareOptions);
|
|
314
|
+
}
|
|
315
|
+
return res;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Get an array of the arguments if any have a description.
|
|
319
|
+
*/
|
|
320
|
+
visibleArguments() {
|
|
321
|
+
return this.cmd.arguments.slice();
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Get the command term to show in the list of subcommands.
|
|
325
|
+
*/
|
|
326
|
+
subcommandTerm(sub) {
|
|
327
|
+
const args = sub.arguments.map((arg) => {
|
|
328
|
+
return arg.usage;
|
|
329
|
+
}).join(" ");
|
|
330
|
+
return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + (args ? ` ${args}` : "");
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Get the option term to show in the list of options.
|
|
334
|
+
*/
|
|
335
|
+
optionTerm(option) {
|
|
336
|
+
return option.flags;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Get the argument term to show in the list of arguments.
|
|
340
|
+
*/
|
|
341
|
+
argumentTerm(argument) {
|
|
342
|
+
return argument.usage;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Get the longest subcommand primary alias length.
|
|
346
|
+
*/
|
|
347
|
+
longestSubcommandAliasLength() {
|
|
348
|
+
return Math.max(0, ...this.visibleCommands().map((c) => {
|
|
349
|
+
return c.aliases[0]?.length || 0;
|
|
350
|
+
}));
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Get the longest subcommand term length.
|
|
354
|
+
*/
|
|
355
|
+
longestSubcommandTermLength() {
|
|
356
|
+
return this.visibleCommands().reduce((max, command) => {
|
|
357
|
+
return Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command))));
|
|
358
|
+
}, 0);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Get the longest option term length.
|
|
362
|
+
*/
|
|
363
|
+
longestOptionTermLength() {
|
|
364
|
+
return this.visibleOptions().reduce((max, option) => {
|
|
365
|
+
return Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option))));
|
|
366
|
+
}, 0);
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Get the longest argument term length.
|
|
370
|
+
*/
|
|
371
|
+
longestArgumentTermLength() {
|
|
372
|
+
return this.visibleArguments().reduce((max, argument) => {
|
|
373
|
+
return Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument))));
|
|
374
|
+
}, 0);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
378
|
+
*/
|
|
379
|
+
commandUsage() {
|
|
380
|
+
let path = "";
|
|
381
|
+
for (let ancestor = this.cmd.parent; ancestor; ancestor = ancestor.parent) {
|
|
382
|
+
path = `${ancestor.name} ${path}`;
|
|
383
|
+
}
|
|
384
|
+
return `${path + this.cmd.name} ${[
|
|
385
|
+
...Object.keys(this.cmd.commands).length ? [
|
|
386
|
+
this.usageDisplaySubcommandAs
|
|
387
|
+
] : [],
|
|
388
|
+
...this.cmd.options.length ? [
|
|
389
|
+
this.usageDisplayOptionsAs
|
|
390
|
+
] : [],
|
|
391
|
+
...this.cmd.arguments.map((arg) => {
|
|
392
|
+
return arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`;
|
|
393
|
+
})
|
|
394
|
+
].join(" ")}`.trim();
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Get the description for the command.
|
|
398
|
+
*/
|
|
399
|
+
commandDescription() {
|
|
400
|
+
let res = "";
|
|
401
|
+
if (this.cmd.aliases.length) {
|
|
402
|
+
res += `Aliases: ${this.cmd.aliases.join(", ")}`;
|
|
403
|
+
res += "\n\n";
|
|
404
|
+
}
|
|
405
|
+
res += this.cmd.description;
|
|
406
|
+
return res;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
410
|
+
* (Fallback to description for backwards compatibility.)
|
|
411
|
+
*/
|
|
412
|
+
subcommandDescription(sub) {
|
|
413
|
+
return sub.summary || (sub.description?.includes("\n") ? sub.description.trim().split("\n")[0] : sub.description.trim());
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Get the option description to show in the list of options.
|
|
417
|
+
*/
|
|
418
|
+
optionDescription(option) {
|
|
419
|
+
const extraInfo = [];
|
|
420
|
+
if (option.choices) {
|
|
421
|
+
const choices = option.choices.length > 5 ? option.choices.slice(0, 5).concat([
|
|
422
|
+
"..."
|
|
423
|
+
]) : option.choices;
|
|
424
|
+
extraInfo.push(
|
|
425
|
+
// use stringify to match the display of the default value
|
|
426
|
+
`choices: ${choices.join(", ")}`
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
if (option.defaultValue && !(Array.isArray(option.defaultValue) && option.defaultValue.length === 0)) {
|
|
430
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue).replaceAll('"', "")}`);
|
|
431
|
+
}
|
|
432
|
+
if (option.env !== void 0) {
|
|
433
|
+
extraInfo.push(`env: ${option.env}`);
|
|
434
|
+
}
|
|
435
|
+
if (extraInfo.length > 0) {
|
|
436
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
437
|
+
if (option.description) {
|
|
438
|
+
return `${option.description} ${extraDescription}`;
|
|
439
|
+
}
|
|
440
|
+
return extraDescription;
|
|
441
|
+
}
|
|
442
|
+
return option.description ?? "";
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Get the argument description to show in the list of arguments.
|
|
446
|
+
*/
|
|
447
|
+
argumentDescription(argument) {
|
|
448
|
+
const extraInfo = [];
|
|
449
|
+
if (argument.choices) {
|
|
450
|
+
const choices = argument.choices.length > 5 ? argument.choices.slice(0, 5).concat([
|
|
451
|
+
"..."
|
|
452
|
+
]) : argument.choices;
|
|
453
|
+
extraInfo.push(
|
|
454
|
+
// use stringify to match the display of the default value
|
|
455
|
+
`choices: ${choices.join(", ")}`
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
if (argument.defaultValue && !(Array.isArray(argument.defaultValue) && argument.defaultValue.length === 0)) {
|
|
459
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue).replaceAll('"', "")}`);
|
|
460
|
+
}
|
|
461
|
+
if (extraInfo.length > 0) {
|
|
462
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
463
|
+
if (argument.description) {
|
|
464
|
+
return `${argument.description} ${extraDescription}`;
|
|
465
|
+
}
|
|
466
|
+
return extraDescription;
|
|
467
|
+
}
|
|
468
|
+
return argument.description ?? "";
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
472
|
+
*/
|
|
473
|
+
formatItemList(heading, items) {
|
|
474
|
+
if (items.length === 0) {
|
|
475
|
+
return [];
|
|
476
|
+
}
|
|
477
|
+
return [
|
|
478
|
+
this.styleTitle(heading),
|
|
479
|
+
...items,
|
|
480
|
+
""
|
|
481
|
+
];
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Group items by their help group heading.
|
|
485
|
+
*/
|
|
486
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
487
|
+
const result = /* @__PURE__ */ new Map();
|
|
488
|
+
unsortedItems.forEach((item) => {
|
|
489
|
+
const group = getGroup(item);
|
|
490
|
+
if (!result.has(group)) {
|
|
491
|
+
result.set(group, []);
|
|
492
|
+
}
|
|
493
|
+
});
|
|
494
|
+
visibleItems.forEach((item) => {
|
|
495
|
+
const group = getGroup(item);
|
|
496
|
+
if (!result.has(group)) {
|
|
497
|
+
result.set(group, []);
|
|
498
|
+
}
|
|
499
|
+
result.get(group).push(item);
|
|
500
|
+
});
|
|
501
|
+
return result;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
505
|
+
*/
|
|
506
|
+
displayWidth(str) {
|
|
507
|
+
const sgrPattern = /\u001b\[\d*(;\d*)*m/g;
|
|
508
|
+
return str.replaceAll(sgrPattern, "").length;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
512
|
+
*/
|
|
513
|
+
styleTitle(str) {
|
|
514
|
+
return C.yellow(str);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
|
|
518
|
+
*/
|
|
519
|
+
styleUsage(str) {
|
|
520
|
+
return str.split(" ").map((word, index, arr) => {
|
|
521
|
+
if (word === this.usageDisplaySubcommandAs) {
|
|
522
|
+
return C.green(word);
|
|
523
|
+
}
|
|
524
|
+
if (word === this.usageDisplayOptionsAs) {
|
|
525
|
+
return C.blue(word);
|
|
526
|
+
}
|
|
527
|
+
if (word[0] === "<") {
|
|
528
|
+
return C.red(word);
|
|
529
|
+
}
|
|
530
|
+
if (word[0] === "[") {
|
|
531
|
+
return C.cyan(word);
|
|
532
|
+
}
|
|
533
|
+
if (arr[index + 1]?.startsWith("[")) {
|
|
534
|
+
return C.magenta(word);
|
|
535
|
+
}
|
|
536
|
+
return this.styleCommandText(word);
|
|
537
|
+
}).join(" ");
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Style command descriptions for display in help output.
|
|
541
|
+
*/
|
|
542
|
+
styleCommandDescription(str) {
|
|
543
|
+
return this.styleDescriptionText(str);
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Style option descriptions for display in help output.
|
|
547
|
+
*/
|
|
548
|
+
styleOptionDescription(str) {
|
|
549
|
+
return C.gray(this.styleDescriptionText(str));
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Style subcommand descriptions for display in help output.
|
|
553
|
+
*/
|
|
554
|
+
styleSubcommandDescription(str) {
|
|
555
|
+
return this.styleDescriptionText(str);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Style argument descriptions for display in help output.
|
|
559
|
+
*/
|
|
560
|
+
styleArgumentDescription(str) {
|
|
561
|
+
return C.gray(this.styleDescriptionText(str));
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Base style used by descriptions. Override in subclass to apply custom formatting.
|
|
565
|
+
*/
|
|
566
|
+
styleDescriptionText(str) {
|
|
567
|
+
return C.gray(str);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Style option terms (flags) for display in help output.
|
|
571
|
+
*/
|
|
572
|
+
styleOptionTerm(str) {
|
|
573
|
+
return this.styleOptionText(str);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
|
|
577
|
+
*/
|
|
578
|
+
styleSubcommandTerm(str) {
|
|
579
|
+
const res = str.split(" ").map((word) => {
|
|
580
|
+
if (word === this.usageDisplayOptionsAs) {
|
|
581
|
+
return C.dim(word);
|
|
582
|
+
}
|
|
583
|
+
if (word[0] === "[" || word[0] === "<") {
|
|
584
|
+
return C.dim(word);
|
|
585
|
+
}
|
|
586
|
+
return this.styleSubcommandText(word);
|
|
587
|
+
}).join(" ");
|
|
588
|
+
const split = res.split("|");
|
|
589
|
+
if (split.length === 1) {
|
|
590
|
+
return res;
|
|
591
|
+
}
|
|
592
|
+
split[0] = C.green(split[0]);
|
|
593
|
+
return split.join("|");
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Style argument terms for display in help output.
|
|
597
|
+
*/
|
|
598
|
+
styleArgumentTerm(str) {
|
|
599
|
+
return this.styleArgumentText(str);
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Base style used in terms and usage for options. Override in subclass to apply custom formatting.
|
|
603
|
+
*/
|
|
604
|
+
styleOptionText(str) {
|
|
605
|
+
return str;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
|
|
609
|
+
*/
|
|
610
|
+
styleArgumentText(str) {
|
|
611
|
+
return str;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
|
|
615
|
+
*/
|
|
616
|
+
styleSubcommandText(str) {
|
|
617
|
+
return str;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
|
|
621
|
+
*/
|
|
622
|
+
styleCommandText(str) {
|
|
623
|
+
return str;
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Calculate the pad width from the maximum term length.
|
|
627
|
+
*/
|
|
628
|
+
padWidth() {
|
|
629
|
+
return Math.max(this.longestOptionTermLength(), this.longestSubcommandTermLength(), this.longestArgumentTermLength());
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
633
|
+
*/
|
|
634
|
+
preformatted(str) {
|
|
635
|
+
return /\n[^\S\n\r]/.test(str);
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
639
|
+
*
|
|
640
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
641
|
+
* TTT DDD DDDD
|
|
642
|
+
* DD DDD
|
|
643
|
+
*/
|
|
644
|
+
formatItem(term, termWidth, description) {
|
|
645
|
+
const itemIndent = 2;
|
|
646
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
647
|
+
if (!description) {
|
|
648
|
+
return itemIndentStr + term;
|
|
649
|
+
}
|
|
650
|
+
const paddedTerm = term.padEnd(termWidth + term.length - this.displayWidth(term));
|
|
651
|
+
const spacerWidth = 2;
|
|
652
|
+
const helpWidth = this.helpWidth;
|
|
653
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
654
|
+
let formattedDescription;
|
|
655
|
+
if (remainingWidth < this.minWidthToWrap || this.preformatted(description)) {
|
|
656
|
+
formattedDescription = description;
|
|
657
|
+
} else {
|
|
658
|
+
const wrappedDescription = this.boxWrap(description, remainingWidth);
|
|
659
|
+
formattedDescription = wrappedDescription.replaceAll("\n", `
|
|
660
|
+
${" ".repeat(termWidth + spacerWidth)}`);
|
|
661
|
+
}
|
|
662
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replaceAll("\n", `
|
|
663
|
+
${itemIndentStr}`);
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
667
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
668
|
+
*/
|
|
669
|
+
boxWrap(str, width) {
|
|
670
|
+
if (width < this.minWidthToWrap) {
|
|
671
|
+
return str;
|
|
672
|
+
}
|
|
673
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
674
|
+
const chunkPattern = /\s*\S+/g;
|
|
675
|
+
const wrappedLines = [];
|
|
676
|
+
rawLines.forEach((line) => {
|
|
677
|
+
const chunks = line.match(chunkPattern);
|
|
678
|
+
if (chunks === null) {
|
|
679
|
+
wrappedLines.push("");
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
let sumChunks = [
|
|
683
|
+
chunks.shift()
|
|
684
|
+
];
|
|
685
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
686
|
+
chunks.forEach((chunk) => {
|
|
687
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
688
|
+
if (sumWidth + visibleWidth <= width) {
|
|
689
|
+
sumChunks.push(chunk);
|
|
690
|
+
sumWidth += visibleWidth;
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
wrappedLines.push(sumChunks.join(""));
|
|
694
|
+
const nextChunk = chunk.trimStart();
|
|
695
|
+
sumChunks = [
|
|
696
|
+
nextChunk
|
|
697
|
+
];
|
|
698
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
699
|
+
});
|
|
700
|
+
wrappedLines.push(sumChunks.join(""));
|
|
701
|
+
});
|
|
702
|
+
return wrappedLines.join("\n");
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Generate the built-in help text.
|
|
706
|
+
*/
|
|
707
|
+
render() {
|
|
708
|
+
let output = [
|
|
709
|
+
`${this.styleTitle("Usage:")} ${this.styleUsage(this.commandUsage())}`,
|
|
710
|
+
""
|
|
711
|
+
];
|
|
712
|
+
const des = this.commandDescription();
|
|
713
|
+
if (des.length > 0) {
|
|
714
|
+
output = output.concat([
|
|
715
|
+
this.boxWrap(this.styleCommandDescription(des), this.helpWidth),
|
|
716
|
+
""
|
|
717
|
+
]);
|
|
718
|
+
}
|
|
719
|
+
const argumentList = this.visibleArguments().map((argument) => {
|
|
720
|
+
return this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument)));
|
|
721
|
+
});
|
|
722
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList));
|
|
723
|
+
const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => {
|
|
724
|
+
return option.group ?? "Options:";
|
|
725
|
+
});
|
|
726
|
+
optionGroups.forEach((options, group) => {
|
|
727
|
+
const optionList = options.map((option) => {
|
|
728
|
+
return this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option)));
|
|
729
|
+
});
|
|
730
|
+
output = output.concat(this.formatItemList(group, optionList));
|
|
731
|
+
});
|
|
732
|
+
const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => {
|
|
733
|
+
return sub.group || "Commands:";
|
|
734
|
+
});
|
|
735
|
+
commandGroups.forEach((commands, group) => {
|
|
736
|
+
const commandList = commands.map((sub) => {
|
|
737
|
+
return this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub)));
|
|
738
|
+
});
|
|
739
|
+
output = output.concat(this.formatItemList(group, commandList));
|
|
740
|
+
});
|
|
741
|
+
return output.join("\n");
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
_ts_decorate([
|
|
745
|
+
lazyProp,
|
|
746
|
+
_ts_metadata("design:type", Function),
|
|
747
|
+
_ts_metadata("design:paramtypes", []),
|
|
748
|
+
_ts_metadata("design:returntype", Array)
|
|
749
|
+
], Help.prototype, "visibleCommands", null);
|
|
750
|
+
_ts_decorate([
|
|
751
|
+
lazyProp,
|
|
752
|
+
_ts_metadata("design:type", Function),
|
|
753
|
+
_ts_metadata("design:paramtypes", []),
|
|
754
|
+
_ts_metadata("design:returntype", Array)
|
|
755
|
+
], Help.prototype, "visibleOptions", null);
|
|
756
|
+
_ts_decorate([
|
|
757
|
+
lazyProp,
|
|
758
|
+
_ts_metadata("design:type", Function),
|
|
759
|
+
_ts_metadata("design:paramtypes", []),
|
|
760
|
+
_ts_metadata("design:returntype", Array)
|
|
761
|
+
], Help.prototype, "visibleArguments", null);
|
|
762
|
+
_ts_decorate([
|
|
763
|
+
lazyProp,
|
|
764
|
+
_ts_metadata("design:type", Function),
|
|
765
|
+
_ts_metadata("design:paramtypes", []),
|
|
766
|
+
_ts_metadata("design:returntype", Number)
|
|
767
|
+
], Help.prototype, "longestSubcommandAliasLength", null);
|
|
768
|
+
_ts_decorate([
|
|
769
|
+
lazyProp,
|
|
770
|
+
_ts_metadata("design:type", Function),
|
|
771
|
+
_ts_metadata("design:paramtypes", []),
|
|
772
|
+
_ts_metadata("design:returntype", Number)
|
|
773
|
+
], Help.prototype, "longestSubcommandTermLength", null);
|
|
774
|
+
_ts_decorate([
|
|
775
|
+
lazyProp,
|
|
776
|
+
_ts_metadata("design:type", Function),
|
|
777
|
+
_ts_metadata("design:paramtypes", []),
|
|
778
|
+
_ts_metadata("design:returntype", Number)
|
|
779
|
+
], Help.prototype, "longestOptionTermLength", null);
|
|
780
|
+
_ts_decorate([
|
|
781
|
+
lazyProp,
|
|
782
|
+
_ts_metadata("design:type", Function),
|
|
783
|
+
_ts_metadata("design:paramtypes", []),
|
|
784
|
+
_ts_metadata("design:returntype", Number)
|
|
785
|
+
], Help.prototype, "longestArgumentTermLength", null);
|
|
786
|
+
_ts_decorate([
|
|
787
|
+
lazyProp,
|
|
788
|
+
_ts_metadata("design:type", Function),
|
|
789
|
+
_ts_metadata("design:paramtypes", []),
|
|
790
|
+
_ts_metadata("design:returntype", Number)
|
|
791
|
+
], Help.prototype, "padWidth", null);
|
|
792
|
+
|
|
793
|
+
// src/lib/internal/collectVariadicOptionValues.ts
|
|
794
|
+
function collectVariadicOptionValues(parsed, options) {
|
|
795
|
+
for (let i = 0; i < parsed.tokens.length; i++) {
|
|
796
|
+
const token = parsed.tokens[i];
|
|
797
|
+
if (token.kind !== "option") {
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
const def = options.find((o) => {
|
|
801
|
+
return o.name === token.name;
|
|
802
|
+
});
|
|
803
|
+
if (!def?.variadic || def.type !== "string") {
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
const values = [
|
|
807
|
+
token.value
|
|
808
|
+
];
|
|
809
|
+
let j = i + 1;
|
|
810
|
+
while (j < parsed.tokens.length && parsed.tokens[j].kind === "positional") {
|
|
811
|
+
const positionalToken = parsed.tokens[j];
|
|
812
|
+
values.push(positionalToken.value);
|
|
813
|
+
const posIndex = parsed.positionals.indexOf(positionalToken.value);
|
|
814
|
+
if (posIndex !== -1) {
|
|
815
|
+
parsed.positionals.splice(posIndex, 1);
|
|
816
|
+
}
|
|
817
|
+
j++;
|
|
818
|
+
}
|
|
819
|
+
Reflect.set(parsed.values, token.name, values.filter((v) => {
|
|
820
|
+
return v !== void 0;
|
|
821
|
+
}));
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
__name(collectVariadicOptionValues, "collectVariadicOptionValues");
|
|
825
|
+
|
|
826
|
+
// src/lib/helpers/findCommand.ts
|
|
827
|
+
function findCommand(cmd, nameOrAlias) {
|
|
828
|
+
return cmd.commands[nameOrAlias] ?? valuesOf(cmd.commands).find((c) => {
|
|
829
|
+
return c.aliases.includes(nameOrAlias);
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
__name(findCommand, "findCommand");
|
|
833
|
+
|
|
834
|
+
// src/lib/helpers/findOption.ts
|
|
835
|
+
function findOption(cmd, nameOrShortOrLong) {
|
|
836
|
+
return nameOrShortOrLong.startsWith("--") ? cmd.options.find((o) => {
|
|
837
|
+
return o.long === nameOrShortOrLong.slice(2);
|
|
838
|
+
}) : nameOrShortOrLong.startsWith("-") ? cmd.options.find((o) => {
|
|
839
|
+
return o.short === nameOrShortOrLong.slice(1);
|
|
840
|
+
}) : cmd.options.find((o) => {
|
|
841
|
+
return o.name === nameOrShortOrLong;
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
__name(findOption, "findOption");
|
|
845
|
+
|
|
846
|
+
// src/lib/helpers/getCommandAndAncestors.ts
|
|
847
|
+
function getCommandAndAncestors(cmd) {
|
|
848
|
+
const result = [];
|
|
849
|
+
let command = cmd;
|
|
850
|
+
for (; command; command = command.parent) {
|
|
851
|
+
result.push(command);
|
|
852
|
+
}
|
|
853
|
+
return result;
|
|
854
|
+
}
|
|
855
|
+
__name(getCommandAndAncestors, "getCommandAndAncestors");
|
|
856
|
+
|
|
857
|
+
// src/lib/helpers/getCommandAncestors.ts
|
|
858
|
+
function getCommandAncestors(cmd) {
|
|
859
|
+
return getCommandAndAncestors(cmd).slice(1);
|
|
860
|
+
}
|
|
861
|
+
__name(getCommandAncestors, "getCommandAncestors");
|
|
862
|
+
|
|
863
|
+
// src/lib/internal/mergeOptionDefaults.ts
|
|
864
|
+
function mergeOptionDefaults(values, options) {
|
|
865
|
+
for (const option of options) {
|
|
866
|
+
if (option.defaultValue !== void 0 && option.name in values) {
|
|
867
|
+
values[option.name] ??= option.defaultValue;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
__name(mergeOptionDefaults, "mergeOptionDefaults");
|
|
872
|
+
|
|
873
|
+
// src/lib/internal/normalizeArgv.ts
|
|
874
|
+
function normalizeArgv(argv, options) {
|
|
875
|
+
for (const o of options) {
|
|
876
|
+
if (o.long === o.name) {
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
argv = argv.map((a) => {
|
|
880
|
+
if (a === `--${o.long}`) {
|
|
881
|
+
return `--${o.name}`;
|
|
882
|
+
}
|
|
883
|
+
if (a === `--no-${o.long}`) {
|
|
884
|
+
return `--no-${o.name}`;
|
|
885
|
+
}
|
|
886
|
+
return a;
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
return argv;
|
|
890
|
+
}
|
|
891
|
+
__name(normalizeArgv, "normalizeArgv");
|
|
892
|
+
|
|
893
|
+
// src/lib/helpers/parseOptionFlags.ts
|
|
894
|
+
function parseOptionFlags(flags) {
|
|
895
|
+
const match = flags.match(/^-(.+?), --([A-Za-z][\w-]*)(?:\s*(<(.+?)>|\[(.+?)]))?$/);
|
|
896
|
+
if (!match) {
|
|
897
|
+
throw new Error(`Invalid option format: ${flags}`);
|
|
898
|
+
}
|
|
899
|
+
const short = match[1];
|
|
900
|
+
if (short.length !== 1) {
|
|
901
|
+
throw new Error(`Expected short name to be a single character. Got: -${short}`);
|
|
902
|
+
}
|
|
903
|
+
const long = match[2];
|
|
904
|
+
const argName = (match[4] || match[5])?.replace(/\.{3}$/, "") || void 0;
|
|
905
|
+
const name = long.split("-").reduce((str, word) => {
|
|
906
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
907
|
+
});
|
|
908
|
+
return {
|
|
909
|
+
short,
|
|
910
|
+
long,
|
|
911
|
+
name,
|
|
912
|
+
argName
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
__name(parseOptionFlags, "parseOptionFlags");
|
|
916
|
+
function resolveArguments(positionals, args) {
|
|
917
|
+
const result = args.map((arg, index) => {
|
|
918
|
+
if (arg.variadic) {
|
|
919
|
+
const remaining = positionals.slice(index);
|
|
920
|
+
return remaining.length > 0 ? remaining : arg.defaultValue;
|
|
921
|
+
}
|
|
922
|
+
return positionals[index] ?? arg.defaultValue;
|
|
923
|
+
});
|
|
924
|
+
while (result.length && last(result) === void 0) {
|
|
925
|
+
result.pop();
|
|
926
|
+
}
|
|
927
|
+
return result;
|
|
928
|
+
}
|
|
929
|
+
__name(resolveArguments, "resolveArguments");
|
|
930
|
+
|
|
931
|
+
// ../fn/src/setName.ts
|
|
932
|
+
function setName(name, target) {
|
|
933
|
+
return Object.defineProperty(target, "name", {
|
|
934
|
+
value: typeof name === "string" ? name : name.name,
|
|
935
|
+
configurable: true,
|
|
936
|
+
enumerable: false
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
__name(setName, "setName");
|
|
940
|
+
function createLogger(name) {
|
|
941
|
+
const NAME = name ? C.dim.cyan(name) : name;
|
|
942
|
+
const START = [
|
|
943
|
+
NAME,
|
|
944
|
+
C.dim.gray("[START]")
|
|
945
|
+
].filter(Boolean);
|
|
946
|
+
const DEBUG = [
|
|
947
|
+
NAME,
|
|
948
|
+
C.dim.magenta("[DEBUG]")
|
|
949
|
+
].filter(Boolean);
|
|
950
|
+
const INFO = [
|
|
951
|
+
NAME,
|
|
952
|
+
C.dim.gray("[INFO]")
|
|
953
|
+
].filter(Boolean);
|
|
954
|
+
const DONE = [
|
|
955
|
+
NAME,
|
|
956
|
+
C.dim.green("[DONE] ")
|
|
957
|
+
].filter(Boolean);
|
|
958
|
+
const WARN = [
|
|
959
|
+
NAME,
|
|
960
|
+
C.dim.yellow("[WARN] ")
|
|
961
|
+
].filter(Boolean);
|
|
962
|
+
const ERROR = [
|
|
963
|
+
NAME,
|
|
964
|
+
C.dim.red("[ERROR]")
|
|
965
|
+
].filter(Boolean);
|
|
966
|
+
const grayArgs = createColoredArgs(C.gray);
|
|
967
|
+
const cyanArgs = createColoredArgs(C.cyan);
|
|
968
|
+
const yellowArgs = createColoredArgs(C.yellow);
|
|
969
|
+
return {
|
|
970
|
+
start: /* @__PURE__ */ __name((...args) => {
|
|
971
|
+
return console.info(...START, ...args);
|
|
972
|
+
}, "start"),
|
|
973
|
+
done: /* @__PURE__ */ __name((...args) => {
|
|
974
|
+
return console.info(...DONE, ...args);
|
|
975
|
+
}, "done"),
|
|
976
|
+
info: /* @__PURE__ */ __name((...args) => {
|
|
977
|
+
return console.info(...INFO, ...grayArgs(args));
|
|
978
|
+
}, "info"),
|
|
979
|
+
log: /* @__PURE__ */ __name((...args) => {
|
|
980
|
+
return console.log(...NAME ? [
|
|
981
|
+
NAME,
|
|
982
|
+
...args
|
|
983
|
+
] : args);
|
|
984
|
+
}, "log"),
|
|
985
|
+
warn: /* @__PURE__ */ __name((...args) => {
|
|
986
|
+
return console.warn(...WARN, ...yellowArgs(args));
|
|
987
|
+
}, "warn"),
|
|
988
|
+
debug: /* @__PURE__ */ __name((...args) => {
|
|
989
|
+
return console.debug(...DEBUG, ...cyanArgs(args));
|
|
990
|
+
}, "debug"),
|
|
991
|
+
error: /* @__PURE__ */ __name((...args) => {
|
|
992
|
+
return args.forEach((arg) => {
|
|
993
|
+
return console.error(...ERROR, arg);
|
|
994
|
+
});
|
|
995
|
+
}, "error")
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
__name(createLogger, "createLogger");
|
|
999
|
+
function createColoredArgs(colorFn) {
|
|
1000
|
+
return (args) => {
|
|
1001
|
+
return args.map((arg) => {
|
|
1002
|
+
if (isString(arg)) {
|
|
1003
|
+
return arg === C.stripColor(arg) ? colorFn(arg) : arg;
|
|
1004
|
+
} else if (isPrimitive(arg)) {
|
|
1005
|
+
return colorFn(String(arg));
|
|
1006
|
+
} else {
|
|
1007
|
+
return arg;
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
__name(createColoredArgs, "createColoredArgs");
|
|
1013
|
+
function timer(arg, task) {
|
|
1014
|
+
const t0 = process.hrtime.bigint();
|
|
1015
|
+
const [name, description] = Array.isArray(arg) ? arg : [
|
|
1016
|
+
arg,
|
|
1017
|
+
""
|
|
1018
|
+
];
|
|
1019
|
+
const log = createLogger(name);
|
|
1020
|
+
if (name && description) {
|
|
1021
|
+
log.start(description);
|
|
1022
|
+
}
|
|
1023
|
+
const retval = task(log, name);
|
|
1024
|
+
if (!isPromise(retval)) {
|
|
1025
|
+
return done(retval);
|
|
1026
|
+
}
|
|
1027
|
+
return retval.then((result) => {
|
|
1028
|
+
return done(result);
|
|
1029
|
+
});
|
|
1030
|
+
function done(retval2) {
|
|
1031
|
+
if (process.exitCode) {
|
|
1032
|
+
return retval2;
|
|
1033
|
+
}
|
|
1034
|
+
const ns = process.hrtime.bigint() - t0;
|
|
1035
|
+
const ms3 = Math.floor(Number(ns) / 1e6);
|
|
1036
|
+
log.done(C.dim(humanizeDuration(ms3)));
|
|
1037
|
+
return retval2;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
__name(timer, "timer");
|
|
1041
|
+
|
|
1042
|
+
// src/lib/internal/validateParsed.ts
|
|
1043
|
+
function validateParsed(args, optionValues, argDefs, optionDefs) {
|
|
1044
|
+
return argDefs.map((def, index) => {
|
|
1045
|
+
const value = args[index];
|
|
1046
|
+
if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
|
|
1047
|
+
return `Missing argument [${index}] ${def.usage}`;
|
|
1048
|
+
}
|
|
1049
|
+
if (def.choices && value !== void 0 && ![
|
|
1050
|
+
value
|
|
1051
|
+
].flat().every((v) => {
|
|
1052
|
+
return def.choices.includes(v);
|
|
1053
|
+
})) {
|
|
1054
|
+
return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
|
|
1055
|
+
return `\`${c}\``;
|
|
1056
|
+
}).join(",")}]`;
|
|
1057
|
+
}
|
|
1058
|
+
}).concat(entriesOf(optionValues).map(([key, value]) => {
|
|
1059
|
+
const def = optionDefs.find((o) => {
|
|
1060
|
+
return o.name === key;
|
|
1061
|
+
});
|
|
1062
|
+
if (!def) {
|
|
1063
|
+
return `Unknown option --${key}`;
|
|
1064
|
+
}
|
|
1065
|
+
if (def.choices && value !== void 0 && !(def.variadic ? value : [
|
|
1066
|
+
value
|
|
1067
|
+
]).every((v) => {
|
|
1068
|
+
return def.choices.includes(v);
|
|
1069
|
+
})) {
|
|
1070
|
+
return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
|
|
1071
|
+
return `\`${c}\``;
|
|
1072
|
+
}).join(",")}]`;
|
|
1073
|
+
}
|
|
1074
|
+
})).filter((s) => {
|
|
1075
|
+
return s !== void 0;
|
|
1076
|
+
}).reduce((acc, curr) => {
|
|
1077
|
+
return (acc ?? []).concat(curr);
|
|
1078
|
+
}, void 0);
|
|
1079
|
+
}
|
|
1080
|
+
__name(validateParsed, "validateParsed");
|
|
1081
|
+
|
|
1082
|
+
// src/lib/Command.ts
|
|
1083
|
+
function _ts_decorate2(decorators, target, key, desc) {
|
|
1084
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
1085
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
1086
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
1087
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
1088
|
+
}
|
|
1089
|
+
__name(_ts_decorate2, "_ts_decorate");
|
|
1090
|
+
function _ts_metadata2(k, v) {
|
|
1091
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
1092
|
+
}
|
|
1093
|
+
__name(_ts_metadata2, "_ts_metadata");
|
|
1094
|
+
var Command = class _Command {
|
|
1095
|
+
static {
|
|
1096
|
+
__name(this, "Command");
|
|
1097
|
+
}
|
|
1098
|
+
/** parent command in the hierarchy, undefined for root command */
|
|
1099
|
+
parent;
|
|
1100
|
+
/** the command name used to invoke it */
|
|
1101
|
+
name;
|
|
1102
|
+
/** semantic version string displayed by --version flag */
|
|
1103
|
+
version;
|
|
1104
|
+
/** alternative names for invoking this command */
|
|
1105
|
+
aliases;
|
|
1106
|
+
/** brief one-line description shown in command lists */
|
|
1107
|
+
summary;
|
|
1108
|
+
/** full description displayed in help text */
|
|
1109
|
+
description;
|
|
1110
|
+
/** whether to exclude from help listings */
|
|
1111
|
+
hidden;
|
|
1112
|
+
/** category for organizing related commands in help output */
|
|
1113
|
+
group;
|
|
1114
|
+
/** positional arguments this command accepts */
|
|
1115
|
+
arguments;
|
|
1116
|
+
/** cLI options (flags) this command recognizes */
|
|
1117
|
+
options;
|
|
1118
|
+
/** subcommands registered with this command */
|
|
1119
|
+
commands;
|
|
1120
|
+
/** main action handler executed when command is invoked */
|
|
1121
|
+
action;
|
|
1122
|
+
/** option-driven actions (e.g., --help, --version) executed when their conditions match */
|
|
1123
|
+
hooks;
|
|
1124
|
+
constructor(name, parent) {
|
|
1125
|
+
this.name = name;
|
|
1126
|
+
this.aliases = [];
|
|
1127
|
+
this.description = "";
|
|
1128
|
+
this.arguments = [];
|
|
1129
|
+
this.options = [];
|
|
1130
|
+
this.commands = {};
|
|
1131
|
+
this.hooks = [];
|
|
1132
|
+
Object.defineProperty(this, "parent", {
|
|
1133
|
+
value: parent,
|
|
1134
|
+
enumerable: false
|
|
1135
|
+
});
|
|
1136
|
+
if (!parent) {
|
|
1137
|
+
this.addOption("-D, --debug", {
|
|
1138
|
+
description: "Display debug information"
|
|
1139
|
+
}).addOptionHook("debug", ({ cmd, ...data }) => {
|
|
1140
|
+
console.debug(inspect(cmd, {
|
|
1141
|
+
depth: 1,
|
|
1142
|
+
colors: true
|
|
1143
|
+
}));
|
|
1144
|
+
console.debug(inspect(data, {
|
|
1145
|
+
depth: 3,
|
|
1146
|
+
colors: true
|
|
1147
|
+
}));
|
|
1148
|
+
});
|
|
1149
|
+
this.addOption("-h, --help", {
|
|
1150
|
+
description: "Display help information"
|
|
1151
|
+
}).addOptionHook("help", ({ cmd }) => {
|
|
1152
|
+
console.log(cmd.renderHelp());
|
|
1153
|
+
process.exitCode = 0;
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
get help() {
|
|
1158
|
+
return new Help(this);
|
|
1159
|
+
}
|
|
1160
|
+
/** configure how the help is rendered */
|
|
1161
|
+
helpConfiguration(cb) {
|
|
1162
|
+
const help = this.help;
|
|
1163
|
+
cb?.(help);
|
|
1164
|
+
return this;
|
|
1165
|
+
}
|
|
1166
|
+
/** renders formatted help text using provided help definition */
|
|
1167
|
+
renderHelp(config = {}) {
|
|
1168
|
+
const result = this.help.render();
|
|
1169
|
+
return config.noColor ? C.stripColor(result) : result;
|
|
1170
|
+
}
|
|
1171
|
+
/** sets the command name */
|
|
1172
|
+
setName(name) {
|
|
1173
|
+
this.name = name;
|
|
1174
|
+
}
|
|
1175
|
+
/** sets command aliases, flattening nested arrays */
|
|
1176
|
+
setAliases(...aliases) {
|
|
1177
|
+
this.aliases = [];
|
|
1178
|
+
this.addAliases(...aliases);
|
|
1179
|
+
return this;
|
|
1180
|
+
}
|
|
1181
|
+
/** adds aliases to existing ones */
|
|
1182
|
+
addAliases(...aliases) {
|
|
1183
|
+
const taken = this.parent ? valuesOf(this.parent.commands).flatMap((c) => {
|
|
1184
|
+
return [
|
|
1185
|
+
c.name,
|
|
1186
|
+
...c.aliases
|
|
1187
|
+
];
|
|
1188
|
+
}) : [];
|
|
1189
|
+
uniq(aliases.flat()).filter((a) => {
|
|
1190
|
+
return !this.aliases.includes(a) && a !== this.name;
|
|
1191
|
+
}).forEach((a) => {
|
|
1192
|
+
if (taken.includes(a)) {
|
|
1193
|
+
throw new Error(`Alias "${a}" is already used by a sibling command: ${findCommand(this.parent, a)?.name}`);
|
|
1194
|
+
}
|
|
1195
|
+
this.aliases.push(a);
|
|
1196
|
+
});
|
|
1197
|
+
this.aliases.sort((a, b) => {
|
|
1198
|
+
return a.length - b.length;
|
|
1199
|
+
});
|
|
1200
|
+
return this;
|
|
1201
|
+
}
|
|
1202
|
+
/** sets the command version */
|
|
1203
|
+
setVersion(version) {
|
|
1204
|
+
this.version = version;
|
|
1205
|
+
if (findOption(this, "version")) {
|
|
1206
|
+
return this;
|
|
1207
|
+
}
|
|
1208
|
+
return this.addOption("-V, --version", {
|
|
1209
|
+
description: "Display semver version"
|
|
1210
|
+
}).addOptionHook("version", ({ cmd }) => {
|
|
1211
|
+
console.log(getCommandAndAncestors(cmd).find((c) => {
|
|
1212
|
+
return c.version;
|
|
1213
|
+
})?.version);
|
|
1214
|
+
process.exitCode = 0;
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
/** sets the command summary */
|
|
1218
|
+
setSummary(summary) {
|
|
1219
|
+
this.summary = summary;
|
|
1220
|
+
return this;
|
|
1221
|
+
}
|
|
1222
|
+
/** sets command description, joining variadic lines */
|
|
1223
|
+
setDescription(...lines) {
|
|
1224
|
+
this.description = lines.join("\n");
|
|
1225
|
+
return this;
|
|
1226
|
+
}
|
|
1227
|
+
/** sets whether command is hidden from help */
|
|
1228
|
+
setHidden(hidden = true) {
|
|
1229
|
+
this.hidden = hidden;
|
|
1230
|
+
return this;
|
|
1231
|
+
}
|
|
1232
|
+
/** sets the command group for help organization */
|
|
1233
|
+
setGroup(group) {
|
|
1234
|
+
this.group = group;
|
|
1235
|
+
return this;
|
|
1236
|
+
}
|
|
1237
|
+
/** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
|
|
1238
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1239
|
+
command(name, cb) {
|
|
1240
|
+
if (this.arguments.length) {
|
|
1241
|
+
throw new Error(`Cannot add subcommand "${name}" to "${this.name}" because it already has arguments defined.`);
|
|
1242
|
+
}
|
|
1243
|
+
const sub = this.createSubcommand(name);
|
|
1244
|
+
const inherit = this.options;
|
|
1245
|
+
sub.options.push(...inherit);
|
|
1246
|
+
const inheritHooks = this.hooks.filter((t) => {
|
|
1247
|
+
return inherit.some((i) => {
|
|
1248
|
+
return i.name === t.name;
|
|
1249
|
+
});
|
|
1250
|
+
});
|
|
1251
|
+
sub.hooks.push(...inheritHooks);
|
|
1252
|
+
const taken = valuesOf(this.commands).flatMap((c) => {
|
|
1253
|
+
return [
|
|
1254
|
+
c.name,
|
|
1255
|
+
...c.aliases
|
|
1256
|
+
];
|
|
1257
|
+
});
|
|
1258
|
+
if (taken.includes(name)) {
|
|
1259
|
+
throw new Error(`Command name "${getCommandAndAncestors(sub).map((c) => {
|
|
1260
|
+
return c.name;
|
|
1261
|
+
})}" is already used by this command or its aliases: ${taken.join(", ")}`);
|
|
1262
|
+
}
|
|
1263
|
+
const kebab = kebabCase(name);
|
|
1264
|
+
const words = kebab.split("-");
|
|
1265
|
+
const initials = words.map((s) => {
|
|
1266
|
+
return s[0];
|
|
1267
|
+
}).join("");
|
|
1268
|
+
if (taken.includes(initials)) {
|
|
1269
|
+
const initials2 = words.map((s) => {
|
|
1270
|
+
return s[0] + s[1];
|
|
1271
|
+
}).join("");
|
|
1272
|
+
if (!taken.includes(initials2)) {
|
|
1273
|
+
sub.addAliases(initials2);
|
|
1274
|
+
}
|
|
1275
|
+
} else {
|
|
1276
|
+
sub.addAliases(initials);
|
|
1277
|
+
}
|
|
1278
|
+
this.commands[name] = sub;
|
|
1279
|
+
return cb ? cb(sub, this) : sub;
|
|
1280
|
+
}
|
|
1281
|
+
/** add a subcommand and return the subcommand. All options are inherited by the subcommand. */
|
|
1282
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1283
|
+
addCommand(name, cb) {
|
|
1284
|
+
this.command(name, cb);
|
|
1285
|
+
return this;
|
|
1286
|
+
}
|
|
1287
|
+
// implementation
|
|
1288
|
+
addArgument(usage, options = {}) {
|
|
1289
|
+
if (!/^<(.*?)>$|^\[(.*?)]$/.test(usage)) {
|
|
1290
|
+
throw new Error(`Invalid argument format: ${usage}`);
|
|
1291
|
+
}
|
|
1292
|
+
const name = usage.slice(1, -1).replace(/\.{3}$/, "");
|
|
1293
|
+
const required = usage.startsWith("<");
|
|
1294
|
+
const variadic = usage.slice(0, -1).endsWith("...");
|
|
1295
|
+
const prevArg = this.arguments[this.arguments.length - 1];
|
|
1296
|
+
if (prevArg?.variadic) {
|
|
1297
|
+
throw new Error(`Cannot add argument ${usage} after variadic argument ${prevArg.usage}`);
|
|
1298
|
+
}
|
|
1299
|
+
if (required && prevArg && !prevArg?.required) {
|
|
1300
|
+
throw new Error(`Cannot add required argument ${usage} after optional argument ${prevArg?.usage}`);
|
|
1301
|
+
}
|
|
1302
|
+
if (required && prevArg?.defaultValue) {
|
|
1303
|
+
throw new Error(`Cannot add required argument ${usage} after optional argument with default value ${prevArg.usage}`);
|
|
1304
|
+
}
|
|
1305
|
+
const arg = {
|
|
1306
|
+
usage,
|
|
1307
|
+
name,
|
|
1308
|
+
required,
|
|
1309
|
+
variadic,
|
|
1310
|
+
...options
|
|
1311
|
+
};
|
|
1312
|
+
if (variadic && !arg.defaultValue) {
|
|
1313
|
+
arg.defaultValue = [];
|
|
1314
|
+
}
|
|
1315
|
+
this.arguments.push(arg);
|
|
1316
|
+
return this;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
|
|
1320
|
+
*/
|
|
1321
|
+
addOption(flags, opts = {}) {
|
|
1322
|
+
const ins = {};
|
|
1323
|
+
const { short, long, name, argName } = parseOptionFlags(flags);
|
|
1324
|
+
for (const opt of this.options) {
|
|
1325
|
+
if (opt.long === long) {
|
|
1326
|
+
throw new Error(`Option long name, --${long} already in use by: ${opt.flags}`);
|
|
1327
|
+
}
|
|
1328
|
+
if (opt.short === short) {
|
|
1329
|
+
throw new Error(`Option short name, -${short} already in use by: ${opt.flags}`);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
ins.flags = flags;
|
|
1333
|
+
ins.short = short;
|
|
1334
|
+
ins.long = long;
|
|
1335
|
+
ins.name = name;
|
|
1336
|
+
ins.description = "";
|
|
1337
|
+
if (argName) {
|
|
1338
|
+
ins.type = "string";
|
|
1339
|
+
ins.argName = argName;
|
|
1340
|
+
if (flags.endsWith(">")) {
|
|
1341
|
+
if (flags.endsWith("...>")) {
|
|
1342
|
+
ins.required = true;
|
|
1343
|
+
ins.variadic = true;
|
|
1344
|
+
} else {
|
|
1345
|
+
ins.required = true;
|
|
1346
|
+
}
|
|
1347
|
+
} else if (flags.endsWith("]") && flags.endsWith("...]")) {
|
|
1348
|
+
ins.variadic = true;
|
|
1349
|
+
ins.defaultValue = opts.defaultValue ?? [];
|
|
1350
|
+
}
|
|
1351
|
+
} else {
|
|
1352
|
+
ins.type = "boolean";
|
|
1353
|
+
}
|
|
1354
|
+
for (const [key, value] of Object.entries(opts)) {
|
|
1355
|
+
if (value !== void 0) {
|
|
1356
|
+
Reflect.set(ins, key, value);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
|
|
1360
|
+
ins.required = false;
|
|
1361
|
+
ins.flags = ins.flags.replace("<", "[").replace(">", "]");
|
|
1362
|
+
if (ins.type === "boolean") {
|
|
1363
|
+
ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
|
|
1364
|
+
} else if (ins.variadic) {
|
|
1365
|
+
ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => {
|
|
1366
|
+
return v.trim();
|
|
1367
|
+
});
|
|
1368
|
+
} else {
|
|
1369
|
+
ins.defaultValue = process.env[ins.env];
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
this.options.push(ins);
|
|
1373
|
+
return this;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* register an action to be invoked when an option is set to true or string value.
|
|
1377
|
+
*
|
|
1378
|
+
* Hooks execute in addition to or instead of the main action handler,
|
|
1379
|
+
* allowing for option-driven behavior. For example, `--help` and `--version`
|
|
1380
|
+
* are implemented as hooks.
|
|
1381
|
+
*/
|
|
1382
|
+
addOptionHook(optionName, action) {
|
|
1383
|
+
const def = findOption(this, optionName);
|
|
1384
|
+
if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
|
|
1385
|
+
def.group = "Command Options";
|
|
1386
|
+
}
|
|
1387
|
+
this.hooks.push({
|
|
1388
|
+
name: optionName,
|
|
1389
|
+
predicate: setName(`has${upperFirst(optionName)}`, ({ opts }) => {
|
|
1390
|
+
return opts[optionName] !== void 0 && opts[optionName] !== false && !(Array.isArray(opts[optionName]) && opts[optionName].length === 0);
|
|
1391
|
+
}),
|
|
1392
|
+
action: setName(optionName, action)
|
|
1393
|
+
});
|
|
1394
|
+
return this;
|
|
1395
|
+
}
|
|
1396
|
+
/** parses command-line arguments with subcommand support and type-safe validation. */
|
|
1397
|
+
parseArgv(argv = process.argv.slice(2)) {
|
|
1398
|
+
const sub = findCommand(this, argv[0]);
|
|
1399
|
+
if (sub) {
|
|
1400
|
+
return sub.parseArgv(argv.slice(1));
|
|
1401
|
+
}
|
|
1402
|
+
argv = normalizeArgv(argv, this.options);
|
|
1403
|
+
const parsed = parseArgs({
|
|
1404
|
+
args: argv,
|
|
1405
|
+
options: Object.fromEntries(this.options.map((o) => {
|
|
1406
|
+
return [
|
|
1407
|
+
o.name,
|
|
1408
|
+
{
|
|
1409
|
+
type: o.type,
|
|
1410
|
+
short: o.short,
|
|
1411
|
+
default: o.defaultValue,
|
|
1412
|
+
multiple: !!o.variadic
|
|
1413
|
+
}
|
|
1414
|
+
];
|
|
1415
|
+
})),
|
|
1416
|
+
allowPositionals: true,
|
|
1417
|
+
tokens: true,
|
|
1418
|
+
strict: false,
|
|
1419
|
+
allowNegative: true
|
|
1420
|
+
});
|
|
1421
|
+
collectVariadicOptionValues(parsed, this.options);
|
|
1422
|
+
mergeOptionDefaults(parsed.values, this.options);
|
|
1423
|
+
parsed.values = objSortKeys(parsed.values, (a, b) => {
|
|
1424
|
+
return a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0;
|
|
1425
|
+
});
|
|
1426
|
+
const args = resolveArguments(parsed.positionals, this.arguments);
|
|
1427
|
+
const opts = filterObject(parsed.values, (value) => {
|
|
1428
|
+
return value !== void 0;
|
|
1429
|
+
});
|
|
1430
|
+
const errors = validateParsed(args, parsed.values, this.arguments, this.options);
|
|
1431
|
+
const path = getCommandAncestors(this).map((c) => {
|
|
1432
|
+
return c.name;
|
|
1433
|
+
});
|
|
1434
|
+
const data = {
|
|
1435
|
+
path,
|
|
1436
|
+
name: this.name,
|
|
1437
|
+
argv,
|
|
1438
|
+
args,
|
|
1439
|
+
opts,
|
|
1440
|
+
errors,
|
|
1441
|
+
cmd: this
|
|
1442
|
+
};
|
|
1443
|
+
const hooks = this.hooks.filter((t) => {
|
|
1444
|
+
return t.predicate(data);
|
|
1445
|
+
});
|
|
1446
|
+
const execute = /* @__PURE__ */ __name(async () => {
|
|
1447
|
+
for (const hook of hooks) {
|
|
1448
|
+
await hook.action(data);
|
|
1449
|
+
if (process.exitCode !== void 0) {
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
await timer([
|
|
1454
|
+
[
|
|
1455
|
+
...path,
|
|
1456
|
+
this.name
|
|
1457
|
+
].join(" "),
|
|
1458
|
+
this.description
|
|
1459
|
+
], async (logger) => {
|
|
1460
|
+
if (errors) {
|
|
1461
|
+
errors.forEach((msg) => {
|
|
1462
|
+
return logger.error(C.red(msg));
|
|
1463
|
+
});
|
|
1464
|
+
process.exitCode = 1;
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
if (this.action) {
|
|
1468
|
+
return await this.action(...args, opts, {
|
|
1469
|
+
...data,
|
|
1470
|
+
args,
|
|
1471
|
+
opts,
|
|
1472
|
+
cmd: this,
|
|
1473
|
+
logger
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
console.log(this.renderHelp());
|
|
1477
|
+
});
|
|
1478
|
+
}, "execute");
|
|
1479
|
+
return {
|
|
1480
|
+
...data,
|
|
1481
|
+
hooks,
|
|
1482
|
+
execute
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
|
|
1487
|
+
* The handler receives parsed arguments and options with correct typings.
|
|
1488
|
+
*/
|
|
1489
|
+
setAction(fn) {
|
|
1490
|
+
this.action = setName(this.name, fn);
|
|
1491
|
+
return this;
|
|
1492
|
+
}
|
|
1493
|
+
/** returns a new Command instance. Override this method in subclasses. */
|
|
1494
|
+
createSubcommand(name) {
|
|
1495
|
+
return new _Command(name, this);
|
|
1496
|
+
}
|
|
1497
|
+
};
|
|
1498
|
+
_ts_decorate2([
|
|
1499
|
+
lazyProp,
|
|
1500
|
+
_ts_metadata2("design:type", typeof Help === "undefined" ? Object : Help),
|
|
1501
|
+
_ts_metadata2("design:paramtypes", [])
|
|
1502
|
+
], Command.prototype, "help", null);
|
|
1503
|
+
|
|
1504
|
+
export { Command, Help, findCommand, findOption, getCommandAncestors, getCommandAndAncestors, parseOptionFlags };
|