@monoedge/jdu-cli 0.1.0
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/LICENSE +21 -0
- package/README.md +28 -0
- package/dist/cli.js +4055 -0
- package/package.json +43 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,4055 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import childProcess, { spawn } from "node:child_process";
|
|
4
|
+
import path, { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import fs, { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
+
import process$1 from "node:process";
|
|
7
|
+
import { stripVTControlCharacters } from "node:util";
|
|
8
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { createServer } from "node:http";
|
|
11
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
12
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
|
|
13
|
+
/**
|
|
14
|
+
* CommanderError class
|
|
15
|
+
*/
|
|
16
|
+
var CommanderError = class extends Error {
|
|
17
|
+
/**
|
|
18
|
+
* Constructs the CommanderError class
|
|
19
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
20
|
+
* @param {string} code an id string representing the error
|
|
21
|
+
* @param {string} message human-readable description of the error
|
|
22
|
+
*/
|
|
23
|
+
constructor(exitCode, code, message) {
|
|
24
|
+
super(message);
|
|
25
|
+
Error.captureStackTrace(this, this.constructor);
|
|
26
|
+
this.name = this.constructor.name;
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.exitCode = exitCode;
|
|
29
|
+
this.nestedError = void 0;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* InvalidArgumentError class
|
|
34
|
+
*/
|
|
35
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
36
|
+
/**
|
|
37
|
+
* Constructs the InvalidArgumentError class
|
|
38
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
39
|
+
*/
|
|
40
|
+
constructor(message) {
|
|
41
|
+
super(1, "commander.invalidArgument", message);
|
|
42
|
+
Error.captureStackTrace(this, this.constructor);
|
|
43
|
+
this.name = this.constructor.name;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
|
|
48
|
+
var Argument = class {
|
|
49
|
+
/**
|
|
50
|
+
* Initialize a new command argument with the given name and description.
|
|
51
|
+
* The default is that the argument is required, and you can explicitly
|
|
52
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} name
|
|
55
|
+
* @param {string} [description]
|
|
56
|
+
*/
|
|
57
|
+
constructor(name, description) {
|
|
58
|
+
this.description = description || "";
|
|
59
|
+
this.variadic = false;
|
|
60
|
+
this.parseArg = void 0;
|
|
61
|
+
this.defaultValue = void 0;
|
|
62
|
+
this.defaultValueDescription = void 0;
|
|
63
|
+
this.argChoices = void 0;
|
|
64
|
+
switch (name[0]) {
|
|
65
|
+
case "<":
|
|
66
|
+
this.required = true;
|
|
67
|
+
this._name = name.slice(1, -1);
|
|
68
|
+
break;
|
|
69
|
+
case "[":
|
|
70
|
+
this.required = false;
|
|
71
|
+
this._name = name.slice(1, -1);
|
|
72
|
+
break;
|
|
73
|
+
default:
|
|
74
|
+
this.required = true;
|
|
75
|
+
this._name = name;
|
|
76
|
+
}
|
|
77
|
+
if (this._name.endsWith("...")) {
|
|
78
|
+
this.variadic = true;
|
|
79
|
+
this._name = this._name.slice(0, -3);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Return argument name.
|
|
84
|
+
*
|
|
85
|
+
* @return {string}
|
|
86
|
+
*/
|
|
87
|
+
name() {
|
|
88
|
+
return this._name;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* @package
|
|
92
|
+
*/
|
|
93
|
+
_collectValue(value, previous) {
|
|
94
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
95
|
+
previous.push(value);
|
|
96
|
+
return previous;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
100
|
+
*
|
|
101
|
+
* @param {*} value
|
|
102
|
+
* @param {string} [description]
|
|
103
|
+
* @return {Argument}
|
|
104
|
+
*/
|
|
105
|
+
default(value, description) {
|
|
106
|
+
this.defaultValue = value;
|
|
107
|
+
this.defaultValueDescription = description;
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
112
|
+
*
|
|
113
|
+
* @param {Function} [fn]
|
|
114
|
+
* @return {Argument}
|
|
115
|
+
*/
|
|
116
|
+
argParser(fn) {
|
|
117
|
+
this.parseArg = fn;
|
|
118
|
+
return this;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Only allow argument value to be one of choices.
|
|
122
|
+
*
|
|
123
|
+
* @param {string[]} values
|
|
124
|
+
* @return {Argument}
|
|
125
|
+
*/
|
|
126
|
+
choices(values) {
|
|
127
|
+
this.argChoices = values.slice();
|
|
128
|
+
this.parseArg = (arg, previous) => {
|
|
129
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
130
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
131
|
+
return arg;
|
|
132
|
+
};
|
|
133
|
+
return this;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Make argument required.
|
|
137
|
+
*
|
|
138
|
+
* @returns {Argument}
|
|
139
|
+
*/
|
|
140
|
+
argRequired() {
|
|
141
|
+
this.required = true;
|
|
142
|
+
return this;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Make argument optional.
|
|
146
|
+
*
|
|
147
|
+
* @returns {Argument}
|
|
148
|
+
*/
|
|
149
|
+
argOptional() {
|
|
150
|
+
this.required = false;
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* Takes an argument and returns its human readable equivalent for help usage.
|
|
156
|
+
*
|
|
157
|
+
* @param {Argument} arg
|
|
158
|
+
* @return {string}
|
|
159
|
+
* @private
|
|
160
|
+
*/
|
|
161
|
+
function humanReadableArgName(arg) {
|
|
162
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
163
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
|
|
167
|
+
/**
|
|
168
|
+
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
|
|
169
|
+
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
|
|
170
|
+
* @typedef { import("./argument.js").Argument } Argument
|
|
171
|
+
* @typedef { import("./command.js").Command } Command
|
|
172
|
+
* @typedef { import("./option.js").Option } Option
|
|
173
|
+
*/
|
|
174
|
+
var Help = class {
|
|
175
|
+
constructor() {
|
|
176
|
+
this.helpWidth = void 0;
|
|
177
|
+
this.minWidthToWrap = 40;
|
|
178
|
+
this.sortSubcommands = false;
|
|
179
|
+
this.sortOptions = false;
|
|
180
|
+
this.showGlobalOptions = false;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
184
|
+
* and just before calling `formatHelp()`.
|
|
185
|
+
*
|
|
186
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
187
|
+
*
|
|
188
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
189
|
+
*/
|
|
190
|
+
prepareContext(contextOptions) {
|
|
191
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
195
|
+
*
|
|
196
|
+
* @param {Command} cmd
|
|
197
|
+
* @returns {Command[]}
|
|
198
|
+
*/
|
|
199
|
+
visibleCommands(cmd) {
|
|
200
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
201
|
+
const helpCommand = cmd._getHelpCommand();
|
|
202
|
+
if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
|
|
203
|
+
if (this.sortSubcommands) visibleCommands.sort((a, b) => {
|
|
204
|
+
return a.name().localeCompare(b.name());
|
|
205
|
+
});
|
|
206
|
+
return visibleCommands;
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Compare options for sort.
|
|
210
|
+
*
|
|
211
|
+
* @param {Option} a
|
|
212
|
+
* @param {Option} b
|
|
213
|
+
* @returns {number}
|
|
214
|
+
*/
|
|
215
|
+
compareOptions(a, b) {
|
|
216
|
+
const getSortKey = (option) => {
|
|
217
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
218
|
+
};
|
|
219
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
223
|
+
*
|
|
224
|
+
* @param {Command} cmd
|
|
225
|
+
* @returns {Option[]}
|
|
226
|
+
*/
|
|
227
|
+
visibleOptions(cmd) {
|
|
228
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
229
|
+
const helpOption = cmd._getHelpOption();
|
|
230
|
+
if (helpOption && !helpOption.hidden) {
|
|
231
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
232
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
233
|
+
if (!removeShort && !removeLong) visibleOptions.push(helpOption);
|
|
234
|
+
else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
235
|
+
else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
236
|
+
}
|
|
237
|
+
if (this.sortOptions) visibleOptions.sort(this.compareOptions);
|
|
238
|
+
return visibleOptions;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Get an array of the visible global options. (Not including help.)
|
|
242
|
+
*
|
|
243
|
+
* @param {Command} cmd
|
|
244
|
+
* @returns {Option[]}
|
|
245
|
+
*/
|
|
246
|
+
visibleGlobalOptions(cmd) {
|
|
247
|
+
if (!this.showGlobalOptions) return [];
|
|
248
|
+
const globalOptions = [];
|
|
249
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
250
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
251
|
+
globalOptions.push(...visibleOptions);
|
|
252
|
+
}
|
|
253
|
+
if (this.sortOptions) globalOptions.sort(this.compareOptions);
|
|
254
|
+
return globalOptions;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Get an array of the arguments if any have a description.
|
|
258
|
+
*
|
|
259
|
+
* @param {Command} cmd
|
|
260
|
+
* @returns {Argument[]}
|
|
261
|
+
*/
|
|
262
|
+
visibleArguments(cmd) {
|
|
263
|
+
if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
|
|
264
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
265
|
+
});
|
|
266
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
|
|
267
|
+
return [];
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Get the command term to show in the list of subcommands.
|
|
271
|
+
*
|
|
272
|
+
* @param {Command} cmd
|
|
273
|
+
* @returns {string}
|
|
274
|
+
*/
|
|
275
|
+
subcommandTerm(cmd) {
|
|
276
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
277
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Get the option term to show in the list of options.
|
|
281
|
+
*
|
|
282
|
+
* @param {Option} option
|
|
283
|
+
* @returns {string}
|
|
284
|
+
*/
|
|
285
|
+
optionTerm(option) {
|
|
286
|
+
return option.flags;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Get the argument term to show in the list of arguments.
|
|
290
|
+
*
|
|
291
|
+
* @param {Argument} argument
|
|
292
|
+
* @returns {string}
|
|
293
|
+
*/
|
|
294
|
+
argumentTerm(argument) {
|
|
295
|
+
return argument.name();
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Get the longest command term length.
|
|
299
|
+
*
|
|
300
|
+
* @param {Command} cmd
|
|
301
|
+
* @param {Help} helper
|
|
302
|
+
* @returns {number}
|
|
303
|
+
*/
|
|
304
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
305
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
306
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
307
|
+
}, 0);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Get the longest option term length.
|
|
311
|
+
*
|
|
312
|
+
* @param {Command} cmd
|
|
313
|
+
* @param {Help} helper
|
|
314
|
+
* @returns {number}
|
|
315
|
+
*/
|
|
316
|
+
longestOptionTermLength(cmd, helper) {
|
|
317
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
318
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
319
|
+
}, 0);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Get the longest global option term length.
|
|
323
|
+
*
|
|
324
|
+
* @param {Command} cmd
|
|
325
|
+
* @param {Help} helper
|
|
326
|
+
* @returns {number}
|
|
327
|
+
*/
|
|
328
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
329
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
330
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
331
|
+
}, 0);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Get the longest argument term length.
|
|
335
|
+
*
|
|
336
|
+
* @param {Command} cmd
|
|
337
|
+
* @param {Help} helper
|
|
338
|
+
* @returns {number}
|
|
339
|
+
*/
|
|
340
|
+
longestArgumentTermLength(cmd, helper) {
|
|
341
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
342
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
343
|
+
}, 0);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
347
|
+
*
|
|
348
|
+
* @param {Command} cmd
|
|
349
|
+
* @returns {string}
|
|
350
|
+
*/
|
|
351
|
+
commandUsage(cmd) {
|
|
352
|
+
let cmdName = cmd._name;
|
|
353
|
+
if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
|
|
354
|
+
let ancestorCmdNames = "";
|
|
355
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
356
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Get the description for the command.
|
|
360
|
+
*
|
|
361
|
+
* @param {Command} cmd
|
|
362
|
+
* @returns {string}
|
|
363
|
+
*/
|
|
364
|
+
commandDescription(cmd) {
|
|
365
|
+
return cmd.description();
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
369
|
+
* (Fallback to description for backwards compatibility.)
|
|
370
|
+
*
|
|
371
|
+
* @param {Command} cmd
|
|
372
|
+
* @returns {string}
|
|
373
|
+
*/
|
|
374
|
+
subcommandDescription(cmd) {
|
|
375
|
+
return cmd.summary() || cmd.description();
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Get the option description to show in the list of options.
|
|
379
|
+
*
|
|
380
|
+
* @param {Option} option
|
|
381
|
+
* @return {string}
|
|
382
|
+
*/
|
|
383
|
+
optionDescription(option) {
|
|
384
|
+
const extraInfo = [];
|
|
385
|
+
if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
386
|
+
if (option.defaultValue !== void 0) {
|
|
387
|
+
if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
388
|
+
}
|
|
389
|
+
if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
390
|
+
if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
|
|
391
|
+
if (extraInfo.length > 0) {
|
|
392
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
393
|
+
if (option.description) return `${option.description} ${extraDescription}`;
|
|
394
|
+
return extraDescription;
|
|
395
|
+
}
|
|
396
|
+
return option.description;
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Get the argument description to show in the list of arguments.
|
|
400
|
+
*
|
|
401
|
+
* @param {Argument} argument
|
|
402
|
+
* @return {string}
|
|
403
|
+
*/
|
|
404
|
+
argumentDescription(argument) {
|
|
405
|
+
const extraInfo = [];
|
|
406
|
+
if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
407
|
+
if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
408
|
+
if (extraInfo.length > 0) {
|
|
409
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
410
|
+
if (argument.description) return `${argument.description} ${extraDescription}`;
|
|
411
|
+
return extraDescription;
|
|
412
|
+
}
|
|
413
|
+
return argument.description;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
417
|
+
*
|
|
418
|
+
* @param {string} heading
|
|
419
|
+
* @param {string[]} items
|
|
420
|
+
* @param {Help} helper
|
|
421
|
+
* @returns string[]
|
|
422
|
+
*/
|
|
423
|
+
formatItemList(heading, items, helper) {
|
|
424
|
+
if (items.length === 0) return [];
|
|
425
|
+
return [
|
|
426
|
+
helper.styleTitle(heading),
|
|
427
|
+
...items,
|
|
428
|
+
""
|
|
429
|
+
];
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Group items by their help group heading.
|
|
433
|
+
*
|
|
434
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
435
|
+
* @param {Command[] | Option[]} visibleItems
|
|
436
|
+
* @param {Function} getGroup
|
|
437
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
438
|
+
*/
|
|
439
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
440
|
+
const result = /* @__PURE__ */ new Map();
|
|
441
|
+
unsortedItems.forEach((item) => {
|
|
442
|
+
const group = getGroup(item);
|
|
443
|
+
if (!result.has(group)) result.set(group, []);
|
|
444
|
+
});
|
|
445
|
+
visibleItems.forEach((item) => {
|
|
446
|
+
const group = getGroup(item);
|
|
447
|
+
if (!result.has(group)) result.set(group, []);
|
|
448
|
+
result.get(group).push(item);
|
|
449
|
+
});
|
|
450
|
+
return result;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Generate the built-in help text.
|
|
454
|
+
*
|
|
455
|
+
* @param {Command} cmd
|
|
456
|
+
* @param {Help} helper
|
|
457
|
+
* @returns {string}
|
|
458
|
+
*/
|
|
459
|
+
formatHelp(cmd, helper) {
|
|
460
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
461
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
462
|
+
function callFormatItem(term, description) {
|
|
463
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
464
|
+
}
|
|
465
|
+
let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
|
|
466
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
467
|
+
if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
|
|
468
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
469
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
470
|
+
});
|
|
471
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
472
|
+
this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
|
|
473
|
+
const optionList = options.map((option) => {
|
|
474
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
475
|
+
});
|
|
476
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
477
|
+
});
|
|
478
|
+
if (helper.showGlobalOptions) {
|
|
479
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
480
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
481
|
+
});
|
|
482
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
483
|
+
}
|
|
484
|
+
this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
|
|
485
|
+
const commandList = commands.map((sub) => {
|
|
486
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
487
|
+
});
|
|
488
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
489
|
+
});
|
|
490
|
+
return output.join("\n");
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
494
|
+
*
|
|
495
|
+
* @param {string} str
|
|
496
|
+
* @returns {number}
|
|
497
|
+
*/
|
|
498
|
+
displayWidth(str) {
|
|
499
|
+
return stripVTControlCharacters(str).length;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
503
|
+
*
|
|
504
|
+
* @param {string} str
|
|
505
|
+
* @returns {string}
|
|
506
|
+
*/
|
|
507
|
+
styleTitle(str) {
|
|
508
|
+
return str;
|
|
509
|
+
}
|
|
510
|
+
styleUsage(str) {
|
|
511
|
+
return str.split(" ").map((word) => {
|
|
512
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
513
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
514
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
515
|
+
return this.styleCommandText(word);
|
|
516
|
+
}).join(" ");
|
|
517
|
+
}
|
|
518
|
+
styleCommandDescription(str) {
|
|
519
|
+
return this.styleDescriptionText(str);
|
|
520
|
+
}
|
|
521
|
+
styleOptionDescription(str) {
|
|
522
|
+
return this.styleDescriptionText(str);
|
|
523
|
+
}
|
|
524
|
+
styleSubcommandDescription(str) {
|
|
525
|
+
return this.styleDescriptionText(str);
|
|
526
|
+
}
|
|
527
|
+
styleArgumentDescription(str) {
|
|
528
|
+
return this.styleDescriptionText(str);
|
|
529
|
+
}
|
|
530
|
+
styleDescriptionText(str) {
|
|
531
|
+
return str;
|
|
532
|
+
}
|
|
533
|
+
styleOptionTerm(str) {
|
|
534
|
+
return this.styleOptionText(str);
|
|
535
|
+
}
|
|
536
|
+
styleSubcommandTerm(str) {
|
|
537
|
+
return str.split(" ").map((word) => {
|
|
538
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
539
|
+
if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
|
|
540
|
+
return this.styleSubcommandText(word);
|
|
541
|
+
}).join(" ");
|
|
542
|
+
}
|
|
543
|
+
styleArgumentTerm(str) {
|
|
544
|
+
return this.styleArgumentText(str);
|
|
545
|
+
}
|
|
546
|
+
styleOptionText(str) {
|
|
547
|
+
return str;
|
|
548
|
+
}
|
|
549
|
+
styleArgumentText(str) {
|
|
550
|
+
return str;
|
|
551
|
+
}
|
|
552
|
+
styleSubcommandText(str) {
|
|
553
|
+
return str;
|
|
554
|
+
}
|
|
555
|
+
styleCommandText(str) {
|
|
556
|
+
return str;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Calculate the pad width from the maximum term length.
|
|
560
|
+
*
|
|
561
|
+
* @param {Command} cmd
|
|
562
|
+
* @param {Help} helper
|
|
563
|
+
* @returns {number}
|
|
564
|
+
*/
|
|
565
|
+
padWidth(cmd, helper) {
|
|
566
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
570
|
+
*
|
|
571
|
+
* @param {string} str
|
|
572
|
+
* @returns {boolean}
|
|
573
|
+
*/
|
|
574
|
+
preformatted(str) {
|
|
575
|
+
return /\n[^\S\r\n]/.test(str);
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
579
|
+
*
|
|
580
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
581
|
+
* TTT DDD DDDD
|
|
582
|
+
* DD DDD
|
|
583
|
+
*
|
|
584
|
+
* @param {string} term
|
|
585
|
+
* @param {number} termWidth
|
|
586
|
+
* @param {string} description
|
|
587
|
+
* @param {Help} helper
|
|
588
|
+
* @returns {string}
|
|
589
|
+
*/
|
|
590
|
+
formatItem(term, termWidth, description, helper) {
|
|
591
|
+
const itemIndent = 2;
|
|
592
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
593
|
+
if (!description) return itemIndentStr + term;
|
|
594
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
595
|
+
const spacerWidth = 2;
|
|
596
|
+
const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
|
|
597
|
+
let formattedDescription;
|
|
598
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
|
|
599
|
+
else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
|
|
600
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
604
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
605
|
+
*
|
|
606
|
+
* @param {string} str
|
|
607
|
+
* @param {number} width
|
|
608
|
+
* @returns {string}
|
|
609
|
+
*/
|
|
610
|
+
boxWrap(str, width) {
|
|
611
|
+
if (width < this.minWidthToWrap) return str;
|
|
612
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
613
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
614
|
+
const wrappedLines = [];
|
|
615
|
+
rawLines.forEach((line) => {
|
|
616
|
+
const chunks = line.match(chunkPattern);
|
|
617
|
+
if (chunks === null) {
|
|
618
|
+
wrappedLines.push("");
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
let sumChunks = [chunks.shift()];
|
|
622
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
623
|
+
chunks.forEach((chunk) => {
|
|
624
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
625
|
+
if (sumWidth + visibleWidth <= width) {
|
|
626
|
+
sumChunks.push(chunk);
|
|
627
|
+
sumWidth += visibleWidth;
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
wrappedLines.push(sumChunks.join(""));
|
|
631
|
+
const nextChunk = chunk.trimStart();
|
|
632
|
+
sumChunks = [nextChunk];
|
|
633
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
634
|
+
});
|
|
635
|
+
wrappedLines.push(sumChunks.join(""));
|
|
636
|
+
});
|
|
637
|
+
return wrappedLines.join("\n");
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
//#endregion
|
|
641
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
|
|
642
|
+
var Option = class {
|
|
643
|
+
/**
|
|
644
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
645
|
+
*
|
|
646
|
+
* @param {string} flags
|
|
647
|
+
* @param {string} [description]
|
|
648
|
+
*/
|
|
649
|
+
constructor(flags, description) {
|
|
650
|
+
this.flags = flags;
|
|
651
|
+
this.description = description || "";
|
|
652
|
+
this.required = flags.includes("<");
|
|
653
|
+
this.optional = flags.includes("[");
|
|
654
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
655
|
+
this.mandatory = false;
|
|
656
|
+
const optionFlags = splitOptionFlags(flags);
|
|
657
|
+
this.short = optionFlags.shortFlag;
|
|
658
|
+
this.long = optionFlags.longFlag;
|
|
659
|
+
this.negate = false;
|
|
660
|
+
if (this.long) this.negate = this.long.startsWith("--no-");
|
|
661
|
+
this.defaultValue = void 0;
|
|
662
|
+
this.defaultValueDescription = void 0;
|
|
663
|
+
this.presetArg = void 0;
|
|
664
|
+
this.envVar = void 0;
|
|
665
|
+
this.parseArg = void 0;
|
|
666
|
+
this.hidden = false;
|
|
667
|
+
this.argChoices = void 0;
|
|
668
|
+
this.conflictsWith = [];
|
|
669
|
+
this.implied = void 0;
|
|
670
|
+
this.helpGroupHeading = void 0;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
674
|
+
*
|
|
675
|
+
* @param {*} value
|
|
676
|
+
* @param {string} [description]
|
|
677
|
+
* @return {Option}
|
|
678
|
+
*/
|
|
679
|
+
default(value, description) {
|
|
680
|
+
this.defaultValue = value;
|
|
681
|
+
this.defaultValueDescription = description;
|
|
682
|
+
return this;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
686
|
+
* The custom processing (parseArg) is called.
|
|
687
|
+
*
|
|
688
|
+
* @example
|
|
689
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
690
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
691
|
+
*
|
|
692
|
+
* @param {*} arg
|
|
693
|
+
* @return {Option}
|
|
694
|
+
*/
|
|
695
|
+
preset(arg) {
|
|
696
|
+
this.presetArg = arg;
|
|
697
|
+
return this;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Add option name(s) that conflict with this option.
|
|
701
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
702
|
+
*
|
|
703
|
+
* @example
|
|
704
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
705
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
706
|
+
*
|
|
707
|
+
* @param {(string | string[])} names
|
|
708
|
+
* @return {Option}
|
|
709
|
+
*/
|
|
710
|
+
conflicts(names) {
|
|
711
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
712
|
+
return this;
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
716
|
+
*
|
|
717
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
718
|
+
*
|
|
719
|
+
* @example
|
|
720
|
+
* program
|
|
721
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
722
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
723
|
+
*
|
|
724
|
+
* @param {object} impliedOptionValues
|
|
725
|
+
* @return {Option}
|
|
726
|
+
*/
|
|
727
|
+
implies(impliedOptionValues) {
|
|
728
|
+
let newImplied = impliedOptionValues;
|
|
729
|
+
if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
|
|
730
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
731
|
+
return this;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Set environment variable to check for option value.
|
|
735
|
+
*
|
|
736
|
+
* An environment variable is only used if when processed the current option value is
|
|
737
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
738
|
+
*
|
|
739
|
+
* @param {string} name
|
|
740
|
+
* @return {Option}
|
|
741
|
+
*/
|
|
742
|
+
env(name) {
|
|
743
|
+
this.envVar = name;
|
|
744
|
+
return this;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
748
|
+
*
|
|
749
|
+
* @param {Function} [fn]
|
|
750
|
+
* @return {Option}
|
|
751
|
+
*/
|
|
752
|
+
argParser(fn) {
|
|
753
|
+
this.parseArg = fn;
|
|
754
|
+
return this;
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
758
|
+
*
|
|
759
|
+
* @param {boolean} [mandatory=true]
|
|
760
|
+
* @return {Option}
|
|
761
|
+
*/
|
|
762
|
+
makeOptionMandatory(mandatory = true) {
|
|
763
|
+
this.mandatory = !!mandatory;
|
|
764
|
+
return this;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Hide option in help.
|
|
768
|
+
*
|
|
769
|
+
* @param {boolean} [hide=true]
|
|
770
|
+
* @return {Option}
|
|
771
|
+
*/
|
|
772
|
+
hideHelp(hide = true) {
|
|
773
|
+
this.hidden = !!hide;
|
|
774
|
+
return this;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* @package
|
|
778
|
+
*/
|
|
779
|
+
_collectValue(value, previous) {
|
|
780
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
|
|
781
|
+
previous.push(value);
|
|
782
|
+
return previous;
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Only allow option value to be one of choices.
|
|
786
|
+
*
|
|
787
|
+
* @param {string[]} values
|
|
788
|
+
* @return {Option}
|
|
789
|
+
*/
|
|
790
|
+
choices(values) {
|
|
791
|
+
this.argChoices = values.slice();
|
|
792
|
+
this.parseArg = (arg, previous) => {
|
|
793
|
+
if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
794
|
+
if (this.variadic) return this._collectValue(arg, previous);
|
|
795
|
+
return arg;
|
|
796
|
+
};
|
|
797
|
+
return this;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Return option name.
|
|
801
|
+
*
|
|
802
|
+
* @return {string}
|
|
803
|
+
*/
|
|
804
|
+
name() {
|
|
805
|
+
if (this.long) return this.long.replace(/^--/, "");
|
|
806
|
+
return this.short.replace(/^-/, "");
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Return option name, in a camelcase format that can be used
|
|
810
|
+
* as an object attribute key.
|
|
811
|
+
*
|
|
812
|
+
* @return {string}
|
|
813
|
+
*/
|
|
814
|
+
attributeName() {
|
|
815
|
+
if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
|
|
816
|
+
return camelcase(this.name());
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Set the help group heading.
|
|
820
|
+
*
|
|
821
|
+
* @param {string} heading
|
|
822
|
+
* @return {Option}
|
|
823
|
+
*/
|
|
824
|
+
helpGroup(heading) {
|
|
825
|
+
this.helpGroupHeading = heading;
|
|
826
|
+
return this;
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Check if `arg` matches the short or long flag.
|
|
830
|
+
*
|
|
831
|
+
* @param {string} arg
|
|
832
|
+
* @return {boolean}
|
|
833
|
+
* @package
|
|
834
|
+
*/
|
|
835
|
+
is(arg) {
|
|
836
|
+
return this.short === arg || this.long === arg;
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Return whether a boolean option.
|
|
840
|
+
*
|
|
841
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
842
|
+
*
|
|
843
|
+
* @return {boolean}
|
|
844
|
+
* @package
|
|
845
|
+
*/
|
|
846
|
+
isBoolean() {
|
|
847
|
+
return !this.required && !this.optional && !this.negate;
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
/**
|
|
851
|
+
* This class is to make it easier to work with dual options, without changing the existing
|
|
852
|
+
* implementation. We support separate dual options for separate positive and negative options,
|
|
853
|
+
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
|
|
854
|
+
* use cases, but is tricky for others where we want separate behaviours despite
|
|
855
|
+
* the single shared option value.
|
|
856
|
+
*/
|
|
857
|
+
var DualOptions = class {
|
|
858
|
+
/**
|
|
859
|
+
* @param {Option[]} options
|
|
860
|
+
*/
|
|
861
|
+
constructor(options) {
|
|
862
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
863
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
864
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
865
|
+
options.forEach((option) => {
|
|
866
|
+
if (option.negate) this.negativeOptions.set(option.attributeName(), option);
|
|
867
|
+
else this.positiveOptions.set(option.attributeName(), option);
|
|
868
|
+
});
|
|
869
|
+
this.negativeOptions.forEach((value, key) => {
|
|
870
|
+
if (this.positiveOptions.has(key)) this.dualOptions.add(key);
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
875
|
+
*
|
|
876
|
+
* @param {*} value
|
|
877
|
+
* @param {Option} option
|
|
878
|
+
* @returns {boolean}
|
|
879
|
+
*/
|
|
880
|
+
valueFromOption(value, option) {
|
|
881
|
+
const optionKey = option.attributeName();
|
|
882
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
883
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
884
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
885
|
+
return option.negate === (negativeValue === value);
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
/**
|
|
889
|
+
* Convert string from kebab-case to camelCase.
|
|
890
|
+
*
|
|
891
|
+
* @param {string} str
|
|
892
|
+
* @return {string}
|
|
893
|
+
* @private
|
|
894
|
+
*/
|
|
895
|
+
function camelcase(str) {
|
|
896
|
+
return str.split("-").reduce((str, word) => {
|
|
897
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Split the short and long flag out of something like '-m,--mixed <value>'
|
|
902
|
+
*
|
|
903
|
+
* @private
|
|
904
|
+
*/
|
|
905
|
+
function splitOptionFlags(flags) {
|
|
906
|
+
let shortFlag;
|
|
907
|
+
let longFlag;
|
|
908
|
+
const shortFlagExp = /^-[^-]$/;
|
|
909
|
+
const longFlagExp = /^--[^-]/;
|
|
910
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
911
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
912
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
913
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
914
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
915
|
+
shortFlag = longFlag;
|
|
916
|
+
longFlag = flagParts.shift();
|
|
917
|
+
}
|
|
918
|
+
if (flagParts[0].startsWith("-")) {
|
|
919
|
+
const unsupportedFlag = flagParts[0];
|
|
920
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
921
|
+
if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
922
|
+
- a short flag is a single dash and a single character
|
|
923
|
+
- either use a single dash and a single character (for a short flag)
|
|
924
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
925
|
+
if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
926
|
+
- too many short flags`);
|
|
927
|
+
if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
|
|
928
|
+
- too many long flags`);
|
|
929
|
+
throw new Error(`${baseError}
|
|
930
|
+
- unrecognised flag format`);
|
|
931
|
+
}
|
|
932
|
+
if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
933
|
+
return {
|
|
934
|
+
shortFlag,
|
|
935
|
+
longFlag
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
|
|
940
|
+
var maxDistance = 3;
|
|
941
|
+
function editDistance(a, b) {
|
|
942
|
+
if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
|
|
943
|
+
const d = [];
|
|
944
|
+
for (let i = 0; i <= a.length; i++) d[i] = [i];
|
|
945
|
+
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
|
946
|
+
for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
|
|
947
|
+
let cost;
|
|
948
|
+
if (a[i - 1] === b[j - 1]) cost = 0;
|
|
949
|
+
else cost = 1;
|
|
950
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
951
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
952
|
+
}
|
|
953
|
+
return d[a.length][b.length];
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Find close matches, restricted to same number of edits.
|
|
957
|
+
*
|
|
958
|
+
* @param {string} word
|
|
959
|
+
* @param {string[]} candidates
|
|
960
|
+
* @returns {string}
|
|
961
|
+
*/
|
|
962
|
+
function suggestSimilar(word, candidates) {
|
|
963
|
+
if (!candidates || candidates.length === 0) return "";
|
|
964
|
+
candidates = Array.from(new Set(candidates));
|
|
965
|
+
const searchingOptions = word.startsWith("--");
|
|
966
|
+
if (searchingOptions) {
|
|
967
|
+
word = word.slice(2);
|
|
968
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
969
|
+
}
|
|
970
|
+
let similar = [];
|
|
971
|
+
let bestDistance = maxDistance;
|
|
972
|
+
const minSimilarity = .4;
|
|
973
|
+
candidates.forEach((candidate) => {
|
|
974
|
+
if (candidate.length <= 1) return;
|
|
975
|
+
const distance = editDistance(word, candidate);
|
|
976
|
+
const length = Math.max(word.length, candidate.length);
|
|
977
|
+
if ((length - distance) / length > minSimilarity) {
|
|
978
|
+
if (distance < bestDistance) {
|
|
979
|
+
bestDistance = distance;
|
|
980
|
+
similar = [candidate];
|
|
981
|
+
} else if (distance === bestDistance) similar.push(candidate);
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
985
|
+
if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
|
|
986
|
+
if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
|
|
987
|
+
if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
|
|
988
|
+
return "";
|
|
989
|
+
}
|
|
990
|
+
//#endregion
|
|
991
|
+
//#region ../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
|
|
992
|
+
var Command = class Command extends EventEmitter {
|
|
993
|
+
/**
|
|
994
|
+
* Initialize a new `Command`.
|
|
995
|
+
*
|
|
996
|
+
* @param {string} [name]
|
|
997
|
+
*/
|
|
998
|
+
constructor(name) {
|
|
999
|
+
super();
|
|
1000
|
+
/** @type {Command[]} */
|
|
1001
|
+
this.commands = [];
|
|
1002
|
+
/** @type {Option[]} */
|
|
1003
|
+
this.options = [];
|
|
1004
|
+
this.parent = null;
|
|
1005
|
+
this._allowUnknownOption = false;
|
|
1006
|
+
this._allowExcessArguments = false;
|
|
1007
|
+
/** @type {Argument[]} */
|
|
1008
|
+
this.registeredArguments = [];
|
|
1009
|
+
this._args = this.registeredArguments;
|
|
1010
|
+
/** @type {string[]} */
|
|
1011
|
+
this.args = [];
|
|
1012
|
+
this.rawArgs = [];
|
|
1013
|
+
this.processedArgs = [];
|
|
1014
|
+
this._scriptPath = null;
|
|
1015
|
+
this._name = name || "";
|
|
1016
|
+
this._optionValues = {};
|
|
1017
|
+
this._optionValueSources = {};
|
|
1018
|
+
this._storeOptionsAsProperties = false;
|
|
1019
|
+
this._actionHandler = null;
|
|
1020
|
+
this._executableHandler = false;
|
|
1021
|
+
this._executableFile = null;
|
|
1022
|
+
this._executableDir = null;
|
|
1023
|
+
this._defaultCommandName = null;
|
|
1024
|
+
this._exitCallback = null;
|
|
1025
|
+
this._aliases = [];
|
|
1026
|
+
this._combineFlagAndOptionalValue = true;
|
|
1027
|
+
this._description = "";
|
|
1028
|
+
this._summary = "";
|
|
1029
|
+
this._argsDescription = void 0;
|
|
1030
|
+
this._enablePositionalOptions = false;
|
|
1031
|
+
this._passThroughOptions = false;
|
|
1032
|
+
this._lifeCycleHooks = {};
|
|
1033
|
+
/** @type {(boolean | string)} */
|
|
1034
|
+
this._showHelpAfterError = false;
|
|
1035
|
+
this._showSuggestionAfterError = true;
|
|
1036
|
+
this._savedState = null;
|
|
1037
|
+
this._outputConfiguration = {
|
|
1038
|
+
writeOut: (str) => process$1.stdout.write(str),
|
|
1039
|
+
writeErr: (str) => process$1.stderr.write(str),
|
|
1040
|
+
outputError: (str, write) => write(str),
|
|
1041
|
+
getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
|
|
1042
|
+
getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
|
|
1043
|
+
getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
|
|
1044
|
+
getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
|
|
1045
|
+
stripColor: (str) => stripVTControlCharacters(str)
|
|
1046
|
+
};
|
|
1047
|
+
this._hidden = false;
|
|
1048
|
+
/** @type {(Option | null | undefined)} */
|
|
1049
|
+
this._helpOption = void 0;
|
|
1050
|
+
this._addImplicitHelpCommand = void 0;
|
|
1051
|
+
/** @type {Command} */
|
|
1052
|
+
this._helpCommand = void 0;
|
|
1053
|
+
this._helpConfiguration = {};
|
|
1054
|
+
/** @type {string | undefined} */
|
|
1055
|
+
this._helpGroupHeading = void 0;
|
|
1056
|
+
/** @type {string | undefined} */
|
|
1057
|
+
this._defaultCommandGroup = void 0;
|
|
1058
|
+
/** @type {string | undefined} */
|
|
1059
|
+
this._defaultOptionGroup = void 0;
|
|
1060
|
+
}
|
|
1061
|
+
/**
|
|
1062
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1063
|
+
*
|
|
1064
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1065
|
+
*
|
|
1066
|
+
* @param {Command} sourceCommand
|
|
1067
|
+
* @return {Command} `this` command for chaining
|
|
1068
|
+
*/
|
|
1069
|
+
copyInheritedSettings(sourceCommand) {
|
|
1070
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1071
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1072
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1073
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1074
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1075
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1076
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1077
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1078
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1079
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1080
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1081
|
+
return this;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* @returns {Command[]}
|
|
1085
|
+
* @private
|
|
1086
|
+
*/
|
|
1087
|
+
_getCommandAndAncestors() {
|
|
1088
|
+
const result = [];
|
|
1089
|
+
for (let command = this; command; command = command.parent) result.push(command);
|
|
1090
|
+
return result;
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Define a command.
|
|
1094
|
+
*
|
|
1095
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1096
|
+
*
|
|
1097
|
+
* @example
|
|
1098
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1099
|
+
* program
|
|
1100
|
+
* .command('clone <source> [destination]')
|
|
1101
|
+
* .description('clone a repository into a newly created directory')
|
|
1102
|
+
* .action((source, destination) => {
|
|
1103
|
+
* console.log('clone command called');
|
|
1104
|
+
* });
|
|
1105
|
+
*
|
|
1106
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1107
|
+
* program
|
|
1108
|
+
* .command('start <service>', 'start named service')
|
|
1109
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1110
|
+
*
|
|
1111
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1112
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1113
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1114
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1115
|
+
*/
|
|
1116
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1117
|
+
let desc = actionOptsOrExecDesc;
|
|
1118
|
+
let opts = execOpts;
|
|
1119
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1120
|
+
opts = desc;
|
|
1121
|
+
desc = null;
|
|
1122
|
+
}
|
|
1123
|
+
opts = opts || {};
|
|
1124
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1125
|
+
const cmd = this.createCommand(name);
|
|
1126
|
+
if (desc) {
|
|
1127
|
+
cmd.description(desc);
|
|
1128
|
+
cmd._executableHandler = true;
|
|
1129
|
+
}
|
|
1130
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1131
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1132
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1133
|
+
if (args) cmd.arguments(args);
|
|
1134
|
+
this._registerCommand(cmd);
|
|
1135
|
+
cmd.parent = this;
|
|
1136
|
+
cmd.copyInheritedSettings(this);
|
|
1137
|
+
if (desc) return this;
|
|
1138
|
+
return cmd;
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Factory routine to create a new unattached command.
|
|
1142
|
+
*
|
|
1143
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1144
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1145
|
+
*
|
|
1146
|
+
* @param {string} [name]
|
|
1147
|
+
* @return {Command} new command
|
|
1148
|
+
*/
|
|
1149
|
+
createCommand(name) {
|
|
1150
|
+
return new Command(name);
|
|
1151
|
+
}
|
|
1152
|
+
/**
|
|
1153
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1154
|
+
* or by overriding Help properties using configureHelp().
|
|
1155
|
+
*
|
|
1156
|
+
* @return {Help}
|
|
1157
|
+
*/
|
|
1158
|
+
createHelp() {
|
|
1159
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1163
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1164
|
+
*
|
|
1165
|
+
* @param {object} [configuration] - configuration options
|
|
1166
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1167
|
+
*/
|
|
1168
|
+
configureHelp(configuration) {
|
|
1169
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1170
|
+
this._helpConfiguration = configuration;
|
|
1171
|
+
return this;
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1175
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1176
|
+
*
|
|
1177
|
+
* The configuration properties are all functions:
|
|
1178
|
+
*
|
|
1179
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1180
|
+
* writeOut(str)
|
|
1181
|
+
* writeErr(str)
|
|
1182
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1183
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1184
|
+
* // specify width for wrapping help
|
|
1185
|
+
* getOutHelpWidth()
|
|
1186
|
+
* getErrHelpWidth()
|
|
1187
|
+
* // color support, currently only used with Help
|
|
1188
|
+
* getOutHasColors()
|
|
1189
|
+
* getErrHasColors()
|
|
1190
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1191
|
+
*
|
|
1192
|
+
* @param {object} [configuration] - configuration options
|
|
1193
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1194
|
+
*/
|
|
1195
|
+
configureOutput(configuration) {
|
|
1196
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1197
|
+
this._outputConfiguration = {
|
|
1198
|
+
...this._outputConfiguration,
|
|
1199
|
+
...configuration
|
|
1200
|
+
};
|
|
1201
|
+
return this;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Display the help or a custom message after an error occurs.
|
|
1205
|
+
*
|
|
1206
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1207
|
+
* @return {Command} `this` command for chaining
|
|
1208
|
+
*/
|
|
1209
|
+
showHelpAfterError(displayHelp = true) {
|
|
1210
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1211
|
+
this._showHelpAfterError = displayHelp;
|
|
1212
|
+
return this;
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1216
|
+
*
|
|
1217
|
+
* @param {boolean} [displaySuggestion]
|
|
1218
|
+
* @return {Command} `this` command for chaining
|
|
1219
|
+
*/
|
|
1220
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1221
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1222
|
+
return this;
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Add a prepared subcommand.
|
|
1226
|
+
*
|
|
1227
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1228
|
+
*
|
|
1229
|
+
* @param {Command} cmd - new subcommand
|
|
1230
|
+
* @param {object} [opts] - configuration options
|
|
1231
|
+
* @return {Command} `this` command for chaining
|
|
1232
|
+
*/
|
|
1233
|
+
addCommand(cmd, opts) {
|
|
1234
|
+
if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
|
|
1235
|
+
- specify the name in Command constructor or using .name()`);
|
|
1236
|
+
opts = opts || {};
|
|
1237
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1238
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1239
|
+
this._registerCommand(cmd);
|
|
1240
|
+
cmd.parent = this;
|
|
1241
|
+
cmd._checkForBrokenPassThrough();
|
|
1242
|
+
return this;
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Factory routine to create a new unattached argument.
|
|
1246
|
+
*
|
|
1247
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1248
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1249
|
+
*
|
|
1250
|
+
* @param {string} name
|
|
1251
|
+
* @param {string} [description]
|
|
1252
|
+
* @return {Argument} new argument
|
|
1253
|
+
*/
|
|
1254
|
+
createArgument(name, description) {
|
|
1255
|
+
return new Argument(name, description);
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Define argument syntax for command.
|
|
1259
|
+
*
|
|
1260
|
+
* The default is that the argument is required, and you can explicitly
|
|
1261
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1262
|
+
*
|
|
1263
|
+
* @example
|
|
1264
|
+
* program.argument('<input-file>');
|
|
1265
|
+
* program.argument('[output-file]');
|
|
1266
|
+
*
|
|
1267
|
+
* @param {string} name
|
|
1268
|
+
* @param {string} [description]
|
|
1269
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1270
|
+
* @param {*} [defaultValue]
|
|
1271
|
+
* @return {Command} `this` command for chaining
|
|
1272
|
+
*/
|
|
1273
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1274
|
+
const argument = this.createArgument(name, description);
|
|
1275
|
+
if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
|
|
1276
|
+
else argument.default(parseArg);
|
|
1277
|
+
this.addArgument(argument);
|
|
1278
|
+
return this;
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1282
|
+
*
|
|
1283
|
+
* See also .argument().
|
|
1284
|
+
*
|
|
1285
|
+
* @example
|
|
1286
|
+
* program.arguments('<cmd> [env]');
|
|
1287
|
+
*
|
|
1288
|
+
* @param {string} names
|
|
1289
|
+
* @return {Command} `this` command for chaining
|
|
1290
|
+
*/
|
|
1291
|
+
arguments(names) {
|
|
1292
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1293
|
+
this.argument(detail);
|
|
1294
|
+
});
|
|
1295
|
+
return this;
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1299
|
+
*
|
|
1300
|
+
* @param {Argument} argument
|
|
1301
|
+
* @return {Command} `this` command for chaining
|
|
1302
|
+
*/
|
|
1303
|
+
addArgument(argument) {
|
|
1304
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1305
|
+
if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
1306
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
1307
|
+
this.registeredArguments.push(argument);
|
|
1308
|
+
return this;
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1312
|
+
*
|
|
1313
|
+
* @example
|
|
1314
|
+
* program.helpCommand('help [cmd]');
|
|
1315
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1316
|
+
* program.helpCommand(false); // suppress default help command
|
|
1317
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1318
|
+
*
|
|
1319
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1320
|
+
* @param {string} [description] - custom description
|
|
1321
|
+
* @return {Command} `this` command for chaining
|
|
1322
|
+
*/
|
|
1323
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1324
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1325
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1326
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
|
|
1327
|
+
return this;
|
|
1328
|
+
}
|
|
1329
|
+
const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
|
|
1330
|
+
const helpDescription = description ?? "display help for command";
|
|
1331
|
+
const helpCommand = this.createCommand(helpName);
|
|
1332
|
+
helpCommand.helpOption(false);
|
|
1333
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1334
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1335
|
+
this._addImplicitHelpCommand = true;
|
|
1336
|
+
this._helpCommand = helpCommand;
|
|
1337
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1338
|
+
return this;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Add prepared custom help command.
|
|
1342
|
+
*
|
|
1343
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1344
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1345
|
+
* @return {Command} `this` command for chaining
|
|
1346
|
+
*/
|
|
1347
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1348
|
+
if (typeof helpCommand !== "object") {
|
|
1349
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1350
|
+
return this;
|
|
1351
|
+
}
|
|
1352
|
+
this._addImplicitHelpCommand = true;
|
|
1353
|
+
this._helpCommand = helpCommand;
|
|
1354
|
+
this._initCommandGroup(helpCommand);
|
|
1355
|
+
return this;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Lazy create help command.
|
|
1359
|
+
*
|
|
1360
|
+
* @return {(Command|null)}
|
|
1361
|
+
* @package
|
|
1362
|
+
*/
|
|
1363
|
+
_getHelpCommand() {
|
|
1364
|
+
if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
|
|
1365
|
+
if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
|
|
1366
|
+
return this._helpCommand;
|
|
1367
|
+
}
|
|
1368
|
+
return null;
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Add hook for life cycle event.
|
|
1372
|
+
*
|
|
1373
|
+
* @param {string} event
|
|
1374
|
+
* @param {Function} listener
|
|
1375
|
+
* @return {Command} `this` command for chaining
|
|
1376
|
+
*/
|
|
1377
|
+
hook(event, listener) {
|
|
1378
|
+
const allowedValues = [
|
|
1379
|
+
"preSubcommand",
|
|
1380
|
+
"preAction",
|
|
1381
|
+
"postAction"
|
|
1382
|
+
];
|
|
1383
|
+
if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1384
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1385
|
+
if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
|
|
1386
|
+
else this._lifeCycleHooks[event] = [listener];
|
|
1387
|
+
return this;
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1391
|
+
*
|
|
1392
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1393
|
+
* @return {Command} `this` command for chaining
|
|
1394
|
+
*/
|
|
1395
|
+
exitOverride(fn) {
|
|
1396
|
+
if (fn) this._exitCallback = fn;
|
|
1397
|
+
else this._exitCallback = (err) => {
|
|
1398
|
+
if (err.code !== "commander.executeSubCommandAsync") throw err;
|
|
1399
|
+
};
|
|
1400
|
+
return this;
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1404
|
+
*
|
|
1405
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1406
|
+
* @param {string} code an id string representing the error
|
|
1407
|
+
* @param {string} message human-readable description of the error
|
|
1408
|
+
* @return never
|
|
1409
|
+
* @private
|
|
1410
|
+
*/
|
|
1411
|
+
_exit(exitCode, code, message) {
|
|
1412
|
+
if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
|
|
1413
|
+
process$1.exit(exitCode);
|
|
1414
|
+
}
|
|
1415
|
+
/**
|
|
1416
|
+
* Register callback `fn` for the command.
|
|
1417
|
+
*
|
|
1418
|
+
* @example
|
|
1419
|
+
* program
|
|
1420
|
+
* .command('serve')
|
|
1421
|
+
* .description('start service')
|
|
1422
|
+
* .action(function() {
|
|
1423
|
+
* // do work here
|
|
1424
|
+
* });
|
|
1425
|
+
*
|
|
1426
|
+
* @param {Function} fn
|
|
1427
|
+
* @return {Command} `this` command for chaining
|
|
1428
|
+
*/
|
|
1429
|
+
action(fn) {
|
|
1430
|
+
const listener = (args) => {
|
|
1431
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1432
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1433
|
+
if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
|
|
1434
|
+
else actionArgs[expectedArgsCount] = this.opts();
|
|
1435
|
+
actionArgs.push(this);
|
|
1436
|
+
return fn.apply(this, actionArgs);
|
|
1437
|
+
};
|
|
1438
|
+
this._actionHandler = listener;
|
|
1439
|
+
return this;
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Factory routine to create a new unattached option.
|
|
1443
|
+
*
|
|
1444
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1445
|
+
* create the option. You can override createOption to return a custom option.
|
|
1446
|
+
*
|
|
1447
|
+
* @param {string} flags
|
|
1448
|
+
* @param {string} [description]
|
|
1449
|
+
* @return {Option} new option
|
|
1450
|
+
*/
|
|
1451
|
+
createOption(flags, description) {
|
|
1452
|
+
return new Option(flags, description);
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1456
|
+
*
|
|
1457
|
+
* @param {(Option | Argument)} target
|
|
1458
|
+
* @param {string} value
|
|
1459
|
+
* @param {*} previous
|
|
1460
|
+
* @param {string} invalidArgumentMessage
|
|
1461
|
+
* @private
|
|
1462
|
+
*/
|
|
1463
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1464
|
+
try {
|
|
1465
|
+
return target.parseArg(value, previous);
|
|
1466
|
+
} catch (err) {
|
|
1467
|
+
if (err.code === "commander.invalidArgument") {
|
|
1468
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1469
|
+
this.error(message, {
|
|
1470
|
+
exitCode: err.exitCode,
|
|
1471
|
+
code: err.code
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
throw err;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Check for option flag conflicts.
|
|
1479
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1480
|
+
*
|
|
1481
|
+
* @param {Option} option
|
|
1482
|
+
* @private
|
|
1483
|
+
*/
|
|
1484
|
+
_registerOption(option) {
|
|
1485
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1486
|
+
if (matchingOption) {
|
|
1487
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1488
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1489
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1490
|
+
}
|
|
1491
|
+
this._initOptionGroup(option);
|
|
1492
|
+
this.options.push(option);
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1496
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1497
|
+
*
|
|
1498
|
+
* @param {Command} command
|
|
1499
|
+
* @private
|
|
1500
|
+
*/
|
|
1501
|
+
_registerCommand(command) {
|
|
1502
|
+
const knownBy = (cmd) => {
|
|
1503
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1504
|
+
};
|
|
1505
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
1506
|
+
if (alreadyUsed) {
|
|
1507
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1508
|
+
const newCmd = knownBy(command).join("|");
|
|
1509
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1510
|
+
}
|
|
1511
|
+
this._initCommandGroup(command);
|
|
1512
|
+
this.commands.push(command);
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Add an option.
|
|
1516
|
+
*
|
|
1517
|
+
* @param {Option} option
|
|
1518
|
+
* @return {Command} `this` command for chaining
|
|
1519
|
+
*/
|
|
1520
|
+
addOption(option) {
|
|
1521
|
+
this._registerOption(option);
|
|
1522
|
+
const oname = option.name();
|
|
1523
|
+
const name = option.attributeName();
|
|
1524
|
+
if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1525
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1526
|
+
if (val == null && option.presetArg !== void 0) val = option.presetArg;
|
|
1527
|
+
const oldValue = this.getOptionValue(name);
|
|
1528
|
+
if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1529
|
+
else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
|
|
1530
|
+
if (val == null) {
|
|
1531
|
+
if (option.negate) val = false;
|
|
1532
|
+
else if (option.isBoolean() || option.optional) val = true;
|
|
1533
|
+
else val = "";
|
|
1534
|
+
}
|
|
1535
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1536
|
+
};
|
|
1537
|
+
this.on("option:" + oname, (val) => {
|
|
1538
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1539
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1540
|
+
});
|
|
1541
|
+
if (option.envVar) this.on("optionEnv:" + oname, (val) => {
|
|
1542
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1543
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1544
|
+
});
|
|
1545
|
+
return this;
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1549
|
+
*
|
|
1550
|
+
* @return {Command} `this` command for chaining
|
|
1551
|
+
* @private
|
|
1552
|
+
*/
|
|
1553
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1554
|
+
if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1555
|
+
const option = this.createOption(flags, description);
|
|
1556
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1557
|
+
if (typeof fn === "function") option.default(defaultValue).argParser(fn);
|
|
1558
|
+
else if (fn instanceof RegExp) {
|
|
1559
|
+
const regex = fn;
|
|
1560
|
+
fn = (val, def) => {
|
|
1561
|
+
const m = regex.exec(val);
|
|
1562
|
+
return m ? m[0] : def;
|
|
1563
|
+
};
|
|
1564
|
+
option.default(defaultValue).argParser(fn);
|
|
1565
|
+
} else option.default(fn);
|
|
1566
|
+
return this.addOption(option);
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1570
|
+
*
|
|
1571
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1572
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1573
|
+
*
|
|
1574
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1575
|
+
*
|
|
1576
|
+
* @example
|
|
1577
|
+
* program
|
|
1578
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1579
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1580
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1581
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1582
|
+
*
|
|
1583
|
+
* @param {string} flags
|
|
1584
|
+
* @param {string} [description]
|
|
1585
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1586
|
+
* @param {*} [defaultValue]
|
|
1587
|
+
* @return {Command} `this` command for chaining
|
|
1588
|
+
*/
|
|
1589
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1590
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1594
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1595
|
+
*
|
|
1596
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1597
|
+
*
|
|
1598
|
+
* @param {string} flags
|
|
1599
|
+
* @param {string} [description]
|
|
1600
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1601
|
+
* @param {*} [defaultValue]
|
|
1602
|
+
* @return {Command} `this` command for chaining
|
|
1603
|
+
*/
|
|
1604
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1605
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1606
|
+
}
|
|
1607
|
+
/**
|
|
1608
|
+
* Alter parsing of short flags with optional values.
|
|
1609
|
+
*
|
|
1610
|
+
* @example
|
|
1611
|
+
* // for `.option('-f,--flag [value]'):
|
|
1612
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1613
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1614
|
+
*
|
|
1615
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1616
|
+
* @return {Command} `this` command for chaining
|
|
1617
|
+
*/
|
|
1618
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1619
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1620
|
+
return this;
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Allow unknown options on the command line.
|
|
1624
|
+
*
|
|
1625
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1626
|
+
* @return {Command} `this` command for chaining
|
|
1627
|
+
*/
|
|
1628
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1629
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1630
|
+
return this;
|
|
1631
|
+
}
|
|
1632
|
+
/**
|
|
1633
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1634
|
+
*
|
|
1635
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1636
|
+
* @return {Command} `this` command for chaining
|
|
1637
|
+
*/
|
|
1638
|
+
allowExcessArguments(allowExcess = true) {
|
|
1639
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1640
|
+
return this;
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1644
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1645
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1646
|
+
*
|
|
1647
|
+
* @param {boolean} [positional]
|
|
1648
|
+
* @return {Command} `this` command for chaining
|
|
1649
|
+
*/
|
|
1650
|
+
enablePositionalOptions(positional = true) {
|
|
1651
|
+
this._enablePositionalOptions = !!positional;
|
|
1652
|
+
return this;
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1656
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1657
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1658
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1659
|
+
*
|
|
1660
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1661
|
+
* @return {Command} `this` command for chaining
|
|
1662
|
+
*/
|
|
1663
|
+
passThroughOptions(passThrough = true) {
|
|
1664
|
+
this._passThroughOptions = !!passThrough;
|
|
1665
|
+
this._checkForBrokenPassThrough();
|
|
1666
|
+
return this;
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* @private
|
|
1670
|
+
*/
|
|
1671
|
+
_checkForBrokenPassThrough() {
|
|
1672
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* Whether to store option values as properties on command object,
|
|
1676
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1677
|
+
*
|
|
1678
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1679
|
+
* @return {Command} `this` command for chaining
|
|
1680
|
+
*/
|
|
1681
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1682
|
+
if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1683
|
+
if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1684
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1685
|
+
return this;
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Retrieve option value.
|
|
1689
|
+
*
|
|
1690
|
+
* @param {string} key
|
|
1691
|
+
* @return {object} value
|
|
1692
|
+
*/
|
|
1693
|
+
getOptionValue(key) {
|
|
1694
|
+
if (this._storeOptionsAsProperties) return this[key];
|
|
1695
|
+
return this._optionValues[key];
|
|
1696
|
+
}
|
|
1697
|
+
/**
|
|
1698
|
+
* Store option value.
|
|
1699
|
+
*
|
|
1700
|
+
* @param {string} key
|
|
1701
|
+
* @param {object} value
|
|
1702
|
+
* @return {Command} `this` command for chaining
|
|
1703
|
+
*/
|
|
1704
|
+
setOptionValue(key, value) {
|
|
1705
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1706
|
+
}
|
|
1707
|
+
/**
|
|
1708
|
+
* Store option value and where the value came from.
|
|
1709
|
+
*
|
|
1710
|
+
* @param {string} key
|
|
1711
|
+
* @param {object} value
|
|
1712
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1713
|
+
* @return {Command} `this` command for chaining
|
|
1714
|
+
*/
|
|
1715
|
+
setOptionValueWithSource(key, value, source) {
|
|
1716
|
+
if (this._storeOptionsAsProperties) this[key] = value;
|
|
1717
|
+
else this._optionValues[key] = value;
|
|
1718
|
+
this._optionValueSources[key] = source;
|
|
1719
|
+
return this;
|
|
1720
|
+
}
|
|
1721
|
+
/**
|
|
1722
|
+
* Get source of option value.
|
|
1723
|
+
* Expected values are default | config | env | cli | implied
|
|
1724
|
+
*
|
|
1725
|
+
* @param {string} key
|
|
1726
|
+
* @return {string}
|
|
1727
|
+
*/
|
|
1728
|
+
getOptionValueSource(key) {
|
|
1729
|
+
return this._optionValueSources[key];
|
|
1730
|
+
}
|
|
1731
|
+
/**
|
|
1732
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1733
|
+
* Expected values are default | config | env | cli | implied
|
|
1734
|
+
*
|
|
1735
|
+
* @param {string} key
|
|
1736
|
+
* @return {string}
|
|
1737
|
+
*/
|
|
1738
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1739
|
+
let source;
|
|
1740
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1741
|
+
if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
|
|
1742
|
+
});
|
|
1743
|
+
return source;
|
|
1744
|
+
}
|
|
1745
|
+
/**
|
|
1746
|
+
* Get user arguments from implied or explicit arguments.
|
|
1747
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1748
|
+
*
|
|
1749
|
+
* @private
|
|
1750
|
+
*/
|
|
1751
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1752
|
+
if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
|
|
1753
|
+
parseOptions = parseOptions || {};
|
|
1754
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1755
|
+
if (process$1.versions?.electron) parseOptions.from = "electron";
|
|
1756
|
+
const execArgv = process$1.execArgv ?? [];
|
|
1757
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
|
|
1758
|
+
}
|
|
1759
|
+
if (argv === void 0) argv = process$1.argv;
|
|
1760
|
+
this.rawArgs = argv.slice();
|
|
1761
|
+
let userArgs;
|
|
1762
|
+
switch (parseOptions.from) {
|
|
1763
|
+
case void 0:
|
|
1764
|
+
case "node":
|
|
1765
|
+
this._scriptPath = argv[1];
|
|
1766
|
+
userArgs = argv.slice(2);
|
|
1767
|
+
break;
|
|
1768
|
+
case "electron":
|
|
1769
|
+
if (process$1.defaultApp) {
|
|
1770
|
+
this._scriptPath = argv[1];
|
|
1771
|
+
userArgs = argv.slice(2);
|
|
1772
|
+
} else userArgs = argv.slice(1);
|
|
1773
|
+
break;
|
|
1774
|
+
case "user":
|
|
1775
|
+
userArgs = argv.slice(0);
|
|
1776
|
+
break;
|
|
1777
|
+
case "eval":
|
|
1778
|
+
userArgs = argv.slice(1);
|
|
1779
|
+
break;
|
|
1780
|
+
default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1781
|
+
}
|
|
1782
|
+
if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
|
|
1783
|
+
this._name = this._name || "program";
|
|
1784
|
+
return userArgs;
|
|
1785
|
+
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1788
|
+
*
|
|
1789
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
1790
|
+
*
|
|
1791
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1792
|
+
*
|
|
1793
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1794
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1795
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1796
|
+
* - `'user'`: just user arguments
|
|
1797
|
+
*
|
|
1798
|
+
* @example
|
|
1799
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
1800
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1801
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1802
|
+
*
|
|
1803
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
1804
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
1805
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
1806
|
+
* @return {Command} `this` command for chaining
|
|
1807
|
+
*/
|
|
1808
|
+
parse(argv, parseOptions) {
|
|
1809
|
+
this._prepareForParse();
|
|
1810
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1811
|
+
this._parseCommand([], userArgs);
|
|
1812
|
+
return this;
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
1816
|
+
*
|
|
1817
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
1818
|
+
*
|
|
1819
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
1820
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
1821
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
1822
|
+
* - `'user'`: just user arguments
|
|
1823
|
+
*
|
|
1824
|
+
* @example
|
|
1825
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
1826
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
1827
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
1828
|
+
*
|
|
1829
|
+
* @param {string[]} [argv]
|
|
1830
|
+
* @param {object} [parseOptions]
|
|
1831
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
1832
|
+
* @return {Promise}
|
|
1833
|
+
*/
|
|
1834
|
+
async parseAsync(argv, parseOptions) {
|
|
1835
|
+
this._prepareForParse();
|
|
1836
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1837
|
+
await this._parseCommand([], userArgs);
|
|
1838
|
+
return this;
|
|
1839
|
+
}
|
|
1840
|
+
_prepareForParse() {
|
|
1841
|
+
if (this._savedState === null) {
|
|
1842
|
+
this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
|
|
1843
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1844
|
+
if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
|
|
1845
|
+
});
|
|
1846
|
+
this.saveStateBeforeParse();
|
|
1847
|
+
} else this.restoreStateBeforeParse();
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
1851
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1852
|
+
*
|
|
1853
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
1854
|
+
*/
|
|
1855
|
+
saveStateBeforeParse() {
|
|
1856
|
+
this._savedState = {
|
|
1857
|
+
_name: this._name,
|
|
1858
|
+
_optionValues: { ...this._optionValues },
|
|
1859
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1860
|
+
};
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Restore state before parse for calls after the first.
|
|
1864
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
1865
|
+
*
|
|
1866
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
1867
|
+
*/
|
|
1868
|
+
restoreStateBeforeParse() {
|
|
1869
|
+
if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1870
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1871
|
+
this._name = this._savedState._name;
|
|
1872
|
+
this._scriptPath = null;
|
|
1873
|
+
this.rawArgs = [];
|
|
1874
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1875
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1876
|
+
this.args = [];
|
|
1877
|
+
this.processedArgs = [];
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
1881
|
+
*
|
|
1882
|
+
* @param {string} executableFile
|
|
1883
|
+
* @param {string} executableDir
|
|
1884
|
+
* @param {string} subcommandName
|
|
1885
|
+
*/
|
|
1886
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1887
|
+
if (fs.existsSync(executableFile)) return;
|
|
1888
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1889
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1890
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1891
|
+
- ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
|
|
1892
|
+
throw new Error(executableMissing);
|
|
1893
|
+
}
|
|
1894
|
+
/**
|
|
1895
|
+
* Execute a sub-command executable.
|
|
1896
|
+
*
|
|
1897
|
+
* @private
|
|
1898
|
+
*/
|
|
1899
|
+
_executeSubCommand(subcommand, args) {
|
|
1900
|
+
args = args.slice();
|
|
1901
|
+
const sourceExt = [
|
|
1902
|
+
".js",
|
|
1903
|
+
".ts",
|
|
1904
|
+
".tsx",
|
|
1905
|
+
".mjs",
|
|
1906
|
+
".cjs"
|
|
1907
|
+
];
|
|
1908
|
+
function findFile(baseDir, baseName) {
|
|
1909
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1910
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
1911
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
1912
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1913
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
1914
|
+
}
|
|
1915
|
+
this._checkForMissingMandatoryOptions();
|
|
1916
|
+
this._checkForConflictingOptions();
|
|
1917
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1918
|
+
let executableDir = this._executableDir || "";
|
|
1919
|
+
if (this._scriptPath) {
|
|
1920
|
+
let resolvedScriptPath;
|
|
1921
|
+
try {
|
|
1922
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1923
|
+
} catch {
|
|
1924
|
+
resolvedScriptPath = this._scriptPath;
|
|
1925
|
+
}
|
|
1926
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1927
|
+
}
|
|
1928
|
+
if (executableDir) {
|
|
1929
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1930
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1931
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1932
|
+
if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1933
|
+
}
|
|
1934
|
+
executableFile = localFile || executableFile;
|
|
1935
|
+
}
|
|
1936
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1937
|
+
let proc;
|
|
1938
|
+
if (process$1.platform !== "win32") {
|
|
1939
|
+
if (launchWithNode) {
|
|
1940
|
+
args.unshift(executableFile);
|
|
1941
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1942
|
+
proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
|
|
1943
|
+
} else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1944
|
+
} else {
|
|
1945
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1946
|
+
args.unshift(executableFile);
|
|
1947
|
+
args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
|
|
1948
|
+
proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
|
|
1949
|
+
}
|
|
1950
|
+
if (!proc.killed) [
|
|
1951
|
+
"SIGUSR1",
|
|
1952
|
+
"SIGUSR2",
|
|
1953
|
+
"SIGTERM",
|
|
1954
|
+
"SIGINT",
|
|
1955
|
+
"SIGHUP"
|
|
1956
|
+
].forEach((signal) => {
|
|
1957
|
+
process$1.on(signal, () => {
|
|
1958
|
+
if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
|
|
1959
|
+
});
|
|
1960
|
+
});
|
|
1961
|
+
const exitCallback = this._exitCallback;
|
|
1962
|
+
proc.on("close", (code) => {
|
|
1963
|
+
code = code ?? 1;
|
|
1964
|
+
if (!exitCallback) process$1.exit(code);
|
|
1965
|
+
else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1966
|
+
});
|
|
1967
|
+
proc.on("error", (err) => {
|
|
1968
|
+
if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1969
|
+
else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
|
|
1970
|
+
if (!exitCallback) process$1.exit(1);
|
|
1971
|
+
else {
|
|
1972
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1973
|
+
wrappedError.nestedError = err;
|
|
1974
|
+
exitCallback(wrappedError);
|
|
1975
|
+
}
|
|
1976
|
+
});
|
|
1977
|
+
this.runningCommand = proc;
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* @private
|
|
1981
|
+
*/
|
|
1982
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1983
|
+
const subCommand = this._findCommand(commandName);
|
|
1984
|
+
if (!subCommand) this.help({ error: true });
|
|
1985
|
+
subCommand._prepareForParse();
|
|
1986
|
+
let promiseChain;
|
|
1987
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1988
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1989
|
+
if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1990
|
+
else return subCommand._parseCommand(operands, unknown);
|
|
1991
|
+
});
|
|
1992
|
+
return promiseChain;
|
|
1993
|
+
}
|
|
1994
|
+
/**
|
|
1995
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
1996
|
+
* e.g. help foo
|
|
1997
|
+
*
|
|
1998
|
+
* @private
|
|
1999
|
+
*/
|
|
2000
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2001
|
+
if (!subcommandName) this.help();
|
|
2002
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2003
|
+
if (subCommand && !subCommand._executableHandler) subCommand.help();
|
|
2004
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* Check this.args against expected this.registeredArguments.
|
|
2008
|
+
*
|
|
2009
|
+
* @private
|
|
2010
|
+
*/
|
|
2011
|
+
_checkNumberOfArguments() {
|
|
2012
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2013
|
+
if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
|
|
2014
|
+
});
|
|
2015
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
|
|
2016
|
+
if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2020
|
+
*
|
|
2021
|
+
* @private
|
|
2022
|
+
*/
|
|
2023
|
+
_processArguments() {
|
|
2024
|
+
const myParseArg = (argument, value, previous) => {
|
|
2025
|
+
let parsedValue = value;
|
|
2026
|
+
if (value !== null && argument.parseArg) {
|
|
2027
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2028
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
2029
|
+
}
|
|
2030
|
+
return parsedValue;
|
|
2031
|
+
};
|
|
2032
|
+
this._checkNumberOfArguments();
|
|
2033
|
+
const processedArgs = [];
|
|
2034
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2035
|
+
let value = declaredArg.defaultValue;
|
|
2036
|
+
if (declaredArg.variadic) {
|
|
2037
|
+
if (index < this.args.length) {
|
|
2038
|
+
value = this.args.slice(index);
|
|
2039
|
+
if (declaredArg.parseArg) value = value.reduce((processed, v) => {
|
|
2040
|
+
return myParseArg(declaredArg, v, processed);
|
|
2041
|
+
}, declaredArg.defaultValue);
|
|
2042
|
+
} else if (value === void 0) value = [];
|
|
2043
|
+
} else if (index < this.args.length) {
|
|
2044
|
+
value = this.args[index];
|
|
2045
|
+
if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2046
|
+
}
|
|
2047
|
+
processedArgs[index] = value;
|
|
2048
|
+
});
|
|
2049
|
+
this.processedArgs = processedArgs;
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2053
|
+
*
|
|
2054
|
+
* @param {(Promise|undefined)} promise
|
|
2055
|
+
* @param {Function} fn
|
|
2056
|
+
* @return {(Promise|undefined)}
|
|
2057
|
+
* @private
|
|
2058
|
+
*/
|
|
2059
|
+
_chainOrCall(promise, fn) {
|
|
2060
|
+
if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
|
|
2061
|
+
return fn();
|
|
2062
|
+
}
|
|
2063
|
+
/**
|
|
2064
|
+
*
|
|
2065
|
+
* @param {(Promise|undefined)} promise
|
|
2066
|
+
* @param {string} event
|
|
2067
|
+
* @return {(Promise|undefined)}
|
|
2068
|
+
* @private
|
|
2069
|
+
*/
|
|
2070
|
+
_chainOrCallHooks(promise, event) {
|
|
2071
|
+
let result = promise;
|
|
2072
|
+
const hooks = [];
|
|
2073
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2074
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2075
|
+
hooks.push({
|
|
2076
|
+
hookedCommand,
|
|
2077
|
+
callback
|
|
2078
|
+
});
|
|
2079
|
+
});
|
|
2080
|
+
});
|
|
2081
|
+
if (event === "postAction") hooks.reverse();
|
|
2082
|
+
hooks.forEach((hookDetail) => {
|
|
2083
|
+
result = this._chainOrCall(result, () => {
|
|
2084
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2085
|
+
});
|
|
2086
|
+
});
|
|
2087
|
+
return result;
|
|
2088
|
+
}
|
|
2089
|
+
/**
|
|
2090
|
+
*
|
|
2091
|
+
* @param {(Promise|undefined)} promise
|
|
2092
|
+
* @param {Command} subCommand
|
|
2093
|
+
* @param {string} event
|
|
2094
|
+
* @return {(Promise|undefined)}
|
|
2095
|
+
* @private
|
|
2096
|
+
*/
|
|
2097
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2098
|
+
let result = promise;
|
|
2099
|
+
if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
|
|
2100
|
+
result = this._chainOrCall(result, () => {
|
|
2101
|
+
return hook(this, subCommand);
|
|
2102
|
+
});
|
|
2103
|
+
});
|
|
2104
|
+
return result;
|
|
2105
|
+
}
|
|
2106
|
+
/**
|
|
2107
|
+
* Process arguments in context of this command.
|
|
2108
|
+
* Returns action result, in case it is a promise.
|
|
2109
|
+
*
|
|
2110
|
+
* @private
|
|
2111
|
+
*/
|
|
2112
|
+
_parseCommand(operands, unknown) {
|
|
2113
|
+
const parsed = this.parseOptions(unknown);
|
|
2114
|
+
this._parseOptionsEnv();
|
|
2115
|
+
this._parseOptionsImplied();
|
|
2116
|
+
operands = operands.concat(parsed.operands);
|
|
2117
|
+
unknown = parsed.unknown;
|
|
2118
|
+
this.args = operands.concat(unknown);
|
|
2119
|
+
if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2120
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
|
|
2121
|
+
if (this._defaultCommandName) {
|
|
2122
|
+
this._outputHelpIfRequested(unknown);
|
|
2123
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
2124
|
+
}
|
|
2125
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
|
|
2126
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2127
|
+
this._checkForMissingMandatoryOptions();
|
|
2128
|
+
this._checkForConflictingOptions();
|
|
2129
|
+
const checkForUnknownOptions = () => {
|
|
2130
|
+
if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
|
|
2131
|
+
};
|
|
2132
|
+
const commandEvent = `command:${this.name()}`;
|
|
2133
|
+
if (this._actionHandler) {
|
|
2134
|
+
checkForUnknownOptions();
|
|
2135
|
+
this._processArguments();
|
|
2136
|
+
let promiseChain;
|
|
2137
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2138
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
2139
|
+
if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2140
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2141
|
+
});
|
|
2142
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2143
|
+
return promiseChain;
|
|
2144
|
+
}
|
|
2145
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2146
|
+
checkForUnknownOptions();
|
|
2147
|
+
this._processArguments();
|
|
2148
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2149
|
+
} else if (operands.length) {
|
|
2150
|
+
if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
|
|
2151
|
+
if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
|
|
2152
|
+
else if (this.commands.length) this.unknownCommand();
|
|
2153
|
+
else {
|
|
2154
|
+
checkForUnknownOptions();
|
|
2155
|
+
this._processArguments();
|
|
2156
|
+
}
|
|
2157
|
+
} else if (this.commands.length) {
|
|
2158
|
+
checkForUnknownOptions();
|
|
2159
|
+
this.help({ error: true });
|
|
2160
|
+
} else {
|
|
2161
|
+
checkForUnknownOptions();
|
|
2162
|
+
this._processArguments();
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
/**
|
|
2166
|
+
* Find matching command.
|
|
2167
|
+
*
|
|
2168
|
+
* @private
|
|
2169
|
+
* @return {Command | undefined}
|
|
2170
|
+
*/
|
|
2171
|
+
_findCommand(name) {
|
|
2172
|
+
if (!name) return void 0;
|
|
2173
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
2174
|
+
}
|
|
2175
|
+
/**
|
|
2176
|
+
* Return an option matching `arg` if any.
|
|
2177
|
+
*
|
|
2178
|
+
* @param {string} arg
|
|
2179
|
+
* @return {Option}
|
|
2180
|
+
* @package
|
|
2181
|
+
*/
|
|
2182
|
+
_findOption(arg) {
|
|
2183
|
+
return this.options.find((option) => option.is(arg));
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2187
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2188
|
+
*
|
|
2189
|
+
* @private
|
|
2190
|
+
*/
|
|
2191
|
+
_checkForMissingMandatoryOptions() {
|
|
2192
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2193
|
+
cmd.options.forEach((anOption) => {
|
|
2194
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
|
|
2195
|
+
});
|
|
2196
|
+
});
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* Display an error message if conflicting options are used together in this.
|
|
2200
|
+
*
|
|
2201
|
+
* @private
|
|
2202
|
+
*/
|
|
2203
|
+
_checkForConflictingLocalOptions() {
|
|
2204
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2205
|
+
const optionKey = option.attributeName();
|
|
2206
|
+
if (this.getOptionValue(optionKey) === void 0) return false;
|
|
2207
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2208
|
+
});
|
|
2209
|
+
definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
|
|
2210
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
2211
|
+
if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
|
|
2212
|
+
});
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Display an error message if conflicting options are used together.
|
|
2216
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2217
|
+
*
|
|
2218
|
+
* @private
|
|
2219
|
+
*/
|
|
2220
|
+
_checkForConflictingOptions() {
|
|
2221
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2222
|
+
cmd._checkForConflictingLocalOptions();
|
|
2223
|
+
});
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* Parse options from `argv` removing known options,
|
|
2227
|
+
* and return argv split into operands and unknown arguments.
|
|
2228
|
+
*
|
|
2229
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2230
|
+
*
|
|
2231
|
+
* Examples:
|
|
2232
|
+
*
|
|
2233
|
+
* argv => operands, unknown
|
|
2234
|
+
* --known kkk op => [op], []
|
|
2235
|
+
* op --known kkk => [op], []
|
|
2236
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2237
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2238
|
+
*
|
|
2239
|
+
* @param {string[]} args
|
|
2240
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2241
|
+
*/
|
|
2242
|
+
parseOptions(args) {
|
|
2243
|
+
const operands = [];
|
|
2244
|
+
const unknown = [];
|
|
2245
|
+
let dest = operands;
|
|
2246
|
+
function maybeOption(arg) {
|
|
2247
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2248
|
+
}
|
|
2249
|
+
const negativeNumberArg = (arg) => {
|
|
2250
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2251
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
2252
|
+
};
|
|
2253
|
+
let activeVariadicOption = null;
|
|
2254
|
+
let activeGroup = null;
|
|
2255
|
+
let i = 0;
|
|
2256
|
+
while (i < args.length || activeGroup) {
|
|
2257
|
+
const arg = activeGroup ?? args[i++];
|
|
2258
|
+
activeGroup = null;
|
|
2259
|
+
if (arg === "--") {
|
|
2260
|
+
if (dest === unknown) dest.push(arg);
|
|
2261
|
+
dest.push(...args.slice(i));
|
|
2262
|
+
break;
|
|
2263
|
+
}
|
|
2264
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2265
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2266
|
+
continue;
|
|
2267
|
+
}
|
|
2268
|
+
activeVariadicOption = null;
|
|
2269
|
+
if (maybeOption(arg)) {
|
|
2270
|
+
const option = this._findOption(arg);
|
|
2271
|
+
if (option) {
|
|
2272
|
+
if (option.required) {
|
|
2273
|
+
const value = args[i++];
|
|
2274
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2275
|
+
this.emit(`option:${option.name()}`, value);
|
|
2276
|
+
} else if (option.optional) {
|
|
2277
|
+
let value = null;
|
|
2278
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
|
|
2279
|
+
this.emit(`option:${option.name()}`, value);
|
|
2280
|
+
} else this.emit(`option:${option.name()}`);
|
|
2281
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2286
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2287
|
+
if (option) {
|
|
2288
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2289
|
+
else {
|
|
2290
|
+
this.emit(`option:${option.name()}`);
|
|
2291
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2292
|
+
}
|
|
2293
|
+
continue;
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2297
|
+
const index = arg.indexOf("=");
|
|
2298
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2299
|
+
if (option && (option.required || option.optional)) {
|
|
2300
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2301
|
+
continue;
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
|
|
2305
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2306
|
+
if (this._findCommand(arg)) {
|
|
2307
|
+
operands.push(arg);
|
|
2308
|
+
unknown.push(...args.slice(i));
|
|
2309
|
+
break;
|
|
2310
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2311
|
+
operands.push(arg, ...args.slice(i));
|
|
2312
|
+
break;
|
|
2313
|
+
} else if (this._defaultCommandName) {
|
|
2314
|
+
unknown.push(arg, ...args.slice(i));
|
|
2315
|
+
break;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
if (this._passThroughOptions) {
|
|
2319
|
+
dest.push(arg, ...args.slice(i));
|
|
2320
|
+
break;
|
|
2321
|
+
}
|
|
2322
|
+
dest.push(arg);
|
|
2323
|
+
}
|
|
2324
|
+
return {
|
|
2325
|
+
operands,
|
|
2326
|
+
unknown
|
|
2327
|
+
};
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Return an object containing local option values as key-value pairs.
|
|
2331
|
+
*
|
|
2332
|
+
* @return {object}
|
|
2333
|
+
*/
|
|
2334
|
+
opts() {
|
|
2335
|
+
if (this._storeOptionsAsProperties) {
|
|
2336
|
+
const result = {};
|
|
2337
|
+
const len = this.options.length;
|
|
2338
|
+
for (let i = 0; i < len; i++) {
|
|
2339
|
+
const key = this.options[i].attributeName();
|
|
2340
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2341
|
+
}
|
|
2342
|
+
return result;
|
|
2343
|
+
}
|
|
2344
|
+
return this._optionValues;
|
|
2345
|
+
}
|
|
2346
|
+
/**
|
|
2347
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2348
|
+
*
|
|
2349
|
+
* @return {object}
|
|
2350
|
+
*/
|
|
2351
|
+
optsWithGlobals() {
|
|
2352
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
2353
|
+
}
|
|
2354
|
+
/**
|
|
2355
|
+
* Display error message and exit (or call exitOverride).
|
|
2356
|
+
*
|
|
2357
|
+
* @param {string} message
|
|
2358
|
+
* @param {object} [errorOptions]
|
|
2359
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2360
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2361
|
+
*/
|
|
2362
|
+
error(message, errorOptions) {
|
|
2363
|
+
this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
|
|
2364
|
+
if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
|
|
2365
|
+
else if (this._showHelpAfterError) {
|
|
2366
|
+
this._outputConfiguration.writeErr("\n");
|
|
2367
|
+
this.outputHelp({ error: true });
|
|
2368
|
+
}
|
|
2369
|
+
const config = errorOptions || {};
|
|
2370
|
+
const exitCode = config.exitCode || 1;
|
|
2371
|
+
const code = config.code || "commander.error";
|
|
2372
|
+
this._exit(exitCode, code, message);
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Apply any option related environment variables, if option does
|
|
2376
|
+
* not have a value from cli or client code.
|
|
2377
|
+
*
|
|
2378
|
+
* @private
|
|
2379
|
+
*/
|
|
2380
|
+
_parseOptionsEnv() {
|
|
2381
|
+
this.options.forEach((option) => {
|
|
2382
|
+
if (option.envVar && option.envVar in process$1.env) {
|
|
2383
|
+
const optionKey = option.attributeName();
|
|
2384
|
+
if (this.getOptionValue(optionKey) === void 0 || [
|
|
2385
|
+
"default",
|
|
2386
|
+
"config",
|
|
2387
|
+
"env"
|
|
2388
|
+
].includes(this.getOptionValueSource(optionKey))) {
|
|
2389
|
+
if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
|
|
2390
|
+
else this.emit(`optionEnv:${option.name()}`);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
});
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2397
|
+
*
|
|
2398
|
+
* @private
|
|
2399
|
+
*/
|
|
2400
|
+
_parseOptionsImplied() {
|
|
2401
|
+
const dualHelper = new DualOptions(this.options);
|
|
2402
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2403
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2404
|
+
};
|
|
2405
|
+
this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
2406
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2407
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
2408
|
+
});
|
|
2409
|
+
});
|
|
2410
|
+
}
|
|
2411
|
+
/**
|
|
2412
|
+
* Argument `name` is missing.
|
|
2413
|
+
*
|
|
2414
|
+
* @param {string} name
|
|
2415
|
+
* @private
|
|
2416
|
+
*/
|
|
2417
|
+
missingArgument(name) {
|
|
2418
|
+
const message = `error: missing required argument '${name}'`;
|
|
2419
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* `Option` is missing an argument.
|
|
2423
|
+
*
|
|
2424
|
+
* @param {Option} option
|
|
2425
|
+
* @private
|
|
2426
|
+
*/
|
|
2427
|
+
optionMissingArgument(option) {
|
|
2428
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2429
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2433
|
+
*
|
|
2434
|
+
* @param {Option} option
|
|
2435
|
+
* @private
|
|
2436
|
+
*/
|
|
2437
|
+
missingMandatoryOptionValue(option) {
|
|
2438
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2439
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2440
|
+
}
|
|
2441
|
+
/**
|
|
2442
|
+
* `Option` conflicts with another option.
|
|
2443
|
+
*
|
|
2444
|
+
* @param {Option} option
|
|
2445
|
+
* @param {Option} conflictingOption
|
|
2446
|
+
* @private
|
|
2447
|
+
*/
|
|
2448
|
+
_conflictingOption(option, conflictingOption) {
|
|
2449
|
+
const findBestOptionFromValue = (option) => {
|
|
2450
|
+
const optionKey = option.attributeName();
|
|
2451
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2452
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
2453
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
2454
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
|
|
2455
|
+
return positiveOption || option;
|
|
2456
|
+
};
|
|
2457
|
+
const getErrorMessage = (option) => {
|
|
2458
|
+
const bestOption = findBestOptionFromValue(option);
|
|
2459
|
+
const optionKey = bestOption.attributeName();
|
|
2460
|
+
if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
|
|
2461
|
+
return `option '${bestOption.flags}'`;
|
|
2462
|
+
};
|
|
2463
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2464
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* Unknown option `flag`.
|
|
2468
|
+
*
|
|
2469
|
+
* @param {string} flag
|
|
2470
|
+
* @private
|
|
2471
|
+
*/
|
|
2472
|
+
unknownOption(flag) {
|
|
2473
|
+
if (this._allowUnknownOption) return;
|
|
2474
|
+
let suggestion = "";
|
|
2475
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2476
|
+
let candidateFlags = [];
|
|
2477
|
+
let command = this;
|
|
2478
|
+
do {
|
|
2479
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2480
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2481
|
+
command = command.parent;
|
|
2482
|
+
} while (command && !command._enablePositionalOptions);
|
|
2483
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2484
|
+
}
|
|
2485
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2486
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* Excess arguments, more than expected.
|
|
2490
|
+
*
|
|
2491
|
+
* @param {string[]} receivedArgs
|
|
2492
|
+
* @private
|
|
2493
|
+
*/
|
|
2494
|
+
_excessArguments(receivedArgs) {
|
|
2495
|
+
if (this._allowExcessArguments) return;
|
|
2496
|
+
const expected = this.registeredArguments.length;
|
|
2497
|
+
const s = expected === 1 ? "" : "s";
|
|
2498
|
+
const received = receivedArgs.length;
|
|
2499
|
+
const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
|
|
2500
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2501
|
+
}
|
|
2502
|
+
/**
|
|
2503
|
+
* Unknown command.
|
|
2504
|
+
*
|
|
2505
|
+
* @private
|
|
2506
|
+
*/
|
|
2507
|
+
unknownCommand() {
|
|
2508
|
+
const unknownName = this.args[0];
|
|
2509
|
+
let suggestion = "";
|
|
2510
|
+
if (this._showSuggestionAfterError) {
|
|
2511
|
+
const candidateNames = [];
|
|
2512
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2513
|
+
candidateNames.push(command.name());
|
|
2514
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2515
|
+
});
|
|
2516
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2517
|
+
}
|
|
2518
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2519
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2520
|
+
}
|
|
2521
|
+
/**
|
|
2522
|
+
* Get or set the program version.
|
|
2523
|
+
*
|
|
2524
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2525
|
+
*
|
|
2526
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2527
|
+
*
|
|
2528
|
+
* @param {string} [str]
|
|
2529
|
+
* @param {string} [flags]
|
|
2530
|
+
* @param {string} [description]
|
|
2531
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2532
|
+
*/
|
|
2533
|
+
version(str, flags, description) {
|
|
2534
|
+
if (str === void 0) return this._version;
|
|
2535
|
+
this._version = str;
|
|
2536
|
+
flags = flags || "-V, --version";
|
|
2537
|
+
description = description || "output the version number";
|
|
2538
|
+
const versionOption = this.createOption(flags, description);
|
|
2539
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2540
|
+
this._registerOption(versionOption);
|
|
2541
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2542
|
+
this._outputConfiguration.writeOut(`${str}\n`);
|
|
2543
|
+
this._exit(0, "commander.version", str);
|
|
2544
|
+
});
|
|
2545
|
+
return this;
|
|
2546
|
+
}
|
|
2547
|
+
/**
|
|
2548
|
+
* Set the description.
|
|
2549
|
+
*
|
|
2550
|
+
* @param {string} [str]
|
|
2551
|
+
* @param {object} [argsDescription]
|
|
2552
|
+
* @return {(string|Command)}
|
|
2553
|
+
*/
|
|
2554
|
+
description(str, argsDescription) {
|
|
2555
|
+
if (str === void 0 && argsDescription === void 0) return this._description;
|
|
2556
|
+
this._description = str;
|
|
2557
|
+
if (argsDescription) this._argsDescription = argsDescription;
|
|
2558
|
+
return this;
|
|
2559
|
+
}
|
|
2560
|
+
/**
|
|
2561
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2562
|
+
*
|
|
2563
|
+
* @param {string} [str]
|
|
2564
|
+
* @return {(string|Command)}
|
|
2565
|
+
*/
|
|
2566
|
+
summary(str) {
|
|
2567
|
+
if (str === void 0) return this._summary;
|
|
2568
|
+
this._summary = str;
|
|
2569
|
+
return this;
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Set an alias for the command.
|
|
2573
|
+
*
|
|
2574
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2575
|
+
*
|
|
2576
|
+
* @param {string} [alias]
|
|
2577
|
+
* @return {(string|Command)}
|
|
2578
|
+
*/
|
|
2579
|
+
alias(alias) {
|
|
2580
|
+
if (alias === void 0) return this._aliases[0];
|
|
2581
|
+
/** @type {Command} */
|
|
2582
|
+
let command = this;
|
|
2583
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
|
|
2584
|
+
if (alias === command._name) throw new Error("Command alias can't be the same as its name");
|
|
2585
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2586
|
+
if (matchingCommand) {
|
|
2587
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2588
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
2589
|
+
}
|
|
2590
|
+
command._aliases.push(alias);
|
|
2591
|
+
return this;
|
|
2592
|
+
}
|
|
2593
|
+
/**
|
|
2594
|
+
* Set aliases for the command.
|
|
2595
|
+
*
|
|
2596
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2597
|
+
*
|
|
2598
|
+
* @param {string[]} [aliases]
|
|
2599
|
+
* @return {(string[]|Command)}
|
|
2600
|
+
*/
|
|
2601
|
+
aliases(aliases) {
|
|
2602
|
+
if (aliases === void 0) return this._aliases;
|
|
2603
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2604
|
+
return this;
|
|
2605
|
+
}
|
|
2606
|
+
/**
|
|
2607
|
+
* Set / get the command usage `str`.
|
|
2608
|
+
*
|
|
2609
|
+
* @param {string} [str]
|
|
2610
|
+
* @return {(string|Command)}
|
|
2611
|
+
*/
|
|
2612
|
+
usage(str) {
|
|
2613
|
+
if (str === void 0) {
|
|
2614
|
+
if (this._usage) return this._usage;
|
|
2615
|
+
const args = this.registeredArguments.map((arg) => {
|
|
2616
|
+
return humanReadableArgName(arg);
|
|
2617
|
+
});
|
|
2618
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
2619
|
+
}
|
|
2620
|
+
this._usage = str;
|
|
2621
|
+
return this;
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Get or set the name of the command.
|
|
2625
|
+
*
|
|
2626
|
+
* @param {string} [str]
|
|
2627
|
+
* @return {(string|Command)}
|
|
2628
|
+
*/
|
|
2629
|
+
name(str) {
|
|
2630
|
+
if (str === void 0) return this._name;
|
|
2631
|
+
this._name = str;
|
|
2632
|
+
return this;
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
2636
|
+
*
|
|
2637
|
+
* @param {string} [heading]
|
|
2638
|
+
* @return {Command | string}
|
|
2639
|
+
*/
|
|
2640
|
+
helpGroup(heading) {
|
|
2641
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
2642
|
+
this._helpGroupHeading = heading;
|
|
2643
|
+
return this;
|
|
2644
|
+
}
|
|
2645
|
+
/**
|
|
2646
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
2647
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
2648
|
+
*
|
|
2649
|
+
* @example
|
|
2650
|
+
* program.commandsGroup('Development Commands:);
|
|
2651
|
+
* program.command('watch')...
|
|
2652
|
+
* program.command('lint')...
|
|
2653
|
+
* ...
|
|
2654
|
+
*
|
|
2655
|
+
* @param {string} [heading]
|
|
2656
|
+
* @returns {Command | string}
|
|
2657
|
+
*/
|
|
2658
|
+
commandsGroup(heading) {
|
|
2659
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
2660
|
+
this._defaultCommandGroup = heading;
|
|
2661
|
+
return this;
|
|
2662
|
+
}
|
|
2663
|
+
/**
|
|
2664
|
+
* Set/get the default help group heading for options added to this command.
|
|
2665
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
2666
|
+
*
|
|
2667
|
+
* @example
|
|
2668
|
+
* program
|
|
2669
|
+
* .optionsGroup('Development Options:')
|
|
2670
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
2671
|
+
* .option('-p, --profile', 'output profiling information')
|
|
2672
|
+
*
|
|
2673
|
+
* @param {string} [heading]
|
|
2674
|
+
* @returns {Command | string}
|
|
2675
|
+
*/
|
|
2676
|
+
optionsGroup(heading) {
|
|
2677
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
2678
|
+
this._defaultOptionGroup = heading;
|
|
2679
|
+
return this;
|
|
2680
|
+
}
|
|
2681
|
+
/**
|
|
2682
|
+
* @param {Option} option
|
|
2683
|
+
* @private
|
|
2684
|
+
*/
|
|
2685
|
+
_initOptionGroup(option) {
|
|
2686
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
|
|
2687
|
+
}
|
|
2688
|
+
/**
|
|
2689
|
+
* @param {Command} cmd
|
|
2690
|
+
* @private
|
|
2691
|
+
*/
|
|
2692
|
+
_initCommandGroup(cmd) {
|
|
2693
|
+
if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
|
|
2694
|
+
}
|
|
2695
|
+
/**
|
|
2696
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
2697
|
+
* or import.meta.filename.
|
|
2698
|
+
*
|
|
2699
|
+
* (Used internally and public although not documented in README.)
|
|
2700
|
+
*
|
|
2701
|
+
* @example
|
|
2702
|
+
* program.nameFromFilename(import.meta.filename);
|
|
2703
|
+
*
|
|
2704
|
+
* @param {string} filename
|
|
2705
|
+
* @return {Command}
|
|
2706
|
+
*/
|
|
2707
|
+
nameFromFilename(filename) {
|
|
2708
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
2709
|
+
return this;
|
|
2710
|
+
}
|
|
2711
|
+
/**
|
|
2712
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
2713
|
+
*
|
|
2714
|
+
* @example
|
|
2715
|
+
* program.executableDir(import.meta.dirname);
|
|
2716
|
+
* // or
|
|
2717
|
+
* program.executableDir('subcommands');
|
|
2718
|
+
*
|
|
2719
|
+
* @param {string} [path]
|
|
2720
|
+
* @return {(string|null|Command)}
|
|
2721
|
+
*/
|
|
2722
|
+
executableDir(path) {
|
|
2723
|
+
if (path === void 0) return this._executableDir;
|
|
2724
|
+
this._executableDir = path;
|
|
2725
|
+
return this;
|
|
2726
|
+
}
|
|
2727
|
+
/**
|
|
2728
|
+
* Return program help documentation.
|
|
2729
|
+
*
|
|
2730
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
2731
|
+
* @return {string}
|
|
2732
|
+
*/
|
|
2733
|
+
helpInformation(contextOptions) {
|
|
2734
|
+
const helper = this.createHelp();
|
|
2735
|
+
const context = this._getOutputContext(contextOptions);
|
|
2736
|
+
helper.prepareContext({
|
|
2737
|
+
error: context.error,
|
|
2738
|
+
helpWidth: context.helpWidth,
|
|
2739
|
+
outputHasColors: context.hasColors
|
|
2740
|
+
});
|
|
2741
|
+
const text = helper.formatHelp(this, helper);
|
|
2742
|
+
if (context.hasColors) return text;
|
|
2743
|
+
return this._outputConfiguration.stripColor(text);
|
|
2744
|
+
}
|
|
2745
|
+
/**
|
|
2746
|
+
* @typedef HelpContext
|
|
2747
|
+
* @type {object}
|
|
2748
|
+
* @property {boolean} error
|
|
2749
|
+
* @property {number} helpWidth
|
|
2750
|
+
* @property {boolean} hasColors
|
|
2751
|
+
* @property {function} write - includes stripColor if needed
|
|
2752
|
+
*
|
|
2753
|
+
* @returns {HelpContext}
|
|
2754
|
+
* @private
|
|
2755
|
+
*/
|
|
2756
|
+
_getOutputContext(contextOptions) {
|
|
2757
|
+
contextOptions = contextOptions || {};
|
|
2758
|
+
const error = !!contextOptions.error;
|
|
2759
|
+
let baseWrite;
|
|
2760
|
+
let hasColors;
|
|
2761
|
+
let helpWidth;
|
|
2762
|
+
if (error) {
|
|
2763
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
2764
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
2765
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
2766
|
+
} else {
|
|
2767
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
2768
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
2769
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
2770
|
+
}
|
|
2771
|
+
const write = (str) => {
|
|
2772
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
2773
|
+
return baseWrite(str);
|
|
2774
|
+
};
|
|
2775
|
+
return {
|
|
2776
|
+
error,
|
|
2777
|
+
write,
|
|
2778
|
+
hasColors,
|
|
2779
|
+
helpWidth
|
|
2780
|
+
};
|
|
2781
|
+
}
|
|
2782
|
+
/**
|
|
2783
|
+
* Output help information for this command.
|
|
2784
|
+
*
|
|
2785
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2786
|
+
*
|
|
2787
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2788
|
+
*/
|
|
2789
|
+
outputHelp(contextOptions) {
|
|
2790
|
+
let deprecatedCallback;
|
|
2791
|
+
if (typeof contextOptions === "function") {
|
|
2792
|
+
deprecatedCallback = contextOptions;
|
|
2793
|
+
contextOptions = void 0;
|
|
2794
|
+
}
|
|
2795
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
2796
|
+
/** @type {HelpTextEventContext} */
|
|
2797
|
+
const eventContext = {
|
|
2798
|
+
error: outputContext.error,
|
|
2799
|
+
write: outputContext.write,
|
|
2800
|
+
command: this
|
|
2801
|
+
};
|
|
2802
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
2803
|
+
this.emit("beforeHelp", eventContext);
|
|
2804
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
2805
|
+
if (deprecatedCallback) {
|
|
2806
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
2807
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
|
|
2808
|
+
}
|
|
2809
|
+
outputContext.write(helpInformation);
|
|
2810
|
+
if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
|
|
2811
|
+
this.emit("afterHelp", eventContext);
|
|
2812
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
2813
|
+
}
|
|
2814
|
+
/**
|
|
2815
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
2816
|
+
* Pass in false to disable the built-in help option.
|
|
2817
|
+
*
|
|
2818
|
+
* @example
|
|
2819
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
2820
|
+
* program.helpOption(false); // disable
|
|
2821
|
+
*
|
|
2822
|
+
* @param {(string | boolean)} flags
|
|
2823
|
+
* @param {string} [description]
|
|
2824
|
+
* @return {Command} `this` command for chaining
|
|
2825
|
+
*/
|
|
2826
|
+
helpOption(flags, description) {
|
|
2827
|
+
if (typeof flags === "boolean") {
|
|
2828
|
+
if (flags) {
|
|
2829
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
2830
|
+
if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
|
|
2831
|
+
} else this._helpOption = null;
|
|
2832
|
+
return this;
|
|
2833
|
+
}
|
|
2834
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
2835
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
2836
|
+
return this;
|
|
2837
|
+
}
|
|
2838
|
+
/**
|
|
2839
|
+
* Lazy create help option.
|
|
2840
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
2841
|
+
*
|
|
2842
|
+
* @returns {(Option | null)} the help option
|
|
2843
|
+
* @package
|
|
2844
|
+
*/
|
|
2845
|
+
_getHelpOption() {
|
|
2846
|
+
if (this._helpOption === void 0) this.helpOption(void 0, void 0);
|
|
2847
|
+
return this._helpOption;
|
|
2848
|
+
}
|
|
2849
|
+
/**
|
|
2850
|
+
* Supply your own option to use for the built-in help option.
|
|
2851
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
2852
|
+
*
|
|
2853
|
+
* @param {Option} option
|
|
2854
|
+
* @return {Command} `this` command for chaining
|
|
2855
|
+
*/
|
|
2856
|
+
addHelpOption(option) {
|
|
2857
|
+
this._helpOption = option;
|
|
2858
|
+
this._initOptionGroup(option);
|
|
2859
|
+
return this;
|
|
2860
|
+
}
|
|
2861
|
+
/**
|
|
2862
|
+
* Output help information and exit.
|
|
2863
|
+
*
|
|
2864
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
2865
|
+
*
|
|
2866
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
2867
|
+
*/
|
|
2868
|
+
help(contextOptions) {
|
|
2869
|
+
this.outputHelp(contextOptions);
|
|
2870
|
+
let exitCode = Number(process$1.exitCode ?? 0);
|
|
2871
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
|
|
2872
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
2873
|
+
}
|
|
2874
|
+
/**
|
|
2875
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
2876
|
+
* @typedef HelpTextEventContext
|
|
2877
|
+
* @type {object}
|
|
2878
|
+
* @property {boolean} error
|
|
2879
|
+
* @property {Command} command
|
|
2880
|
+
* @property {function} write
|
|
2881
|
+
*/
|
|
2882
|
+
/**
|
|
2883
|
+
* Add additional text to be displayed with the built-in help.
|
|
2884
|
+
*
|
|
2885
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
2886
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
2887
|
+
*
|
|
2888
|
+
* @param {string} position - before or after built-in help
|
|
2889
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
2890
|
+
* @return {Command} `this` command for chaining
|
|
2891
|
+
*/
|
|
2892
|
+
addHelpText(position, text) {
|
|
2893
|
+
const allowedValues = [
|
|
2894
|
+
"beforeAll",
|
|
2895
|
+
"before",
|
|
2896
|
+
"after",
|
|
2897
|
+
"afterAll"
|
|
2898
|
+
];
|
|
2899
|
+
if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
|
|
2900
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
2901
|
+
const helpEvent = `${position}Help`;
|
|
2902
|
+
this.on(helpEvent, (context) => {
|
|
2903
|
+
let helpStr;
|
|
2904
|
+
if (typeof text === "function") helpStr = text({
|
|
2905
|
+
error: context.error,
|
|
2906
|
+
command: context.command
|
|
2907
|
+
});
|
|
2908
|
+
else helpStr = text;
|
|
2909
|
+
if (helpStr) context.write(`${helpStr}\n`);
|
|
2910
|
+
});
|
|
2911
|
+
return this;
|
|
2912
|
+
}
|
|
2913
|
+
/**
|
|
2914
|
+
* Output help information if help flags specified
|
|
2915
|
+
*
|
|
2916
|
+
* @param {Array} args - array of options to search for help flags
|
|
2917
|
+
* @private
|
|
2918
|
+
*/
|
|
2919
|
+
_outputHelpIfRequested(args) {
|
|
2920
|
+
const helpOption = this._getHelpOption();
|
|
2921
|
+
if (helpOption && args.find((arg) => helpOption.is(arg))) {
|
|
2922
|
+
this.outputHelp();
|
|
2923
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2924
|
+
}
|
|
2925
|
+
}
|
|
2926
|
+
};
|
|
2927
|
+
/**
|
|
2928
|
+
* Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
|
|
2929
|
+
*
|
|
2930
|
+
* @param {string[]} args - array of arguments from node.execArgv
|
|
2931
|
+
* @returns {string[]}
|
|
2932
|
+
* @private
|
|
2933
|
+
*/
|
|
2934
|
+
function incrementNodeInspectorPort(args) {
|
|
2935
|
+
return args.map((arg) => {
|
|
2936
|
+
if (!arg.startsWith("--inspect")) return arg;
|
|
2937
|
+
let debugOption;
|
|
2938
|
+
let debugHost = "127.0.0.1";
|
|
2939
|
+
let debugPort = "9229";
|
|
2940
|
+
let match;
|
|
2941
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
|
|
2942
|
+
else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2943
|
+
debugOption = match[1];
|
|
2944
|
+
if (/^\d+$/.test(match[3])) debugPort = match[3];
|
|
2945
|
+
else debugHost = match[3];
|
|
2946
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2947
|
+
debugOption = match[1];
|
|
2948
|
+
debugHost = match[3];
|
|
2949
|
+
debugPort = match[4];
|
|
2950
|
+
}
|
|
2951
|
+
if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2952
|
+
return arg;
|
|
2953
|
+
});
|
|
2954
|
+
}
|
|
2955
|
+
/**
|
|
2956
|
+
* Exported for using from tests, not otherwise used outside this file.
|
|
2957
|
+
*
|
|
2958
|
+
* @returns {boolean | undefined}
|
|
2959
|
+
* @package
|
|
2960
|
+
*/
|
|
2961
|
+
function useColor() {
|
|
2962
|
+
if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
|
|
2963
|
+
if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
|
|
2964
|
+
}
|
|
2965
|
+
new Command();
|
|
2966
|
+
//#endregion
|
|
2967
|
+
//#region src/blobs.ts
|
|
2968
|
+
/** 流式算 hash,避免把大图整份读进内存。 */
|
|
2969
|
+
function sha256File(path) {
|
|
2970
|
+
return new Promise((res, rej) => {
|
|
2971
|
+
const h = createHash("sha256");
|
|
2972
|
+
const rs = createReadStream(path);
|
|
2973
|
+
rs.on("error", rej);
|
|
2974
|
+
rs.on("data", (chunk) => h.update(chunk));
|
|
2975
|
+
rs.on("end", () => res(h.digest("hex")));
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
var MIME = Object.freeze({
|
|
2979
|
+
".md": "text/markdown; charset=utf-8",
|
|
2980
|
+
".markdown": "text/markdown; charset=utf-8",
|
|
2981
|
+
".txt": "text/plain; charset=utf-8",
|
|
2982
|
+
".json": "application/json",
|
|
2983
|
+
".js": "text/javascript; charset=utf-8",
|
|
2984
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
2985
|
+
".css": "text/css; charset=utf-8",
|
|
2986
|
+
".html": "text/html; charset=utf-8",
|
|
2987
|
+
".svg": "image/svg+xml",
|
|
2988
|
+
".png": "image/png",
|
|
2989
|
+
".jpg": "image/jpeg",
|
|
2990
|
+
".jpeg": "image/jpeg",
|
|
2991
|
+
".gif": "image/gif",
|
|
2992
|
+
".webp": "image/webp",
|
|
2993
|
+
".avif": "image/avif",
|
|
2994
|
+
".ico": "image/x-icon",
|
|
2995
|
+
".mp4": "video/mp4",
|
|
2996
|
+
".webm": "video/webm",
|
|
2997
|
+
".mov": "video/quicktime",
|
|
2998
|
+
".mp3": "audio/mpeg",
|
|
2999
|
+
".wav": "audio/wav",
|
|
3000
|
+
".pdf": "application/pdf",
|
|
3001
|
+
".zip": "application/zip",
|
|
3002
|
+
".woff2": "font/woff2"
|
|
3003
|
+
});
|
|
3004
|
+
function guessMime(path) {
|
|
3005
|
+
return MIME[extname(path).toLowerCase()] ?? "application/octet-stream";
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* 增量上传:先用 hash 清单跟 server 协商,只 PUT 缺失的。
|
|
3009
|
+
* server 返回体不可解析时按「全都缺」处理 —— 宁可多传也不能漏传导致文档半残。
|
|
3010
|
+
*/
|
|
3011
|
+
async function syncBlobs(api, entries) {
|
|
3012
|
+
const byHash = /* @__PURE__ */ new Map();
|
|
3013
|
+
for (const e of entries) if (!byHash.has(e.hash)) byHash.set(e.hash, e.path);
|
|
3014
|
+
const hashes = [...byHash.keys()];
|
|
3015
|
+
if (hashes.length === 0) return {
|
|
3016
|
+
total: 0,
|
|
3017
|
+
uploaded: [],
|
|
3018
|
+
reused: 0
|
|
3019
|
+
};
|
|
3020
|
+
const res = await api.postJson("/api/blobs/check", { hashes });
|
|
3021
|
+
const missing = Array.isArray(res?.missing) ? res.missing.filter((h) => typeof h === "string") : hashes;
|
|
3022
|
+
const uploaded = [];
|
|
3023
|
+
for (const hash of missing) {
|
|
3024
|
+
const path = byHash.get(hash);
|
|
3025
|
+
if (path === void 0) continue;
|
|
3026
|
+
await api.putBytes(`/api/blobs/${hash}`, readFileSync(path), guessMime(path));
|
|
3027
|
+
uploaded.push(hash);
|
|
3028
|
+
}
|
|
3029
|
+
return {
|
|
3030
|
+
total: hashes.length,
|
|
3031
|
+
uploaded,
|
|
3032
|
+
reused: hashes.length - uploaded.length
|
|
3033
|
+
};
|
|
3034
|
+
}
|
|
3035
|
+
//#endregion
|
|
3036
|
+
//#region src/errors.ts
|
|
3037
|
+
/**
|
|
3038
|
+
* 面向用户的可读错误。
|
|
3039
|
+
*
|
|
3040
|
+
* cli 顶层只打印 message + hint,不吐 stack —— 命令行使用者拿到栈没有任何帮助,
|
|
3041
|
+
* 反而会淹没真正有用的那一行。内部意外错误(bug)才保留原始堆栈。
|
|
3042
|
+
*/
|
|
3043
|
+
var CliError = class extends Error {
|
|
3044
|
+
hint;
|
|
3045
|
+
constructor(message, hint) {
|
|
3046
|
+
super(message);
|
|
3047
|
+
this.name = "CliError";
|
|
3048
|
+
this.hint = hint;
|
|
3049
|
+
}
|
|
3050
|
+
};
|
|
3051
|
+
//#endregion
|
|
3052
|
+
//#region src/oidc.ts
|
|
3053
|
+
/** CLI / server 共用的 OIDC 参数环境变量名。issuer 与 client id 都不内置默认值。 */
|
|
3054
|
+
var OIDC_ISSUER_ENV = "JIANDU_OIDC_ISSUER";
|
|
3055
|
+
var OIDC_CLIENT_ID_ENV = "JIANDU_OIDC_CLIENT_ID";
|
|
3056
|
+
/** loopback PKCE 回调。换端口必须同时改 IdP 里登记的 Redirect URI。 */
|
|
3057
|
+
var DEFAULT_OIDC_LISTEN_HOST = "127.0.0.1";
|
|
3058
|
+
var DEFAULT_OIDC_LISTEN_PORT = 8085;
|
|
3059
|
+
function defaultRedirectUrl() {
|
|
3060
|
+
return `http://${DEFAULT_OIDC_LISTEN_HOST}:${DEFAULT_OIDC_LISTEN_PORT}/callback`;
|
|
3061
|
+
}
|
|
3062
|
+
function pkce() {
|
|
3063
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
3064
|
+
return {
|
|
3065
|
+
verifier,
|
|
3066
|
+
challenge: createHash("sha256").update(verifier).digest("base64url")
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
async function discover(issuer) {
|
|
3070
|
+
const url = `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
3071
|
+
const resp = await fetch(url);
|
|
3072
|
+
if (!resp.ok) throw new CliError(`OIDC discovery ${url}: ${resp.status}`, resp.status === 404 ? `OIDC issuer 无法做 discovery。确认 --issuer / ${OIDC_ISSUER_ENV} 指向带 /.well-known/openid-configuration 的 issuer,且 IdP 登记了 Redirect URI ${defaultRedirectUrl()}` : void 0);
|
|
3073
|
+
const body = await resp.json();
|
|
3074
|
+
const rec = body !== null && typeof body === "object" ? body : {};
|
|
3075
|
+
const authURL = rec["authorization_endpoint"];
|
|
3076
|
+
const tokenURL = rec["token_endpoint"];
|
|
3077
|
+
if (typeof authURL !== "string" || typeof tokenURL !== "string") throw new CliError(`OIDC discovery 响应缺少 endpoint: ${url}`);
|
|
3078
|
+
return {
|
|
3079
|
+
authURL,
|
|
3080
|
+
tokenURL
|
|
3081
|
+
};
|
|
3082
|
+
}
|
|
3083
|
+
function callbackHandler(wantState, onCode) {
|
|
3084
|
+
let done = false;
|
|
3085
|
+
return (req, res) => {
|
|
3086
|
+
const q = new URL(req.url ?? "/", "http://localhost").searchParams;
|
|
3087
|
+
if (q.get("state") !== wantState || !q.get("code")) {
|
|
3088
|
+
res.writeHead(400);
|
|
3089
|
+
res.end("invalid callback");
|
|
3090
|
+
return;
|
|
3091
|
+
}
|
|
3092
|
+
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
|
3093
|
+
res.end("登录成功,可以关闭此页面回到终端。\n");
|
|
3094
|
+
if (!done) {
|
|
3095
|
+
done = true;
|
|
3096
|
+
onCode(q.get("code") ?? "");
|
|
3097
|
+
}
|
|
3098
|
+
};
|
|
3099
|
+
}
|
|
3100
|
+
async function tokenRequest(tokenURL, params) {
|
|
3101
|
+
const resp = await fetch(tokenURL, {
|
|
3102
|
+
method: "POST",
|
|
3103
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
3104
|
+
body: new URLSearchParams(params).toString()
|
|
3105
|
+
});
|
|
3106
|
+
const body = await resp.text();
|
|
3107
|
+
if (!resp.ok) throw new CliError(`token endpoint ${resp.status}: ${body.slice(0, 300)}`);
|
|
3108
|
+
const tok = JSON.parse(body);
|
|
3109
|
+
const access = tok["access_token"];
|
|
3110
|
+
if (typeof access !== "string" || access === "") throw new CliError("token endpoint 没有返回 access_token");
|
|
3111
|
+
const expiresIn = typeof tok["expires_in"] === "number" ? tok["expires_in"] : 0;
|
|
3112
|
+
return {
|
|
3113
|
+
access_token: access,
|
|
3114
|
+
token_type: typeof tok["token_type"] === "string" ? tok["token_type"] : void 0,
|
|
3115
|
+
refresh_token: typeof tok["refresh_token"] === "string" ? tok["refresh_token"] : void 0,
|
|
3116
|
+
expiry: new Date(Date.now() + expiresIn * 1e3).toISOString()
|
|
3117
|
+
};
|
|
3118
|
+
}
|
|
3119
|
+
function openBrowser(url) {
|
|
3120
|
+
const child = process.platform === "win32" ? spawn("cmd", [
|
|
3121
|
+
"/c",
|
|
3122
|
+
"start",
|
|
3123
|
+
"",
|
|
3124
|
+
url
|
|
3125
|
+
], {
|
|
3126
|
+
stdio: "ignore",
|
|
3127
|
+
detached: true
|
|
3128
|
+
}) : spawn(process.platform === "darwin" ? "open" : "xdg-open", [url], {
|
|
3129
|
+
stdio: "ignore",
|
|
3130
|
+
detached: true
|
|
3131
|
+
});
|
|
3132
|
+
child.on("error", () => {
|
|
3133
|
+
process.stderr.write("自动打开浏览器失败,请手动访问上面的地址\n");
|
|
3134
|
+
});
|
|
3135
|
+
child.unref();
|
|
3136
|
+
}
|
|
3137
|
+
async function authorizationCodeLogin(input) {
|
|
3138
|
+
const ep = await discover(input.issuer);
|
|
3139
|
+
const { verifier, challenge } = pkce();
|
|
3140
|
+
const state = randomBytes(16).toString("base64url");
|
|
3141
|
+
const authURL = new URL(ep.authURL);
|
|
3142
|
+
authURL.search = new URLSearchParams({
|
|
3143
|
+
response_type: "code",
|
|
3144
|
+
client_id: input.clientId,
|
|
3145
|
+
redirect_uri: defaultRedirectUrl(),
|
|
3146
|
+
scope: "openid profile email offline_access",
|
|
3147
|
+
state,
|
|
3148
|
+
code_challenge: challenge,
|
|
3149
|
+
code_challenge_method: "S256"
|
|
3150
|
+
}).toString();
|
|
3151
|
+
const code = await new Promise((resolve, reject) => {
|
|
3152
|
+
const finish = (fn) => (value) => {
|
|
3153
|
+
clearTimeout(timer);
|
|
3154
|
+
server.close();
|
|
3155
|
+
fn(value);
|
|
3156
|
+
};
|
|
3157
|
+
const handler = callbackHandler(state, finish(resolve));
|
|
3158
|
+
const server = createServer((req, res) => {
|
|
3159
|
+
if (new URL(req.url ?? "/", "http://localhost").pathname !== "/callback") {
|
|
3160
|
+
res.writeHead(404).end();
|
|
3161
|
+
return;
|
|
3162
|
+
}
|
|
3163
|
+
handler(req, res);
|
|
3164
|
+
});
|
|
3165
|
+
const timer = setTimeout(() => finish((msg) => reject(new CliError(msg)))("等待浏览器回调超时"), 18e4);
|
|
3166
|
+
server.on("error", (err) => {
|
|
3167
|
+
finish((msg) => reject(new CliError(msg)))(`监听 ${defaultRedirectUrl()} 失败(端口被占用?): ${err.message}`);
|
|
3168
|
+
});
|
|
3169
|
+
server.listen(DEFAULT_OIDC_LISTEN_PORT, DEFAULT_OIDC_LISTEN_HOST, () => {
|
|
3170
|
+
process.stderr.write(`在浏览器中完成登录:${authURL.toString()}\n`);
|
|
3171
|
+
(input.open ?? openBrowser)(authURL.toString());
|
|
3172
|
+
});
|
|
3173
|
+
});
|
|
3174
|
+
return tokenRequest(ep.tokenURL, {
|
|
3175
|
+
grant_type: "authorization_code",
|
|
3176
|
+
code,
|
|
3177
|
+
redirect_uri: defaultRedirectUrl(),
|
|
3178
|
+
client_id: input.clientId,
|
|
3179
|
+
code_verifier: verifier
|
|
3180
|
+
});
|
|
3181
|
+
}
|
|
3182
|
+
//#endregion
|
|
3183
|
+
//#region src/oidc-creds.ts
|
|
3184
|
+
var CREDS_FILE = "credentials.json";
|
|
3185
|
+
/** 与 `config.json` 同目录:`~/.config/jiandu/`(尊重 XDG_CONFIG_HOME)。 */
|
|
3186
|
+
function oidcConfigDir() {
|
|
3187
|
+
const xdg = process.env.XDG_CONFIG_HOME?.trim();
|
|
3188
|
+
const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".config");
|
|
3189
|
+
return join(base, "jiandu");
|
|
3190
|
+
}
|
|
3191
|
+
function loadOidcToken(dir = oidcConfigDir()) {
|
|
3192
|
+
const file = join(dir, CREDS_FILE);
|
|
3193
|
+
if (!existsSync(file)) return void 0;
|
|
3194
|
+
try {
|
|
3195
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
3196
|
+
} catch {
|
|
3197
|
+
throw new CliError(`OIDC credential 不是合法 JSON:${file}`, "删除该文件后重新 jdu login");
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
function saveOidcToken(tok, dir = oidcConfigDir()) {
|
|
3201
|
+
mkdirSync(dir, {
|
|
3202
|
+
recursive: true,
|
|
3203
|
+
mode: 448
|
|
3204
|
+
});
|
|
3205
|
+
const file = join(dir, CREDS_FILE);
|
|
3206
|
+
writeFileSync(file, `${JSON.stringify(tok, null, 2)}\n`, { mode: 384 });
|
|
3207
|
+
chmodSync(file, 384);
|
|
3208
|
+
return file;
|
|
3209
|
+
}
|
|
3210
|
+
function oidcTokenValid(tok, now = Date.now()) {
|
|
3211
|
+
if (!tok?.access_token || !tok.expiry) return false;
|
|
3212
|
+
return Date.parse(tok.expiry) - 3e4 > now;
|
|
3213
|
+
}
|
|
3214
|
+
async function freshOidcAccessToken(input) {
|
|
3215
|
+
const dir = input.dir ?? oidcConfigDir();
|
|
3216
|
+
const tok = loadOidcToken(dir);
|
|
3217
|
+
if (tok === void 0) return void 0;
|
|
3218
|
+
if (oidcTokenValid(tok)) return tok.access_token;
|
|
3219
|
+
if (!tok.refresh_token) return void 0;
|
|
3220
|
+
const ep = await discover(input.issuer);
|
|
3221
|
+
let renewed;
|
|
3222
|
+
try {
|
|
3223
|
+
renewed = await tokenRequest(ep.tokenURL, {
|
|
3224
|
+
grant_type: "refresh_token",
|
|
3225
|
+
refresh_token: tok.refresh_token,
|
|
3226
|
+
client_id: input.clientId
|
|
3227
|
+
});
|
|
3228
|
+
} catch (err) {
|
|
3229
|
+
throw new CliError(`OIDC 续期失败:${err instanceof Error ? err.message : String(err)}`, "重新执行 jdu login");
|
|
3230
|
+
}
|
|
3231
|
+
if (!renewed.refresh_token) renewed.refresh_token = tok.refresh_token;
|
|
3232
|
+
saveOidcToken(renewed, dir);
|
|
3233
|
+
return renewed.access_token;
|
|
3234
|
+
}
|
|
3235
|
+
//#endregion
|
|
3236
|
+
//#region src/config.ts
|
|
3237
|
+
/** `~/.config/jiandu/config.json`;尊重 XDG_CONFIG_HOME 便于隔离测试与多环境切换。 */
|
|
3238
|
+
function configPath() {
|
|
3239
|
+
const xdg = process.env.XDG_CONFIG_HOME?.trim();
|
|
3240
|
+
const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".config");
|
|
3241
|
+
return join(base, "jiandu", "config.json");
|
|
3242
|
+
}
|
|
3243
|
+
function readOidc(raw) {
|
|
3244
|
+
if (raw === null || typeof raw !== "object") return void 0;
|
|
3245
|
+
const obj = raw;
|
|
3246
|
+
const issuer = typeof obj.issuer === "string" ? obj.issuer.trim() : "";
|
|
3247
|
+
const clientId = typeof obj.clientId === "string" ? obj.clientId.trim() : "";
|
|
3248
|
+
if (issuer === "" || clientId === "") return void 0;
|
|
3249
|
+
return {
|
|
3250
|
+
issuer,
|
|
3251
|
+
clientId
|
|
3252
|
+
};
|
|
3253
|
+
}
|
|
3254
|
+
function readStoredConfig() {
|
|
3255
|
+
const path = configPath();
|
|
3256
|
+
let raw;
|
|
3257
|
+
try {
|
|
3258
|
+
raw = readFileSync(path, "utf8");
|
|
3259
|
+
} catch (err) {
|
|
3260
|
+
if (err.code === "ENOENT") return {};
|
|
3261
|
+
throw new CliError(`读取配置失败 ${path}:${err.message}`);
|
|
3262
|
+
}
|
|
3263
|
+
let parsed;
|
|
3264
|
+
try {
|
|
3265
|
+
parsed = JSON.parse(raw);
|
|
3266
|
+
} catch {
|
|
3267
|
+
throw new CliError(`配置文件不是合法 JSON:${path}`, "删除该文件后重新执行 jdu login");
|
|
3268
|
+
}
|
|
3269
|
+
if (parsed === null || typeof parsed !== "object") return {};
|
|
3270
|
+
const obj = parsed;
|
|
3271
|
+
const out = {};
|
|
3272
|
+
if (typeof obj.server === "string") out.server = obj.server;
|
|
3273
|
+
if (typeof obj.token === "string") out.token = obj.token;
|
|
3274
|
+
const oidc = readOidc(obj.oidc);
|
|
3275
|
+
if (oidc) out.oidc = oidc;
|
|
3276
|
+
return out;
|
|
3277
|
+
}
|
|
3278
|
+
function saveConfig(next) {
|
|
3279
|
+
const path = configPath();
|
|
3280
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
3281
|
+
const body = { server: next.server };
|
|
3282
|
+
if (next.token !== void 0) body.token = next.token;
|
|
3283
|
+
if (next.oidc !== void 0) body.oidc = next.oidc;
|
|
3284
|
+
writeFileSync(path, `${JSON.stringify(body, null, 2)}\n`, { mode: 384 });
|
|
3285
|
+
return path;
|
|
3286
|
+
}
|
|
3287
|
+
/** 环境变量优先级高于配置文件,方便 CI / 一次性切服务端。 */
|
|
3288
|
+
function loadConfig() {
|
|
3289
|
+
const stored = readStoredConfig();
|
|
3290
|
+
const server = (process.env.JIANDU_SERVER ?? stored.server ?? "").trim().replace(/\/+$/, "");
|
|
3291
|
+
const rawToken = process.env.JIANDU_TOKEN ?? stored.token;
|
|
3292
|
+
if (server === "") throw new CliError("未配置 jiandu server 地址", "执行 jdu login --server <url>,或设置环境变量 JIANDU_SERVER");
|
|
3293
|
+
const cfg = {
|
|
3294
|
+
server,
|
|
3295
|
+
token: rawToken && rawToken.length > 0 ? rawToken : void 0
|
|
3296
|
+
};
|
|
3297
|
+
if (stored.oidc) cfg.oidc = stored.oidc;
|
|
3298
|
+
return cfg;
|
|
3299
|
+
}
|
|
3300
|
+
/** 运行时配置:没有显式 token 时,用已保存 / 环境变量里的 OIDC 客户端去续期。 */
|
|
3301
|
+
async function loadRuntimeConfig() {
|
|
3302
|
+
const cfg = loadConfig();
|
|
3303
|
+
if (cfg.token) return cfg;
|
|
3304
|
+
const issuer = cfg.oidc?.issuer ?? process.env["JIANDU_OIDC_ISSUER"]?.trim();
|
|
3305
|
+
const clientId = cfg.oidc?.clientId ?? process.env["JIANDU_OIDC_CLIENT_ID"]?.trim();
|
|
3306
|
+
if (!issuer || !clientId) return cfg;
|
|
3307
|
+
const token = await freshOidcAccessToken({
|
|
3308
|
+
issuer,
|
|
3309
|
+
clientId
|
|
3310
|
+
});
|
|
3311
|
+
if (token) return {
|
|
3312
|
+
...cfg,
|
|
3313
|
+
token
|
|
3314
|
+
};
|
|
3315
|
+
if (cfg.oidc) throw new CliError("SSO credential 已过期", `重新执行 jdu login --server ${cfg.server}`);
|
|
3316
|
+
return cfg;
|
|
3317
|
+
}
|
|
3318
|
+
//#endregion
|
|
3319
|
+
//#region src/http.ts
|
|
3320
|
+
/** 错误响应体太长会淹没终端,只留头部。 */
|
|
3321
|
+
var MAX_DETAIL = 400;
|
|
3322
|
+
var ApiClient = class {
|
|
3323
|
+
server;
|
|
3324
|
+
token;
|
|
3325
|
+
constructor(cfg) {
|
|
3326
|
+
this.server = cfg.server;
|
|
3327
|
+
this.token = cfg.token;
|
|
3328
|
+
}
|
|
3329
|
+
url(path) {
|
|
3330
|
+
return `${this.server}${path}`;
|
|
3331
|
+
}
|
|
3332
|
+
async getJson(path) {
|
|
3333
|
+
return this.json("GET", path, void 0, void 0);
|
|
3334
|
+
}
|
|
3335
|
+
async postJson(path, body) {
|
|
3336
|
+
return this.json("POST", path, JSON.stringify(body), "application/json");
|
|
3337
|
+
}
|
|
3338
|
+
async putJson(path, body) {
|
|
3339
|
+
return this.json("PUT", path, JSON.stringify(body), "application/json");
|
|
3340
|
+
}
|
|
3341
|
+
async deleteJson(path) {
|
|
3342
|
+
return this.json("DELETE", path, void 0, void 0);
|
|
3343
|
+
}
|
|
3344
|
+
/** widget push 走 multipart:boundary 交给 fetch 生成,别自己设 Content-Type。 */
|
|
3345
|
+
async postForm(path, form) {
|
|
3346
|
+
const text = await (await this.send("POST", path, form, void 0)).text();
|
|
3347
|
+
if (text.trim() === "") return void 0;
|
|
3348
|
+
try {
|
|
3349
|
+
return JSON.parse(text);
|
|
3350
|
+
} catch {
|
|
3351
|
+
throw new CliError(`POST ${this.url(path)} 返回的不是合法 JSON:${clip(text)}`);
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
3354
|
+
/** blob 上传走原始字节,不做任何包装 —— server 直接对 body 校验 sha256。 */
|
|
3355
|
+
async putBytes(path, bytes, contentType) {
|
|
3356
|
+
await this.send("PUT", path, bytes, contentType);
|
|
3357
|
+
}
|
|
3358
|
+
async json(method, path, body, contentType) {
|
|
3359
|
+
const text = await (await this.send(method, path, body, contentType)).text();
|
|
3360
|
+
if (text.trim() === "") return void 0;
|
|
3361
|
+
try {
|
|
3362
|
+
return JSON.parse(text);
|
|
3363
|
+
} catch {
|
|
3364
|
+
throw new CliError(`${method} ${this.url(path)} 返回的不是合法 JSON:${clip(text)}`);
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
async send(method, path, body, contentType) {
|
|
3368
|
+
const url = this.url(path);
|
|
3369
|
+
const headers = {};
|
|
3370
|
+
if (this.token !== void 0) headers.Authorization = `Bearer ${this.token}`;
|
|
3371
|
+
if (contentType !== void 0) headers["Content-Type"] = contentType;
|
|
3372
|
+
let res;
|
|
3373
|
+
try {
|
|
3374
|
+
res = await fetch(url, {
|
|
3375
|
+
method,
|
|
3376
|
+
headers,
|
|
3377
|
+
body,
|
|
3378
|
+
redirect: "manual"
|
|
3379
|
+
});
|
|
3380
|
+
} catch (err) {
|
|
3381
|
+
throw new CliError(`请求 ${method} ${url} 失败:${describeNetworkError(err)}`, "确认 server 已启动、地址与端口正确");
|
|
3382
|
+
}
|
|
3383
|
+
if (!res.ok) throw await httpError(method, url, res);
|
|
3384
|
+
return res;
|
|
3385
|
+
}
|
|
3386
|
+
};
|
|
3387
|
+
function clip(text) {
|
|
3388
|
+
const t = text.trim();
|
|
3389
|
+
return t.length > MAX_DETAIL ? `${t.slice(0, MAX_DETAIL)}…` : t;
|
|
3390
|
+
}
|
|
3391
|
+
/** fetch 失败时真正的原因藏在 cause 里(ECONNREFUSED / ENOTFOUND / 证书错误…)。 */
|
|
3392
|
+
function describeNetworkError(err) {
|
|
3393
|
+
const cause = err?.cause;
|
|
3394
|
+
if (cause instanceof Error) {
|
|
3395
|
+
const code = cause.code;
|
|
3396
|
+
return code ? `${code} ${cause.message}` : cause.message;
|
|
3397
|
+
}
|
|
3398
|
+
return err instanceof Error ? err.message : String(err);
|
|
3399
|
+
}
|
|
3400
|
+
async function httpError(method, url, res) {
|
|
3401
|
+
let detail = "";
|
|
3402
|
+
try {
|
|
3403
|
+
detail = clip(await res.text());
|
|
3404
|
+
} catch {
|
|
3405
|
+
detail = "";
|
|
3406
|
+
}
|
|
3407
|
+
if (detail.startsWith("{")) try {
|
|
3408
|
+
const obj = JSON.parse(detail);
|
|
3409
|
+
const msg = obj.error ?? obj.message;
|
|
3410
|
+
if (typeof msg === "string" && msg !== "") detail = msg;
|
|
3411
|
+
} catch {}
|
|
3412
|
+
const hint = res.status === 401 || res.status === 403 ? "token 无效或无权访问,执行 jdu login --server <url>" : res.status === 302 ? "网关要登录。forward-auth 下先 jdu login;若已登录,网关需接受 Authorization: Bearer" : void 0;
|
|
3413
|
+
const suffix = detail === "" ? "" : `:${detail}`;
|
|
3414
|
+
return new CliError(`${method} ${url} 返回 HTTP ${res.status} ${res.statusText}${suffix}`, hint);
|
|
3415
|
+
}
|
|
3416
|
+
//#endregion
|
|
3417
|
+
//#region src/login.ts
|
|
3418
|
+
var OIDC_PARAM_HINT = `传入 --issuer / --client-id,或在 server 配置 auth.oidc(healthz 会带出来),或设置 ${OIDC_ISSUER_ENV} / ${OIDC_CLIENT_ID_ENV}`;
|
|
3419
|
+
function resolveOidc(input) {
|
|
3420
|
+
const env = input.env ?? process.env;
|
|
3421
|
+
const issuer = input.issuer?.trim() || input.healthz?.oidc?.issuer?.trim() || env["JIANDU_OIDC_ISSUER"]?.trim() || "";
|
|
3422
|
+
const clientId = input.clientId?.trim() || input.healthz?.oidc?.clientId?.trim() || env["JIANDU_OIDC_CLIENT_ID"]?.trim() || "";
|
|
3423
|
+
if (issuer === "" || clientId === "") throw new CliError("SSO 登录需要 OIDC issuer 和 client id", OIDC_PARAM_HINT);
|
|
3424
|
+
return {
|
|
3425
|
+
issuer,
|
|
3426
|
+
clientId
|
|
3427
|
+
};
|
|
3428
|
+
}
|
|
3429
|
+
async function fetchHealthz(server) {
|
|
3430
|
+
const url = `${server}/healthz`;
|
|
3431
|
+
let res;
|
|
3432
|
+
try {
|
|
3433
|
+
res = await fetch(url);
|
|
3434
|
+
} catch (err) {
|
|
3435
|
+
throw new CliError(`请求 ${url} 失败:${err instanceof Error ? err.message : String(err)}`, "确认 --server 地址可访问");
|
|
3436
|
+
}
|
|
3437
|
+
if (!res.ok) throw new CliError(`${url} 返回 HTTP ${res.status}`, "--server 填简牍站点根地址(能打开文档库、带 /healthz 的那个),不要填 IdP / 登录页");
|
|
3438
|
+
let body;
|
|
3439
|
+
try {
|
|
3440
|
+
body = await res.json();
|
|
3441
|
+
} catch {
|
|
3442
|
+
throw new CliError(`${url} 不是 jiandu healthz`, "--server 填简牍站点根地址,不要填 IdP");
|
|
3443
|
+
}
|
|
3444
|
+
return body !== null && typeof body === "object" ? body : {};
|
|
3445
|
+
}
|
|
3446
|
+
async function probeApiWithBearer(server, token) {
|
|
3447
|
+
return (await fetch(`${server}/api/docs`, {
|
|
3448
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
3449
|
+
redirect: "manual"
|
|
3450
|
+
})).ok;
|
|
3451
|
+
}
|
|
3452
|
+
async function runLogin(opts) {
|
|
3453
|
+
const server = opts.server.trim().replace(/\/+$/, "");
|
|
3454
|
+
if (server === "") throw new CliError("--server 不能为空");
|
|
3455
|
+
const healthz = await (opts.fetchHealthz ?? fetchHealthz)(server);
|
|
3456
|
+
const provider = healthz.authProvider ?? "token";
|
|
3457
|
+
if (opts.token !== void 0 && opts.token !== "") return {
|
|
3458
|
+
configPath: saveConfig({
|
|
3459
|
+
server,
|
|
3460
|
+
token: opts.token
|
|
3461
|
+
}),
|
|
3462
|
+
source: "token"
|
|
3463
|
+
};
|
|
3464
|
+
if (provider === "anonymous") return {
|
|
3465
|
+
configPath: saveConfig({ server }),
|
|
3466
|
+
source: "anonymous"
|
|
3467
|
+
};
|
|
3468
|
+
if (provider === "token") throw new CliError("这个 server 用 token 鉴权,需要 --token", "jdu login --server <url> --token <token>,token 在 server 首次启动的 stdout / data/initial-token.txt");
|
|
3469
|
+
const oidc = resolveOidc({
|
|
3470
|
+
issuer: opts.issuer,
|
|
3471
|
+
clientId: opts.clientId,
|
|
3472
|
+
healthz,
|
|
3473
|
+
env: opts.env
|
|
3474
|
+
});
|
|
3475
|
+
const cached = await (opts.cachedAccessToken ?? ((input) => freshOidcAccessToken(input)))(oidc);
|
|
3476
|
+
let access;
|
|
3477
|
+
let source;
|
|
3478
|
+
let gotRefresh = true;
|
|
3479
|
+
if (cached !== void 0) {
|
|
3480
|
+
access = cached;
|
|
3481
|
+
source = "oidc-cache";
|
|
3482
|
+
} else {
|
|
3483
|
+
const tok = await (opts.oidcLogin ?? authorizationCodeLogin)(oidc);
|
|
3484
|
+
(opts.saveOidc ?? saveOidcToken)(tok);
|
|
3485
|
+
access = tok.access_token;
|
|
3486
|
+
source = "oidc-browser";
|
|
3487
|
+
gotRefresh = Boolean(tok.refresh_token);
|
|
3488
|
+
}
|
|
3489
|
+
const path = saveConfig({
|
|
3490
|
+
server,
|
|
3491
|
+
oidc
|
|
3492
|
+
});
|
|
3493
|
+
const ok = await (opts.probe ?? probeApiWithBearer)(server, access);
|
|
3494
|
+
const warnings = [];
|
|
3495
|
+
if (!ok) warnings.push("token 已拿到,但 /api 仍被网关挡下。forward-auth 下网关需要对 CLI 的 Authorization: Bearer 放行。");
|
|
3496
|
+
if (source === "oidc-browser" && !gotRefresh) warnings.push("这次没有 refresh token。IdP 需要授权 offline_access,否则过几分钟会过期。");
|
|
3497
|
+
return {
|
|
3498
|
+
configPath: path,
|
|
3499
|
+
source,
|
|
3500
|
+
warning: warnings.length > 0 ? warnings.join("\n") : void 0
|
|
3501
|
+
};
|
|
3502
|
+
}
|
|
3503
|
+
//#endregion
|
|
3504
|
+
//#region src/output.ts
|
|
3505
|
+
/** server 可能返回裸数组,也可能包一层 `{ docs: [...] }`,两种都认。 */
|
|
3506
|
+
function asRows(payload, key) {
|
|
3507
|
+
const raw = Array.isArray(payload) ? payload : payload !== null && typeof payload === "object" ? payload[key] : void 0;
|
|
3508
|
+
if (!Array.isArray(raw)) return [];
|
|
3509
|
+
return raw.filter((r) => r !== null && typeof r === "object");
|
|
3510
|
+
}
|
|
3511
|
+
function cell(value) {
|
|
3512
|
+
if (value === null || value === void 0) return "-";
|
|
3513
|
+
if (typeof value === "boolean") return value ? "yes" : "no";
|
|
3514
|
+
if (typeof value === "number" && value > 0xe8d4a51000) return new Date(value).toISOString().slice(0, 16).replace("T", " ");
|
|
3515
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
3516
|
+
return String(value);
|
|
3517
|
+
}
|
|
3518
|
+
/** 定宽文本表,便于人和 agent 直接读;无数据时给一行提示而不是空输出。 */
|
|
3519
|
+
function printTable(rows, columns) {
|
|
3520
|
+
if (rows.length === 0) {
|
|
3521
|
+
process.stdout.write("(空)\n");
|
|
3522
|
+
return;
|
|
3523
|
+
}
|
|
3524
|
+
const body = rows.map((row) => columns.map((c) => cell(row[c.key])));
|
|
3525
|
+
const widths = columns.map((c, i) => Math.max(c.header.length, ...body.map((r) => (r[i] ?? "").length)));
|
|
3526
|
+
const line = (cells) => cells.map((v, i) => v.padEnd(widths[i] ?? 0)).join(" ").trimEnd();
|
|
3527
|
+
process.stdout.write(`${line(columns.map((c) => c.header))}\n`);
|
|
3528
|
+
for (const r of body) process.stdout.write(`${line(r)}\n`);
|
|
3529
|
+
}
|
|
3530
|
+
/** 只取链接/图片的目标部分,标签内容可以任意嵌套,不参与匹配。 */
|
|
3531
|
+
var MD_DEST_RE = /\]\(([^)]*)\)/g;
|
|
3532
|
+
var HTML_ATTR_RE = /\b(?:src|href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'`=<>]+))/gi;
|
|
3533
|
+
/** 抽出一份文本里所有可能的引用目标(未过滤外链,原样返回)。 */
|
|
3534
|
+
function extractRefs(text) {
|
|
3535
|
+
const out = [];
|
|
3536
|
+
for (const m of text.matchAll(MD_DEST_RE)) {
|
|
3537
|
+
const dest = destinationOf(m[1] ?? "");
|
|
3538
|
+
if (dest !== "") out.push(dest);
|
|
3539
|
+
}
|
|
3540
|
+
for (const m of text.matchAll(HTML_ATTR_RE)) {
|
|
3541
|
+
const value = m[1] ?? m[2] ?? m[3];
|
|
3542
|
+
if (value !== void 0 && value !== "") out.push(value);
|
|
3543
|
+
}
|
|
3544
|
+
return out;
|
|
3545
|
+
}
|
|
3546
|
+
/** `(<a b.png>)` / `(a.png "title")` 两种合法写法都要能剥出路径。 */
|
|
3547
|
+
function destinationOf(inner) {
|
|
3548
|
+
const s = inner.trim();
|
|
3549
|
+
if (s.startsWith("<")) {
|
|
3550
|
+
const end = s.indexOf(">");
|
|
3551
|
+
return end === -1 ? "" : s.slice(1, end).trim();
|
|
3552
|
+
}
|
|
3553
|
+
const m = /^\S+/.exec(s);
|
|
3554
|
+
return m ? m[0] : "";
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
3557
|
+
* 归一化为可用于文件系统查找的相对路径;不是本地相对引用则返回 null。
|
|
3558
|
+
* 跳过:锚点、协议相对(`//host`)、带 scheme 的(http(s)/data/mailto/file…)、站点绝对路径。
|
|
3559
|
+
*/
|
|
3560
|
+
function normalizeRef(spec) {
|
|
3561
|
+
const s = spec.trim();
|
|
3562
|
+
if (s === "" || s.startsWith("#")) return null;
|
|
3563
|
+
if (s.startsWith("//")) return null;
|
|
3564
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s)) return null;
|
|
3565
|
+
if (s.startsWith("/")) return null;
|
|
3566
|
+
const path = (s.split("#")[0] ?? "").split("?")[0] ?? "";
|
|
3567
|
+
if (path === "") return null;
|
|
3568
|
+
try {
|
|
3569
|
+
return decodeURIComponent(path);
|
|
3570
|
+
} catch {
|
|
3571
|
+
return path;
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
function isFile(path) {
|
|
3575
|
+
const st = statSync(path, { throwIfNoEntry: false });
|
|
3576
|
+
return st !== void 0 && st.isFile();
|
|
3577
|
+
}
|
|
3578
|
+
/**
|
|
3579
|
+
* 从 entry.md 出发递归收集本地引用。
|
|
3580
|
+
*
|
|
3581
|
+
* 终止条件有两个,缺一不可:`scanned` 集合让循环引用(a→b→a)只展开一次,
|
|
3582
|
+
* MAX_DEPTH 让符号链接目录之类能无限造出新路径的结构也停得下来。
|
|
3583
|
+
*/
|
|
3584
|
+
function collectReferences(entryPath, maxDepth = 10) {
|
|
3585
|
+
const entryAbs = resolve(entryPath);
|
|
3586
|
+
if (!isFile(entryAbs)) throw new CliError(`入口文件不存在或不是普通文件:${entryAbs}`);
|
|
3587
|
+
const entryDir = dirname(entryAbs);
|
|
3588
|
+
const warnings = [];
|
|
3589
|
+
const aliases = {};
|
|
3590
|
+
const files = /* @__PURE__ */ new Map();
|
|
3591
|
+
const scanned = /* @__PURE__ */ new Set();
|
|
3592
|
+
const keyOf = (abs) => {
|
|
3593
|
+
const rel = relative(entryDir, abs).split(sep).join("/");
|
|
3594
|
+
return rel.startsWith("..") ? rel : `./${rel}`;
|
|
3595
|
+
};
|
|
3596
|
+
const walk = (fileAbs, depth) => {
|
|
3597
|
+
if (scanned.has(fileAbs)) return;
|
|
3598
|
+
scanned.add(fileAbs);
|
|
3599
|
+
let text;
|
|
3600
|
+
try {
|
|
3601
|
+
text = readFileSync(fileAbs, "utf8");
|
|
3602
|
+
} catch (err) {
|
|
3603
|
+
warnings.push(`无法读取 ${keyOf(fileAbs)}:${err.message}`);
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
const dir = dirname(fileAbs);
|
|
3607
|
+
const isEntry = fileAbs === entryAbs;
|
|
3608
|
+
for (const raw of extractRefs(text)) {
|
|
3609
|
+
const spec = normalizeRef(raw);
|
|
3610
|
+
if (spec === null) continue;
|
|
3611
|
+
const abs = resolve(dir, spec);
|
|
3612
|
+
if (!isFile(abs)) {
|
|
3613
|
+
warnings.push(`跳过不存在的本地引用 ${raw}(来自 ${keyOf(fileAbs)})`);
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
if (abs === entryAbs) continue;
|
|
3617
|
+
const childDepth = depth + 1;
|
|
3618
|
+
const key = keyOf(abs);
|
|
3619
|
+
const existing = files.get(abs);
|
|
3620
|
+
if (existing === void 0) files.set(abs, {
|
|
3621
|
+
key,
|
|
3622
|
+
path: abs,
|
|
3623
|
+
depth: childDepth
|
|
3624
|
+
});
|
|
3625
|
+
else if (childDepth < existing.depth) existing.depth = childDepth;
|
|
3626
|
+
if (isEntry && raw.trim() !== key) aliases[raw.trim()] = key;
|
|
3627
|
+
if (abs.toLowerCase().endsWith(".md")) {
|
|
3628
|
+
if (childDepth < maxDepth) walk(abs, childDepth);
|
|
3629
|
+
else if (!scanned.has(abs)) warnings.push(`达到限深 ${maxDepth},不再展开 ${key} 内的引用`);
|
|
3630
|
+
}
|
|
3631
|
+
}
|
|
3632
|
+
};
|
|
3633
|
+
walk(entryAbs, 0);
|
|
3634
|
+
return {
|
|
3635
|
+
entry: {
|
|
3636
|
+
key: keyOf(entryAbs),
|
|
3637
|
+
path: entryAbs,
|
|
3638
|
+
depth: 0
|
|
3639
|
+
},
|
|
3640
|
+
files: [...files.values()].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0),
|
|
3641
|
+
aliases,
|
|
3642
|
+
warnings
|
|
3643
|
+
};
|
|
3644
|
+
}
|
|
3645
|
+
//#endregion
|
|
3646
|
+
//#region src/push.ts
|
|
3647
|
+
var VISIBILITIES = [
|
|
3648
|
+
"private",
|
|
3649
|
+
"link",
|
|
3650
|
+
"public"
|
|
3651
|
+
];
|
|
3652
|
+
function log(line) {
|
|
3653
|
+
process.stderr.write(`${line}\n`);
|
|
3654
|
+
}
|
|
3655
|
+
/** 没给 --title 时用首个一级标题,再退化到文件名。 */
|
|
3656
|
+
function inferTitle(entryPath) {
|
|
3657
|
+
try {
|
|
3658
|
+
const text = readFileSync(entryPath, "utf8");
|
|
3659
|
+
const m = /^[ \t]{0,3}#[ \t]+(.+?)[ \t]*#*[ \t]*$/m.exec(text);
|
|
3660
|
+
if (m?.[1]) return m[1].trim();
|
|
3661
|
+
} catch {}
|
|
3662
|
+
return basename(entryPath, extname(entryPath));
|
|
3663
|
+
}
|
|
3664
|
+
async function pushDoc(api, entryArg, opts) {
|
|
3665
|
+
const visibility = opts.visibility;
|
|
3666
|
+
if (visibility !== void 0 && !VISIBILITIES.includes(visibility)) throw new CliError(`不支持的 visibility:${String(opts.visibility)}`, `可选值:${VISIBILITIES.join(" | ")}`);
|
|
3667
|
+
const collected = collectReferences(entryArg);
|
|
3668
|
+
for (const w of collected.warnings) log(`warn: ${w}`);
|
|
3669
|
+
const entryHash = await sha256File(collected.entry.path);
|
|
3670
|
+
const blobs = [{
|
|
3671
|
+
path: collected.entry.path,
|
|
3672
|
+
hash: entryHash
|
|
3673
|
+
}];
|
|
3674
|
+
const assets = {};
|
|
3675
|
+
for (const file of collected.files) {
|
|
3676
|
+
const hash = await sha256File(file.path);
|
|
3677
|
+
assets[file.key] = hash;
|
|
3678
|
+
blobs.push({
|
|
3679
|
+
path: file.path,
|
|
3680
|
+
hash
|
|
3681
|
+
});
|
|
3682
|
+
}
|
|
3683
|
+
for (const [raw, key] of Object.entries(collected.aliases)) {
|
|
3684
|
+
const hash = assets[key];
|
|
3685
|
+
if (hash !== void 0) assets[raw] = hash;
|
|
3686
|
+
}
|
|
3687
|
+
log(`收集 ${collected.files.length} 个本地引用(入口 ${collected.entry.key})`);
|
|
3688
|
+
const sync = await syncBlobs(api, blobs);
|
|
3689
|
+
log(`blob 协商:共 ${sync.total} 个,新上传 ${sync.uploaded.length} 个,复用 ${sync.reused} 个`);
|
|
3690
|
+
const body = {
|
|
3691
|
+
entry: entryHash,
|
|
3692
|
+
assets
|
|
3693
|
+
};
|
|
3694
|
+
if (visibility !== void 0) body.visibility = visibility;
|
|
3695
|
+
if (opts.title !== void 0 && opts.title !== "") body.title = opts.title;
|
|
3696
|
+
else if (opts.id === void 0 || opts.id === "") body.title = inferTitle(collected.entry.path);
|
|
3697
|
+
if (opts.id !== void 0 && opts.id !== "") body.id = opts.id;
|
|
3698
|
+
if (opts.tag !== void 0) body.tags = opts.tag.flatMap((t) => t.split(",")).map((t) => t.trim()).filter((t) => t.length > 0);
|
|
3699
|
+
const res = await api.postJson("/api/docs", body);
|
|
3700
|
+
const id = typeof res?.id === "string" ? res.id : opts.id;
|
|
3701
|
+
const url = typeof res?.url === "string" && res.url !== "" ? res.url : id !== void 0 ? api.url(`/d/${id}`) : void 0;
|
|
3702
|
+
if (typeof res?.seq === "number") log(`已发布 ${id ?? ""} v${res.seq}`);
|
|
3703
|
+
if (url === void 0) throw new CliError("server 未返回文档 id 或 url,无法给出访问地址");
|
|
3704
|
+
process.stdout.write(`${url}\n`);
|
|
3705
|
+
}
|
|
3706
|
+
//#endregion
|
|
3707
|
+
//#region src/widget.ts
|
|
3708
|
+
var SCOPES = [
|
|
3709
|
+
"official",
|
|
3710
|
+
"team",
|
|
3711
|
+
"personal"
|
|
3712
|
+
];
|
|
3713
|
+
function exists(path) {
|
|
3714
|
+
const st = statSync(path, { throwIfNoEntry: false });
|
|
3715
|
+
return st !== void 0 && st.isFile();
|
|
3716
|
+
}
|
|
3717
|
+
async function readWidgetJson(dir) {
|
|
3718
|
+
const path = join(dir, "widget.json");
|
|
3719
|
+
if (!exists(path)) throw new CliError(`目录下缺少 widget.json:${dir}`, "指向 packages/widgets/dist/<Name> 之类的构建产物目录");
|
|
3720
|
+
let parsed;
|
|
3721
|
+
try {
|
|
3722
|
+
parsed = JSON.parse(await readFile(path, "utf8"));
|
|
3723
|
+
} catch (err) {
|
|
3724
|
+
throw new CliError(`widget.json 不是合法 JSON:${path}(${err.message})`);
|
|
3725
|
+
}
|
|
3726
|
+
if (parsed === null || typeof parsed !== "object") throw new CliError(`widget.json 顶层必须是对象:${path}`);
|
|
3727
|
+
const obj = parsed;
|
|
3728
|
+
const name = obj.name;
|
|
3729
|
+
const scope = obj.scope;
|
|
3730
|
+
const version = obj.version;
|
|
3731
|
+
if (typeof name !== "string" || name === "") throw new CliError(`widget.json 缺少 name:${path}`);
|
|
3732
|
+
if (typeof scope !== "string" || !SCOPES.includes(scope)) throw new CliError(`widget.json 的 scope 非法:${String(scope)}`, `可选值:${SCOPES.join(" | ")}`);
|
|
3733
|
+
if (typeof version !== "string" || version === "") throw new CliError(`widget.json 缺少 version:${path}`);
|
|
3734
|
+
return {
|
|
3735
|
+
name,
|
|
3736
|
+
scope,
|
|
3737
|
+
version,
|
|
3738
|
+
dataSchema: obj.dataSchema ?? null,
|
|
3739
|
+
sampleData: obj.sampleData ?? null
|
|
3740
|
+
};
|
|
3741
|
+
}
|
|
3742
|
+
/** 递归收集 <pushdir>/src 下的源码文件,key 是相对 src 的 POSIX 路径。 */
|
|
3743
|
+
async function collectSource(dir) {
|
|
3744
|
+
const root = join(dir, "src");
|
|
3745
|
+
const out = /* @__PURE__ */ new Map();
|
|
3746
|
+
const st = statSync(root, { throwIfNoEntry: false });
|
|
3747
|
+
if (st === void 0 || !st.isDirectory()) return out;
|
|
3748
|
+
const walk = async (current) => {
|
|
3749
|
+
for (const entry of await readdir(current, { withFileTypes: true })) {
|
|
3750
|
+
const abs = join(current, entry.name);
|
|
3751
|
+
if (entry.isDirectory()) await walk(abs);
|
|
3752
|
+
else if (entry.isFile()) out.set(relative(root, abs).split(sep).join("/"), await readFile(abs));
|
|
3753
|
+
}
|
|
3754
|
+
};
|
|
3755
|
+
await walk(root);
|
|
3756
|
+
return out;
|
|
3757
|
+
}
|
|
3758
|
+
/** 与 server 的算法一致:sha256 over 排序后的 `路径:内容hash` 行。 */
|
|
3759
|
+
function sourceFingerprint(files) {
|
|
3760
|
+
if (files.size === 0) return null;
|
|
3761
|
+
const lines = [...files.keys()].sort().map((rel) => `${rel}:${createHash("sha256").update(files.get(rel)).digest("hex")}`);
|
|
3762
|
+
return createHash("sha256").update(lines.join("\n")).digest("hex");
|
|
3763
|
+
}
|
|
3764
|
+
/** 已注册且内容一样就不必再传一遍(Mermaid 的 ESM 有 3.4MB,低带宽下值得这一次查询)。 */
|
|
3765
|
+
async function unchanged(api, meta, esmHash, cssHash, srcHash) {
|
|
3766
|
+
const hit = (await api.getJson("/api/widgets").catch(() => null))?.widgets?.find((w) => w.scope === meta.scope && w.name === meta.name && w.version === meta.version);
|
|
3767
|
+
if (!hit) return false;
|
|
3768
|
+
return hit.esmHash === esmHash && (hit.cssHash ?? null) === cssHash && (hit.srcHash ?? null) === srcHash;
|
|
3769
|
+
}
|
|
3770
|
+
var STATUS_VERBS = {
|
|
3771
|
+
enable: {
|
|
3772
|
+
status: "active",
|
|
3773
|
+
label: "已上线"
|
|
3774
|
+
},
|
|
3775
|
+
disable: {
|
|
3776
|
+
status: "disabled",
|
|
3777
|
+
label: "已下线"
|
|
3778
|
+
},
|
|
3779
|
+
approve: {
|
|
3780
|
+
status: "active",
|
|
3781
|
+
label: "审批通过,已上线"
|
|
3782
|
+
},
|
|
3783
|
+
reject: {
|
|
3784
|
+
status: "rejected",
|
|
3785
|
+
label: "审批驳回"
|
|
3786
|
+
}
|
|
3787
|
+
};
|
|
3788
|
+
/** 解析 `jdu widget list` 打出来的那种引用:`official/Alert@1.0.0`。 */
|
|
3789
|
+
function parseRef(ref) {
|
|
3790
|
+
const m = /^([a-z]+)\/([A-Za-z0-9][\w.-]*)@([A-Za-z0-9][\w.-]*)$/.exec(ref);
|
|
3791
|
+
if (!m?.[1] || !m[2] || !m[3]) throw new CliError(`widget 引用格式不对:${ref}`, "要 <scope>/<name>@<version>,例如 official/Alert@1.0.0(照 jdu widget list 的输出抄)");
|
|
3792
|
+
if (!SCOPES.includes(m[1])) throw new CliError(`未知 scope:${m[1]}`, `可选值:${SCOPES.join(" | ")}`);
|
|
3793
|
+
return {
|
|
3794
|
+
scope: m[1],
|
|
3795
|
+
name: m[2],
|
|
3796
|
+
version: m[3]
|
|
3797
|
+
};
|
|
3798
|
+
}
|
|
3799
|
+
/** 上线 / 下线 / 审批:只翻状态,产物与源码都不动。 */
|
|
3800
|
+
async function setWidgetStatus(api, verb, ref) {
|
|
3801
|
+
const { scope, name, version } = parseRef(ref);
|
|
3802
|
+
const { status, label } = STATUS_VERBS[verb];
|
|
3803
|
+
const res = await api.postJson(`/api/widgets/${scope}/${name}/${version}/status`, { status });
|
|
3804
|
+
const from = typeof res?.previousStatus === "string" ? `${res.previousStatus} → ` : "";
|
|
3805
|
+
process.stdout.write(`${scope}/${name}@${version} ${label}(${from}${status})\n`);
|
|
3806
|
+
}
|
|
3807
|
+
async function pushWidget(api, dirArg) {
|
|
3808
|
+
const dir = resolve(dirArg);
|
|
3809
|
+
const meta = await readWidgetJson(dir);
|
|
3810
|
+
const esmPath = join(dir, "index.js");
|
|
3811
|
+
if (!exists(esmPath)) throw new CliError(`目录下缺少构建产物 index.js:${dir}`, "先执行 widgets 包的 build");
|
|
3812
|
+
const cssPath = join(dir, "index.css");
|
|
3813
|
+
const hasCss = exists(cssPath);
|
|
3814
|
+
const esmHash = await sha256File(esmPath);
|
|
3815
|
+
const cssHash = hasCss ? await sha256File(cssPath) : null;
|
|
3816
|
+
const sources = await collectSource(dir);
|
|
3817
|
+
if (await unchanged(api, meta, esmHash, cssHash, sourceFingerprint(sources))) {
|
|
3818
|
+
process.stdout.write(`${meta.scope}/${meta.name}@${meta.version} 未变化,跳过\n`);
|
|
3819
|
+
return;
|
|
3820
|
+
}
|
|
3821
|
+
const form = new FormData();
|
|
3822
|
+
form.append("widget.json", new File([JSON.stringify(meta)], "widget.json", { type: "application/json" }));
|
|
3823
|
+
form.append("index.js", new File([await readFile(esmPath)], "index.js", { type: "text/javascript" }));
|
|
3824
|
+
if (hasCss) form.append("index.css", new File([await readFile(cssPath)], "index.css", { type: "text/css" }));
|
|
3825
|
+
for (const [rel, buf] of sources) form.append(`src/${rel}`, new File([new Uint8Array(buf)], rel, { type: "text/plain" }));
|
|
3826
|
+
const res = await api.postForm("/api/widgets", form);
|
|
3827
|
+
const where = typeof res?.dir === "string" ? ` → ${res.dir}` : "";
|
|
3828
|
+
const src = sources.size > 0 ? ` + ${sources.size} 个源码文件` : "";
|
|
3829
|
+
process.stdout.write(`${meta.scope}/${meta.name}@${meta.version}${src}${where}\n`);
|
|
3830
|
+
}
|
|
3831
|
+
//#endregion
|
|
3832
|
+
//#region src/cli.ts
|
|
3833
|
+
async function client() {
|
|
3834
|
+
return new ApiClient(await loadRuntimeConfig());
|
|
3835
|
+
}
|
|
3836
|
+
/** commander 的可重复选项收集器:`--tag a --tag b` → `['a','b']`。 */
|
|
3837
|
+
function collectTag(value, previous) {
|
|
3838
|
+
return [...previous ?? [], value];
|
|
3839
|
+
}
|
|
3840
|
+
var program = new Command();
|
|
3841
|
+
program.name("jdu").description("jiandu 命令行").version("0.1.0").showHelpAfterError();
|
|
3842
|
+
program.command("login").description("登录到 jiandu server(forward-auth 会打开浏览器走 SSO)").requiredOption("--server <url>", "jiandu server 地址").option("--token <token>", "直接保存访问 token(token provider / 跳过浏览器)").option("--issuer <url>", "OIDC issuer(缺省读 healthz.oidc 或 JIANDU_OIDC_ISSUER)").option("--client-id <id>", "OIDC client id(缺省读 healthz.oidc 或 JIANDU_OIDC_CLIENT_ID)").action(async (opts) => {
|
|
3843
|
+
const result = await runLogin({
|
|
3844
|
+
server: opts.server,
|
|
3845
|
+
token: opts.token,
|
|
3846
|
+
issuer: opts.issuer,
|
|
3847
|
+
clientId: opts.clientId
|
|
3848
|
+
});
|
|
3849
|
+
process.stdout.write(`${result.configPath}\n`);
|
|
3850
|
+
if (result.source === "anonymous") process.stderr.write("这个 server 是匿名模式,无需登录。\n");
|
|
3851
|
+
if (result.source === "oidc-cache") process.stderr.write("已复用本机 SSO credential。\n");
|
|
3852
|
+
if (result.source === "oidc-browser") process.stderr.write("SSO 登录成功。\n");
|
|
3853
|
+
if (result.warning) process.stderr.write(`jdu: ${result.warning}\n`);
|
|
3854
|
+
});
|
|
3855
|
+
program.command("push").argument("<entry.md>", "入口 markdown 文件").description("递归收集本地引用、增量上传并发布一个新版本").option("--title <title>", "文档标题,默认取首个一级标题").option("--visibility <v>", `${VISIBILITIES.join(" | ")}(新文档默认 private;更新已有文档时不传则保持原值)`).option("--id <docId>", "复用已有文档 id(发布新版本)").option("--tag <name>", "打标签,可重复;不传则保持原有标签", collectTag, void 0).action(async (entry, opts) => {
|
|
3856
|
+
await pushDoc(await client(), entry, opts);
|
|
3857
|
+
});
|
|
3858
|
+
program.command("list").description("列出文档").option("--all", "包含已归档", false).action(async (opts) => {
|
|
3859
|
+
printTable(asRows(await (await client()).getJson(`/api/docs${opts.all ? "?all=1" : ""}`), "docs"), [
|
|
3860
|
+
{
|
|
3861
|
+
key: "id",
|
|
3862
|
+
header: "ID"
|
|
3863
|
+
},
|
|
3864
|
+
{
|
|
3865
|
+
key: "visibility",
|
|
3866
|
+
header: "VISIBILITY"
|
|
3867
|
+
},
|
|
3868
|
+
{
|
|
3869
|
+
key: "archived",
|
|
3870
|
+
header: "ARCHIVED"
|
|
3871
|
+
},
|
|
3872
|
+
{
|
|
3873
|
+
key: "title",
|
|
3874
|
+
header: "TITLE"
|
|
3875
|
+
}
|
|
3876
|
+
]);
|
|
3877
|
+
});
|
|
3878
|
+
program.command("versions").argument("<docId>").description("列出某文档的全部版本").action(async (docId) => {
|
|
3879
|
+
printTable(asRows(await (await client()).getJson(`/api/docs/${encodeURIComponent(docId)}/versions`), "versions"), [
|
|
3880
|
+
{
|
|
3881
|
+
key: "seq",
|
|
3882
|
+
header: "SEQ"
|
|
3883
|
+
},
|
|
3884
|
+
{
|
|
3885
|
+
key: "created_at",
|
|
3886
|
+
header: "CREATED"
|
|
3887
|
+
},
|
|
3888
|
+
{
|
|
3889
|
+
key: "source_hash",
|
|
3890
|
+
header: "SOURCE"
|
|
3891
|
+
},
|
|
3892
|
+
{
|
|
3893
|
+
key: "html_hash",
|
|
3894
|
+
header: "HTML"
|
|
3895
|
+
}
|
|
3896
|
+
]);
|
|
3897
|
+
});
|
|
3898
|
+
program.command("rollback").argument("<docId>").argument("<seq>").description("回滚到指定版本").action(async (docId, seq) => {
|
|
3899
|
+
const n = Number.parseInt(seq, 10);
|
|
3900
|
+
if (!Number.isInteger(n)) throw new CliError(`seq 必须是整数:${seq}`);
|
|
3901
|
+
await (await client()).postJson(`/api/docs/${encodeURIComponent(docId)}/rollback`, { seq: n });
|
|
3902
|
+
process.stdout.write(`rolled back ${docId} -> v${n}\n`);
|
|
3903
|
+
});
|
|
3904
|
+
program.command("archive").argument("<docId>").description("归档文档").option("--undo", "取消归档", false).action(async (docId, opts) => {
|
|
3905
|
+
await (await client()).postJson(`/api/docs/${encodeURIComponent(docId)}/archive`, { archived: !opts.undo });
|
|
3906
|
+
process.stdout.write(`${opts.undo ? "unarchived" : "archived"} ${docId}\n`);
|
|
3907
|
+
});
|
|
3908
|
+
program.command("delete").argument("<docId>").description("删除文档(默认软删,--hard 物理删)").option("--hard", "物理删除,不可恢复", false).action(async (docId, opts) => {
|
|
3909
|
+
await (await client()).deleteJson(`/api/docs/${encodeURIComponent(docId)}${opts.hard ? "?hard=1" : ""}`);
|
|
3910
|
+
process.stdout.write(`deleted${opts.hard ? " (hard)" : ""} ${docId}\n`);
|
|
3911
|
+
});
|
|
3912
|
+
program.command("reset").argument("<docId>").description("清空该文档的全部版本与产物(物理)").action(async (docId) => {
|
|
3913
|
+
await (await client()).postJson(`/api/docs/${encodeURIComponent(docId)}/reset`, {});
|
|
3914
|
+
process.stdout.write(`reset ${docId}\n`);
|
|
3915
|
+
});
|
|
3916
|
+
program.command("rerender").argument("<docId>", "要刷缓存的文档").description("强制刷渲染缓存(删掉后就地重渲预热)。内核升级不需要它——缓存 key 自然失效").action(async (docId) => {
|
|
3917
|
+
await (await client()).postJson(`/api/docs/${encodeURIComponent(docId)}/rerender`, {});
|
|
3918
|
+
process.stdout.write(`rerendered ${docId}\n`);
|
|
3919
|
+
});
|
|
3920
|
+
var tag = program.command("tag").description("标签");
|
|
3921
|
+
tag.command("list").description("列出全部标签(带文档数与最近使用)").action(async () => {
|
|
3922
|
+
printTable(asRows(await (await client()).getJson("/api/tags"), "tags"), [{
|
|
3923
|
+
key: "name",
|
|
3924
|
+
header: "TAG"
|
|
3925
|
+
}, {
|
|
3926
|
+
key: "docs",
|
|
3927
|
+
header: "DOCS"
|
|
3928
|
+
}]);
|
|
3929
|
+
});
|
|
3930
|
+
tag.command("add").argument("<docId>").argument("<tags...>", "要加的标签名").description("给文档加标签(保留已有的)").action(async (docId, names) => {
|
|
3931
|
+
const api = await client();
|
|
3932
|
+
const cur = await api.getJson(`/api/docs/${encodeURIComponent(docId)}/tags`).catch(() => ({}));
|
|
3933
|
+
const existing = Array.isArray(cur.tags) ? cur.tags.map(String) : [];
|
|
3934
|
+
const next = [.../* @__PURE__ */ new Set([...existing, ...names.flatMap((n) => n.split(","))])];
|
|
3935
|
+
await api.putJson(`/api/docs/${encodeURIComponent(docId)}/tags`, { tags: next });
|
|
3936
|
+
process.stdout.write(`${next.join(", ")}\n`);
|
|
3937
|
+
});
|
|
3938
|
+
tag.command("set").argument("<docId>").argument("[tags...]", "整体覆盖成这些标签;不给就是清空").description("整体覆盖文档的标签(幂等)").action(async (docId, names) => {
|
|
3939
|
+
const next = names.flatMap((n) => n.split(",")).filter((n) => n.length > 0);
|
|
3940
|
+
await (await client()).putJson(`/api/docs/${encodeURIComponent(docId)}/tags`, { tags: next });
|
|
3941
|
+
process.stdout.write(`${next.join(", ") || "(已清空)"}\n`);
|
|
3942
|
+
});
|
|
3943
|
+
tag.command("rename").argument("<from>").argument("<to>").description("重命名:全站引用同步更新").action(async (from, to) => {
|
|
3944
|
+
const res = await (await client()).postJson("/api/tags/rename", {
|
|
3945
|
+
from,
|
|
3946
|
+
to
|
|
3947
|
+
});
|
|
3948
|
+
process.stdout.write(`${from} → ${to}(${String(res.renamed ?? 0)} 篇)\n`);
|
|
3949
|
+
});
|
|
3950
|
+
tag.command("merge").argument("<from>").argument("<into>").description("合并:把 from 的文档并到 into,from 消失").action(async (from, into) => {
|
|
3951
|
+
const res = await (await client()).postJson("/api/tags/merge", {
|
|
3952
|
+
from,
|
|
3953
|
+
into
|
|
3954
|
+
});
|
|
3955
|
+
process.stdout.write(`${from} ⊂ ${into}(${String(res.merged ?? 0)} 篇)\n`);
|
|
3956
|
+
});
|
|
3957
|
+
tag.command("rm").argument("<name>").description("删除标签:只解绑,文档不受影响").action(async (name) => {
|
|
3958
|
+
const res = await (await client()).postJson("/api/tags/delete", { name });
|
|
3959
|
+
process.stdout.write(`已删除 ${name}(解绑 ${String(res.unlinked ?? 0)} 篇)\n`);
|
|
3960
|
+
});
|
|
3961
|
+
program.command("share").argument("<docId>").description("改可见性 / 团队归属 / 按人授权").option("--visibility <v>", VISIBILITIES.join(" | ")).option("--team <teamId>", "设为团队可见;传空串取消").option("--to <user>", "授权给某人,可重复(整体覆盖)", collectTag, void 0).action(async (docId, opts) => {
|
|
3962
|
+
const api = await client();
|
|
3963
|
+
const id = encodeURIComponent(docId);
|
|
3964
|
+
if (opts.visibility !== void 0 || opts.team !== void 0) {
|
|
3965
|
+
const body = {};
|
|
3966
|
+
if (opts.visibility !== void 0) body.visibility = opts.visibility;
|
|
3967
|
+
if (opts.team !== void 0) body.teamId = opts.team;
|
|
3968
|
+
const res = await api.putJson(`/api/docs/${id}/visibility`, body);
|
|
3969
|
+
process.stdout.write(`可见性 ${String(res.visibility)}${res.teamId ? ` · 团队 ${String(res.teamId)}` : ""}\n`);
|
|
3970
|
+
}
|
|
3971
|
+
if (opts.to !== void 0) {
|
|
3972
|
+
const res = await api.putJson(`/api/docs/${id}/grants`, { grantees: opts.to });
|
|
3973
|
+
const list = Array.isArray(res.grantees) ? res.grantees.map(String) : [];
|
|
3974
|
+
process.stdout.write(`已授权:${list.join(", ") || "(已清空)"}\n`);
|
|
3975
|
+
}
|
|
3976
|
+
});
|
|
3977
|
+
program.command("teams").description("列出我所属的团队").action(async () => {
|
|
3978
|
+
printTable(asRows(await (await client()).getJson("/api/teams"), "teams"), [
|
|
3979
|
+
{
|
|
3980
|
+
key: "id",
|
|
3981
|
+
header: "ID"
|
|
3982
|
+
},
|
|
3983
|
+
{
|
|
3984
|
+
key: "name",
|
|
3985
|
+
header: "NAME"
|
|
3986
|
+
},
|
|
3987
|
+
{
|
|
3988
|
+
key: "members",
|
|
3989
|
+
header: "MEMBERS"
|
|
3990
|
+
}
|
|
3991
|
+
]);
|
|
3992
|
+
});
|
|
3993
|
+
program.command("blob").description("内容寻址 blob(shared 档 runtime 等原始资产)").command("push").argument("<files...>", "要上传的文件(如 packages/widgets/dist/_runtime/*.js)").description("按内容 hash 上传为 blob,输出 /blob/<hash> 地址(已存在则跳过)").action(async (files) => {
|
|
3994
|
+
const api = await client();
|
|
3995
|
+
const entries = await Promise.all(files.map(async (f) => ({
|
|
3996
|
+
path: f,
|
|
3997
|
+
hash: await sha256File(f)
|
|
3998
|
+
})));
|
|
3999
|
+
const res = await syncBlobs(api, entries);
|
|
4000
|
+
for (const e of entries) {
|
|
4001
|
+
const state = res.uploaded.includes(e.hash) ? "已上传" : "已存在";
|
|
4002
|
+
process.stdout.write(`${state} /blob/${e.hash} ${e.path}\n`);
|
|
4003
|
+
}
|
|
4004
|
+
});
|
|
4005
|
+
var widget = program.command("widget").description("widget 注册表");
|
|
4006
|
+
widget.command("push").argument("<dir>", "含 widget.json + index.js[ + index.css] 的构建产物目录").description("发布 widget").action(async (dir) => {
|
|
4007
|
+
await pushWidget(await client(), dir);
|
|
4008
|
+
});
|
|
4009
|
+
widget.command("list").description("列出已注册 widget").action(async () => {
|
|
4010
|
+
printTable(asRows(await (await client()).getJson("/api/widgets"), "widgets"), [
|
|
4011
|
+
{
|
|
4012
|
+
key: "scope",
|
|
4013
|
+
header: "SCOPE"
|
|
4014
|
+
},
|
|
4015
|
+
{
|
|
4016
|
+
key: "name",
|
|
4017
|
+
header: "NAME"
|
|
4018
|
+
},
|
|
4019
|
+
{
|
|
4020
|
+
key: "version",
|
|
4021
|
+
header: "VERSION"
|
|
4022
|
+
},
|
|
4023
|
+
{
|
|
4024
|
+
key: "status",
|
|
4025
|
+
header: "STATUS"
|
|
4026
|
+
},
|
|
4027
|
+
{
|
|
4028
|
+
key: "owner",
|
|
4029
|
+
header: "OWNER"
|
|
4030
|
+
},
|
|
4031
|
+
{
|
|
4032
|
+
key: "updatedAt",
|
|
4033
|
+
header: "UPDATED"
|
|
4034
|
+
}
|
|
4035
|
+
]);
|
|
4036
|
+
});
|
|
4037
|
+
for (const [verb, desc] of [
|
|
4038
|
+
["enable", "上线(status → active)"],
|
|
4039
|
+
["disable", "下线(status → disabled,fence 降级成代码块)"],
|
|
4040
|
+
["approve", "审批通过(status → active,需管理员)"],
|
|
4041
|
+
["reject", "审批驳回(status → rejected,需管理员)"]
|
|
4042
|
+
]) widget.command(verb).argument("<ref>", "<scope>/<name>@<version>,如 official/Alert@1.0.0").description(desc).action(async (ref) => {
|
|
4043
|
+
await setWidgetStatus(await client(), verb, ref);
|
|
4044
|
+
});
|
|
4045
|
+
try {
|
|
4046
|
+
await program.parseAsync(process.argv);
|
|
4047
|
+
} catch (err) {
|
|
4048
|
+
if (err instanceof CliError) {
|
|
4049
|
+
process.stderr.write(`jdu: ${err.message}\n`);
|
|
4050
|
+
if (err.hint !== void 0) process.stderr.write(` 提示:${err.hint}\n`);
|
|
4051
|
+
} else process.stderr.write(`jdu: 未预期错误 ${err instanceof Error ? err.stack : String(err)}\n`);
|
|
4052
|
+
process.exitCode = 1;
|
|
4053
|
+
}
|
|
4054
|
+
//#endregion
|
|
4055
|
+
export {};
|