@neopress/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/dist/bin.cjs +4897 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +681 -0
- package/package.json +29 -0
package/dist/bin.cjs
ADDED
|
@@ -0,0 +1,4897 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
|
|
29
|
+
// node_modules/commander/lib/error.js
|
|
30
|
+
var require_error = __commonJS({
|
|
31
|
+
"node_modules/commander/lib/error.js"(exports2) {
|
|
32
|
+
"use strict";
|
|
33
|
+
var CommanderError2 = class extends Error {
|
|
34
|
+
/**
|
|
35
|
+
* Constructs the CommanderError class
|
|
36
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
37
|
+
* @param {string} code an id string representing the error
|
|
38
|
+
* @param {string} message human-readable description of the error
|
|
39
|
+
*/
|
|
40
|
+
constructor(exitCode, code, message) {
|
|
41
|
+
super(message);
|
|
42
|
+
Error.captureStackTrace(this, this.constructor);
|
|
43
|
+
this.name = this.constructor.name;
|
|
44
|
+
this.code = code;
|
|
45
|
+
this.exitCode = exitCode;
|
|
46
|
+
this.nestedError = void 0;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
50
|
+
/**
|
|
51
|
+
* Constructs the InvalidArgumentError class
|
|
52
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
53
|
+
*/
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(1, "commander.invalidArgument", message);
|
|
56
|
+
Error.captureStackTrace(this, this.constructor);
|
|
57
|
+
this.name = this.constructor.name;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
exports2.CommanderError = CommanderError2;
|
|
61
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// node_modules/commander/lib/argument.js
|
|
66
|
+
var require_argument = __commonJS({
|
|
67
|
+
"node_modules/commander/lib/argument.js"(exports2) {
|
|
68
|
+
"use strict";
|
|
69
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
70
|
+
var Argument2 = class {
|
|
71
|
+
/**
|
|
72
|
+
* Initialize a new command argument with the given name and description.
|
|
73
|
+
* The default is that the argument is required, and you can explicitly
|
|
74
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
75
|
+
*
|
|
76
|
+
* @param {string} name
|
|
77
|
+
* @param {string} [description]
|
|
78
|
+
*/
|
|
79
|
+
constructor(name, description) {
|
|
80
|
+
this.description = description || "";
|
|
81
|
+
this.variadic = false;
|
|
82
|
+
this.parseArg = void 0;
|
|
83
|
+
this.defaultValue = void 0;
|
|
84
|
+
this.defaultValueDescription = void 0;
|
|
85
|
+
this.argChoices = void 0;
|
|
86
|
+
switch (name[0]) {
|
|
87
|
+
case "<":
|
|
88
|
+
this.required = true;
|
|
89
|
+
this._name = name.slice(1, -1);
|
|
90
|
+
break;
|
|
91
|
+
case "[":
|
|
92
|
+
this.required = false;
|
|
93
|
+
this._name = name.slice(1, -1);
|
|
94
|
+
break;
|
|
95
|
+
default:
|
|
96
|
+
this.required = true;
|
|
97
|
+
this._name = name;
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
if (this._name.length > 3 && this._name.slice(-3) === "...") {
|
|
101
|
+
this.variadic = true;
|
|
102
|
+
this._name = this._name.slice(0, -3);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Return argument name.
|
|
107
|
+
*
|
|
108
|
+
* @return {string}
|
|
109
|
+
*/
|
|
110
|
+
name() {
|
|
111
|
+
return this._name;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* @package
|
|
115
|
+
*/
|
|
116
|
+
_concatValue(value, previous) {
|
|
117
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
118
|
+
return [value];
|
|
119
|
+
}
|
|
120
|
+
return previous.concat(value);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
124
|
+
*
|
|
125
|
+
* @param {*} value
|
|
126
|
+
* @param {string} [description]
|
|
127
|
+
* @return {Argument}
|
|
128
|
+
*/
|
|
129
|
+
default(value, description) {
|
|
130
|
+
this.defaultValue = value;
|
|
131
|
+
this.defaultValueDescription = description;
|
|
132
|
+
return this;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
136
|
+
*
|
|
137
|
+
* @param {Function} [fn]
|
|
138
|
+
* @return {Argument}
|
|
139
|
+
*/
|
|
140
|
+
argParser(fn) {
|
|
141
|
+
this.parseArg = fn;
|
|
142
|
+
return this;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Only allow argument value to be one of choices.
|
|
146
|
+
*
|
|
147
|
+
* @param {string[]} values
|
|
148
|
+
* @return {Argument}
|
|
149
|
+
*/
|
|
150
|
+
choices(values) {
|
|
151
|
+
this.argChoices = values.slice();
|
|
152
|
+
this.parseArg = (arg, previous) => {
|
|
153
|
+
if (!this.argChoices.includes(arg)) {
|
|
154
|
+
throw new InvalidArgumentError2(
|
|
155
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
if (this.variadic) {
|
|
159
|
+
return this._concatValue(arg, previous);
|
|
160
|
+
}
|
|
161
|
+
return arg;
|
|
162
|
+
};
|
|
163
|
+
return this;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Make argument required.
|
|
167
|
+
*
|
|
168
|
+
* @returns {Argument}
|
|
169
|
+
*/
|
|
170
|
+
argRequired() {
|
|
171
|
+
this.required = true;
|
|
172
|
+
return this;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Make argument optional.
|
|
176
|
+
*
|
|
177
|
+
* @returns {Argument}
|
|
178
|
+
*/
|
|
179
|
+
argOptional() {
|
|
180
|
+
this.required = false;
|
|
181
|
+
return this;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
function humanReadableArgName(arg) {
|
|
185
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
186
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
187
|
+
}
|
|
188
|
+
exports2.Argument = Argument2;
|
|
189
|
+
exports2.humanReadableArgName = humanReadableArgName;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// node_modules/commander/lib/help.js
|
|
194
|
+
var require_help = __commonJS({
|
|
195
|
+
"node_modules/commander/lib/help.js"(exports2) {
|
|
196
|
+
"use strict";
|
|
197
|
+
var { humanReadableArgName } = require_argument();
|
|
198
|
+
var Help2 = class {
|
|
199
|
+
constructor() {
|
|
200
|
+
this.helpWidth = void 0;
|
|
201
|
+
this.minWidthToWrap = 40;
|
|
202
|
+
this.sortSubcommands = false;
|
|
203
|
+
this.sortOptions = false;
|
|
204
|
+
this.showGlobalOptions = false;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
208
|
+
* and just before calling `formatHelp()`.
|
|
209
|
+
*
|
|
210
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
211
|
+
*
|
|
212
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
213
|
+
*/
|
|
214
|
+
prepareContext(contextOptions) {
|
|
215
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
219
|
+
*
|
|
220
|
+
* @param {Command} cmd
|
|
221
|
+
* @returns {Command[]}
|
|
222
|
+
*/
|
|
223
|
+
visibleCommands(cmd) {
|
|
224
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
225
|
+
const helpCommand = cmd._getHelpCommand();
|
|
226
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
227
|
+
visibleCommands.push(helpCommand);
|
|
228
|
+
}
|
|
229
|
+
if (this.sortSubcommands) {
|
|
230
|
+
visibleCommands.sort((a, b) => {
|
|
231
|
+
return a.name().localeCompare(b.name());
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
return visibleCommands;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Compare options for sort.
|
|
238
|
+
*
|
|
239
|
+
* @param {Option} a
|
|
240
|
+
* @param {Option} b
|
|
241
|
+
* @returns {number}
|
|
242
|
+
*/
|
|
243
|
+
compareOptions(a, b) {
|
|
244
|
+
const getSortKey = (option) => {
|
|
245
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
246
|
+
};
|
|
247
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
251
|
+
*
|
|
252
|
+
* @param {Command} cmd
|
|
253
|
+
* @returns {Option[]}
|
|
254
|
+
*/
|
|
255
|
+
visibleOptions(cmd) {
|
|
256
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
257
|
+
const helpOption = cmd._getHelpOption();
|
|
258
|
+
if (helpOption && !helpOption.hidden) {
|
|
259
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
260
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
261
|
+
if (!removeShort && !removeLong) {
|
|
262
|
+
visibleOptions.push(helpOption);
|
|
263
|
+
} else if (helpOption.long && !removeLong) {
|
|
264
|
+
visibleOptions.push(
|
|
265
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
266
|
+
);
|
|
267
|
+
} else if (helpOption.short && !removeShort) {
|
|
268
|
+
visibleOptions.push(
|
|
269
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (this.sortOptions) {
|
|
274
|
+
visibleOptions.sort(this.compareOptions);
|
|
275
|
+
}
|
|
276
|
+
return visibleOptions;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Get an array of the visible global options. (Not including help.)
|
|
280
|
+
*
|
|
281
|
+
* @param {Command} cmd
|
|
282
|
+
* @returns {Option[]}
|
|
283
|
+
*/
|
|
284
|
+
visibleGlobalOptions(cmd) {
|
|
285
|
+
if (!this.showGlobalOptions) return [];
|
|
286
|
+
const globalOptions = [];
|
|
287
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
288
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
289
|
+
(option) => !option.hidden
|
|
290
|
+
);
|
|
291
|
+
globalOptions.push(...visibleOptions);
|
|
292
|
+
}
|
|
293
|
+
if (this.sortOptions) {
|
|
294
|
+
globalOptions.sort(this.compareOptions);
|
|
295
|
+
}
|
|
296
|
+
return globalOptions;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Get an array of the arguments if any have a description.
|
|
300
|
+
*
|
|
301
|
+
* @param {Command} cmd
|
|
302
|
+
* @returns {Argument[]}
|
|
303
|
+
*/
|
|
304
|
+
visibleArguments(cmd) {
|
|
305
|
+
if (cmd._argsDescription) {
|
|
306
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
307
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
311
|
+
return cmd.registeredArguments;
|
|
312
|
+
}
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Get the command term to show in the list of subcommands.
|
|
317
|
+
*
|
|
318
|
+
* @param {Command} cmd
|
|
319
|
+
* @returns {string}
|
|
320
|
+
*/
|
|
321
|
+
subcommandTerm(cmd) {
|
|
322
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
323
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
324
|
+
(args ? " " + args : "");
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Get the option term to show in the list of options.
|
|
328
|
+
*
|
|
329
|
+
* @param {Option} option
|
|
330
|
+
* @returns {string}
|
|
331
|
+
*/
|
|
332
|
+
optionTerm(option) {
|
|
333
|
+
return option.flags;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Get the argument term to show in the list of arguments.
|
|
337
|
+
*
|
|
338
|
+
* @param {Argument} argument
|
|
339
|
+
* @returns {string}
|
|
340
|
+
*/
|
|
341
|
+
argumentTerm(argument) {
|
|
342
|
+
return argument.name();
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Get the longest command term length.
|
|
346
|
+
*
|
|
347
|
+
* @param {Command} cmd
|
|
348
|
+
* @param {Help} helper
|
|
349
|
+
* @returns {number}
|
|
350
|
+
*/
|
|
351
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
352
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
353
|
+
return Math.max(
|
|
354
|
+
max,
|
|
355
|
+
this.displayWidth(
|
|
356
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
357
|
+
)
|
|
358
|
+
);
|
|
359
|
+
}, 0);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Get the longest option term length.
|
|
363
|
+
*
|
|
364
|
+
* @param {Command} cmd
|
|
365
|
+
* @param {Help} helper
|
|
366
|
+
* @returns {number}
|
|
367
|
+
*/
|
|
368
|
+
longestOptionTermLength(cmd, helper) {
|
|
369
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
370
|
+
return Math.max(
|
|
371
|
+
max,
|
|
372
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
373
|
+
);
|
|
374
|
+
}, 0);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Get the longest global option term length.
|
|
378
|
+
*
|
|
379
|
+
* @param {Command} cmd
|
|
380
|
+
* @param {Help} helper
|
|
381
|
+
* @returns {number}
|
|
382
|
+
*/
|
|
383
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
384
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
385
|
+
return Math.max(
|
|
386
|
+
max,
|
|
387
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
388
|
+
);
|
|
389
|
+
}, 0);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Get the longest argument term length.
|
|
393
|
+
*
|
|
394
|
+
* @param {Command} cmd
|
|
395
|
+
* @param {Help} helper
|
|
396
|
+
* @returns {number}
|
|
397
|
+
*/
|
|
398
|
+
longestArgumentTermLength(cmd, helper) {
|
|
399
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
400
|
+
return Math.max(
|
|
401
|
+
max,
|
|
402
|
+
this.displayWidth(
|
|
403
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
404
|
+
)
|
|
405
|
+
);
|
|
406
|
+
}, 0);
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
410
|
+
*
|
|
411
|
+
* @param {Command} cmd
|
|
412
|
+
* @returns {string}
|
|
413
|
+
*/
|
|
414
|
+
commandUsage(cmd) {
|
|
415
|
+
let cmdName = cmd._name;
|
|
416
|
+
if (cmd._aliases[0]) {
|
|
417
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
418
|
+
}
|
|
419
|
+
let ancestorCmdNames = "";
|
|
420
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
421
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
422
|
+
}
|
|
423
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Get the description for the command.
|
|
427
|
+
*
|
|
428
|
+
* @param {Command} cmd
|
|
429
|
+
* @returns {string}
|
|
430
|
+
*/
|
|
431
|
+
commandDescription(cmd) {
|
|
432
|
+
return cmd.description();
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
436
|
+
* (Fallback to description for backwards compatibility.)
|
|
437
|
+
*
|
|
438
|
+
* @param {Command} cmd
|
|
439
|
+
* @returns {string}
|
|
440
|
+
*/
|
|
441
|
+
subcommandDescription(cmd) {
|
|
442
|
+
return cmd.summary() || cmd.description();
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Get the option description to show in the list of options.
|
|
446
|
+
*
|
|
447
|
+
* @param {Option} option
|
|
448
|
+
* @return {string}
|
|
449
|
+
*/
|
|
450
|
+
optionDescription(option) {
|
|
451
|
+
const extraInfo = [];
|
|
452
|
+
if (option.argChoices) {
|
|
453
|
+
extraInfo.push(
|
|
454
|
+
// use stringify to match the display of the default value
|
|
455
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
if (option.defaultValue !== void 0) {
|
|
459
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
460
|
+
if (showDefault) {
|
|
461
|
+
extraInfo.push(
|
|
462
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
467
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
468
|
+
}
|
|
469
|
+
if (option.envVar !== void 0) {
|
|
470
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
471
|
+
}
|
|
472
|
+
if (extraInfo.length > 0) {
|
|
473
|
+
return `${option.description} (${extraInfo.join(", ")})`;
|
|
474
|
+
}
|
|
475
|
+
return option.description;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Get the argument description to show in the list of arguments.
|
|
479
|
+
*
|
|
480
|
+
* @param {Argument} argument
|
|
481
|
+
* @return {string}
|
|
482
|
+
*/
|
|
483
|
+
argumentDescription(argument) {
|
|
484
|
+
const extraInfo = [];
|
|
485
|
+
if (argument.argChoices) {
|
|
486
|
+
extraInfo.push(
|
|
487
|
+
// use stringify to match the display of the default value
|
|
488
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
if (argument.defaultValue !== void 0) {
|
|
492
|
+
extraInfo.push(
|
|
493
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
if (extraInfo.length > 0) {
|
|
497
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
498
|
+
if (argument.description) {
|
|
499
|
+
return `${argument.description} ${extraDescription}`;
|
|
500
|
+
}
|
|
501
|
+
return extraDescription;
|
|
502
|
+
}
|
|
503
|
+
return argument.description;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Generate the built-in help text.
|
|
507
|
+
*
|
|
508
|
+
* @param {Command} cmd
|
|
509
|
+
* @param {Help} helper
|
|
510
|
+
* @returns {string}
|
|
511
|
+
*/
|
|
512
|
+
formatHelp(cmd, helper) {
|
|
513
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
514
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
515
|
+
function callFormatItem(term, description) {
|
|
516
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
517
|
+
}
|
|
518
|
+
let output2 = [
|
|
519
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
520
|
+
""
|
|
521
|
+
];
|
|
522
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
523
|
+
if (commandDescription.length > 0) {
|
|
524
|
+
output2 = output2.concat([
|
|
525
|
+
helper.boxWrap(
|
|
526
|
+
helper.styleCommandDescription(commandDescription),
|
|
527
|
+
helpWidth
|
|
528
|
+
),
|
|
529
|
+
""
|
|
530
|
+
]);
|
|
531
|
+
}
|
|
532
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
533
|
+
return callFormatItem(
|
|
534
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
535
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
536
|
+
);
|
|
537
|
+
});
|
|
538
|
+
if (argumentList.length > 0) {
|
|
539
|
+
output2 = output2.concat([
|
|
540
|
+
helper.styleTitle("Arguments:"),
|
|
541
|
+
...argumentList,
|
|
542
|
+
""
|
|
543
|
+
]);
|
|
544
|
+
}
|
|
545
|
+
const optionList = helper.visibleOptions(cmd).map((option) => {
|
|
546
|
+
return callFormatItem(
|
|
547
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
548
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
549
|
+
);
|
|
550
|
+
});
|
|
551
|
+
if (optionList.length > 0) {
|
|
552
|
+
output2 = output2.concat([
|
|
553
|
+
helper.styleTitle("Options:"),
|
|
554
|
+
...optionList,
|
|
555
|
+
""
|
|
556
|
+
]);
|
|
557
|
+
}
|
|
558
|
+
if (helper.showGlobalOptions) {
|
|
559
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
560
|
+
return callFormatItem(
|
|
561
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
562
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
563
|
+
);
|
|
564
|
+
});
|
|
565
|
+
if (globalOptionList.length > 0) {
|
|
566
|
+
output2 = output2.concat([
|
|
567
|
+
helper.styleTitle("Global Options:"),
|
|
568
|
+
...globalOptionList,
|
|
569
|
+
""
|
|
570
|
+
]);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
const commandList = helper.visibleCommands(cmd).map((cmd2) => {
|
|
574
|
+
return callFormatItem(
|
|
575
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
|
|
576
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
|
|
577
|
+
);
|
|
578
|
+
});
|
|
579
|
+
if (commandList.length > 0) {
|
|
580
|
+
output2 = output2.concat([
|
|
581
|
+
helper.styleTitle("Commands:"),
|
|
582
|
+
...commandList,
|
|
583
|
+
""
|
|
584
|
+
]);
|
|
585
|
+
}
|
|
586
|
+
return output2.join("\n");
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
590
|
+
*
|
|
591
|
+
* @param {string} str
|
|
592
|
+
* @returns {number}
|
|
593
|
+
*/
|
|
594
|
+
displayWidth(str) {
|
|
595
|
+
return stripColor(str).length;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
599
|
+
*
|
|
600
|
+
* @param {string} str
|
|
601
|
+
* @returns {string}
|
|
602
|
+
*/
|
|
603
|
+
styleTitle(str) {
|
|
604
|
+
return str;
|
|
605
|
+
}
|
|
606
|
+
styleUsage(str) {
|
|
607
|
+
return str.split(" ").map((word) => {
|
|
608
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
609
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
610
|
+
if (word[0] === "[" || word[0] === "<")
|
|
611
|
+
return this.styleArgumentText(word);
|
|
612
|
+
return this.styleCommandText(word);
|
|
613
|
+
}).join(" ");
|
|
614
|
+
}
|
|
615
|
+
styleCommandDescription(str) {
|
|
616
|
+
return this.styleDescriptionText(str);
|
|
617
|
+
}
|
|
618
|
+
styleOptionDescription(str) {
|
|
619
|
+
return this.styleDescriptionText(str);
|
|
620
|
+
}
|
|
621
|
+
styleSubcommandDescription(str) {
|
|
622
|
+
return this.styleDescriptionText(str);
|
|
623
|
+
}
|
|
624
|
+
styleArgumentDescription(str) {
|
|
625
|
+
return this.styleDescriptionText(str);
|
|
626
|
+
}
|
|
627
|
+
styleDescriptionText(str) {
|
|
628
|
+
return str;
|
|
629
|
+
}
|
|
630
|
+
styleOptionTerm(str) {
|
|
631
|
+
return this.styleOptionText(str);
|
|
632
|
+
}
|
|
633
|
+
styleSubcommandTerm(str) {
|
|
634
|
+
return str.split(" ").map((word) => {
|
|
635
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
636
|
+
if (word[0] === "[" || word[0] === "<")
|
|
637
|
+
return this.styleArgumentText(word);
|
|
638
|
+
return this.styleSubcommandText(word);
|
|
639
|
+
}).join(" ");
|
|
640
|
+
}
|
|
641
|
+
styleArgumentTerm(str) {
|
|
642
|
+
return this.styleArgumentText(str);
|
|
643
|
+
}
|
|
644
|
+
styleOptionText(str) {
|
|
645
|
+
return str;
|
|
646
|
+
}
|
|
647
|
+
styleArgumentText(str) {
|
|
648
|
+
return str;
|
|
649
|
+
}
|
|
650
|
+
styleSubcommandText(str) {
|
|
651
|
+
return str;
|
|
652
|
+
}
|
|
653
|
+
styleCommandText(str) {
|
|
654
|
+
return str;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Calculate the pad width from the maximum term length.
|
|
658
|
+
*
|
|
659
|
+
* @param {Command} cmd
|
|
660
|
+
* @param {Help} helper
|
|
661
|
+
* @returns {number}
|
|
662
|
+
*/
|
|
663
|
+
padWidth(cmd, helper) {
|
|
664
|
+
return Math.max(
|
|
665
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
666
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
667
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
668
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
673
|
+
*
|
|
674
|
+
* @param {string} str
|
|
675
|
+
* @returns {boolean}
|
|
676
|
+
*/
|
|
677
|
+
preformatted(str) {
|
|
678
|
+
return /\n[^\S\r\n]/.test(str);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
682
|
+
*
|
|
683
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
684
|
+
* TTT DDD DDDD
|
|
685
|
+
* DD DDD
|
|
686
|
+
*
|
|
687
|
+
* @param {string} term
|
|
688
|
+
* @param {number} termWidth
|
|
689
|
+
* @param {string} description
|
|
690
|
+
* @param {Help} helper
|
|
691
|
+
* @returns {string}
|
|
692
|
+
*/
|
|
693
|
+
formatItem(term, termWidth, description, helper) {
|
|
694
|
+
const itemIndent = 2;
|
|
695
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
696
|
+
if (!description) return itemIndentStr + term;
|
|
697
|
+
const paddedTerm = term.padEnd(
|
|
698
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
699
|
+
);
|
|
700
|
+
const spacerWidth = 2;
|
|
701
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
702
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
703
|
+
let formattedDescription;
|
|
704
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
705
|
+
formattedDescription = description;
|
|
706
|
+
} else {
|
|
707
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
708
|
+
formattedDescription = wrappedDescription.replace(
|
|
709
|
+
/\n/g,
|
|
710
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
711
|
+
);
|
|
712
|
+
}
|
|
713
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
714
|
+
${itemIndentStr}`);
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
718
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
719
|
+
*
|
|
720
|
+
* @param {string} str
|
|
721
|
+
* @param {number} width
|
|
722
|
+
* @returns {string}
|
|
723
|
+
*/
|
|
724
|
+
boxWrap(str, width) {
|
|
725
|
+
if (width < this.minWidthToWrap) return str;
|
|
726
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
727
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
728
|
+
const wrappedLines = [];
|
|
729
|
+
rawLines.forEach((line) => {
|
|
730
|
+
const chunks = line.match(chunkPattern);
|
|
731
|
+
if (chunks === null) {
|
|
732
|
+
wrappedLines.push("");
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
let sumChunks = [chunks.shift()];
|
|
736
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
737
|
+
chunks.forEach((chunk) => {
|
|
738
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
739
|
+
if (sumWidth + visibleWidth <= width) {
|
|
740
|
+
sumChunks.push(chunk);
|
|
741
|
+
sumWidth += visibleWidth;
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
wrappedLines.push(sumChunks.join(""));
|
|
745
|
+
const nextChunk = chunk.trimStart();
|
|
746
|
+
sumChunks = [nextChunk];
|
|
747
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
748
|
+
});
|
|
749
|
+
wrappedLines.push(sumChunks.join(""));
|
|
750
|
+
});
|
|
751
|
+
return wrappedLines.join("\n");
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
function stripColor(str) {
|
|
755
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
756
|
+
return str.replace(sgrPattern, "");
|
|
757
|
+
}
|
|
758
|
+
exports2.Help = Help2;
|
|
759
|
+
exports2.stripColor = stripColor;
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
// node_modules/commander/lib/option.js
|
|
764
|
+
var require_option = __commonJS({
|
|
765
|
+
"node_modules/commander/lib/option.js"(exports2) {
|
|
766
|
+
"use strict";
|
|
767
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
768
|
+
var Option2 = class {
|
|
769
|
+
/**
|
|
770
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
771
|
+
*
|
|
772
|
+
* @param {string} flags
|
|
773
|
+
* @param {string} [description]
|
|
774
|
+
*/
|
|
775
|
+
constructor(flags, description) {
|
|
776
|
+
this.flags = flags;
|
|
777
|
+
this.description = description || "";
|
|
778
|
+
this.required = flags.includes("<");
|
|
779
|
+
this.optional = flags.includes("[");
|
|
780
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
781
|
+
this.mandatory = false;
|
|
782
|
+
const optionFlags = splitOptionFlags(flags);
|
|
783
|
+
this.short = optionFlags.shortFlag;
|
|
784
|
+
this.long = optionFlags.longFlag;
|
|
785
|
+
this.negate = false;
|
|
786
|
+
if (this.long) {
|
|
787
|
+
this.negate = this.long.startsWith("--no-");
|
|
788
|
+
}
|
|
789
|
+
this.defaultValue = void 0;
|
|
790
|
+
this.defaultValueDescription = void 0;
|
|
791
|
+
this.presetArg = void 0;
|
|
792
|
+
this.envVar = void 0;
|
|
793
|
+
this.parseArg = void 0;
|
|
794
|
+
this.hidden = false;
|
|
795
|
+
this.argChoices = void 0;
|
|
796
|
+
this.conflictsWith = [];
|
|
797
|
+
this.implied = void 0;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
801
|
+
*
|
|
802
|
+
* @param {*} value
|
|
803
|
+
* @param {string} [description]
|
|
804
|
+
* @return {Option}
|
|
805
|
+
*/
|
|
806
|
+
default(value, description) {
|
|
807
|
+
this.defaultValue = value;
|
|
808
|
+
this.defaultValueDescription = description;
|
|
809
|
+
return this;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
813
|
+
* The custom processing (parseArg) is called.
|
|
814
|
+
*
|
|
815
|
+
* @example
|
|
816
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
817
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
818
|
+
*
|
|
819
|
+
* @param {*} arg
|
|
820
|
+
* @return {Option}
|
|
821
|
+
*/
|
|
822
|
+
preset(arg) {
|
|
823
|
+
this.presetArg = arg;
|
|
824
|
+
return this;
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Add option name(s) that conflict with this option.
|
|
828
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
829
|
+
*
|
|
830
|
+
* @example
|
|
831
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
832
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
833
|
+
*
|
|
834
|
+
* @param {(string | string[])} names
|
|
835
|
+
* @return {Option}
|
|
836
|
+
*/
|
|
837
|
+
conflicts(names) {
|
|
838
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
839
|
+
return this;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
843
|
+
*
|
|
844
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
845
|
+
*
|
|
846
|
+
* @example
|
|
847
|
+
* program
|
|
848
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
849
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
850
|
+
*
|
|
851
|
+
* @param {object} impliedOptionValues
|
|
852
|
+
* @return {Option}
|
|
853
|
+
*/
|
|
854
|
+
implies(impliedOptionValues) {
|
|
855
|
+
let newImplied = impliedOptionValues;
|
|
856
|
+
if (typeof impliedOptionValues === "string") {
|
|
857
|
+
newImplied = { [impliedOptionValues]: true };
|
|
858
|
+
}
|
|
859
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
860
|
+
return this;
|
|
861
|
+
}
|
|
862
|
+
/**
|
|
863
|
+
* Set environment variable to check for option value.
|
|
864
|
+
*
|
|
865
|
+
* An environment variable is only used if when processed the current option value is
|
|
866
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
867
|
+
*
|
|
868
|
+
* @param {string} name
|
|
869
|
+
* @return {Option}
|
|
870
|
+
*/
|
|
871
|
+
env(name) {
|
|
872
|
+
this.envVar = name;
|
|
873
|
+
return this;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
877
|
+
*
|
|
878
|
+
* @param {Function} [fn]
|
|
879
|
+
* @return {Option}
|
|
880
|
+
*/
|
|
881
|
+
argParser(fn) {
|
|
882
|
+
this.parseArg = fn;
|
|
883
|
+
return this;
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
887
|
+
*
|
|
888
|
+
* @param {boolean} [mandatory=true]
|
|
889
|
+
* @return {Option}
|
|
890
|
+
*/
|
|
891
|
+
makeOptionMandatory(mandatory = true) {
|
|
892
|
+
this.mandatory = !!mandatory;
|
|
893
|
+
return this;
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Hide option in help.
|
|
897
|
+
*
|
|
898
|
+
* @param {boolean} [hide=true]
|
|
899
|
+
* @return {Option}
|
|
900
|
+
*/
|
|
901
|
+
hideHelp(hide = true) {
|
|
902
|
+
this.hidden = !!hide;
|
|
903
|
+
return this;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* @package
|
|
907
|
+
*/
|
|
908
|
+
_concatValue(value, previous) {
|
|
909
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
910
|
+
return [value];
|
|
911
|
+
}
|
|
912
|
+
return previous.concat(value);
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Only allow option value to be one of choices.
|
|
916
|
+
*
|
|
917
|
+
* @param {string[]} values
|
|
918
|
+
* @return {Option}
|
|
919
|
+
*/
|
|
920
|
+
choices(values) {
|
|
921
|
+
this.argChoices = values.slice();
|
|
922
|
+
this.parseArg = (arg, previous) => {
|
|
923
|
+
if (!this.argChoices.includes(arg)) {
|
|
924
|
+
throw new InvalidArgumentError2(
|
|
925
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
if (this.variadic) {
|
|
929
|
+
return this._concatValue(arg, previous);
|
|
930
|
+
}
|
|
931
|
+
return arg;
|
|
932
|
+
};
|
|
933
|
+
return this;
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Return option name.
|
|
937
|
+
*
|
|
938
|
+
* @return {string}
|
|
939
|
+
*/
|
|
940
|
+
name() {
|
|
941
|
+
if (this.long) {
|
|
942
|
+
return this.long.replace(/^--/, "");
|
|
943
|
+
}
|
|
944
|
+
return this.short.replace(/^-/, "");
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Return option name, in a camelcase format that can be used
|
|
948
|
+
* as an object attribute key.
|
|
949
|
+
*
|
|
950
|
+
* @return {string}
|
|
951
|
+
*/
|
|
952
|
+
attributeName() {
|
|
953
|
+
if (this.negate) {
|
|
954
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
955
|
+
}
|
|
956
|
+
return camelcase(this.name());
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Check if `arg` matches the short or long flag.
|
|
960
|
+
*
|
|
961
|
+
* @param {string} arg
|
|
962
|
+
* @return {boolean}
|
|
963
|
+
* @package
|
|
964
|
+
*/
|
|
965
|
+
is(arg) {
|
|
966
|
+
return this.short === arg || this.long === arg;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Return whether a boolean option.
|
|
970
|
+
*
|
|
971
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
972
|
+
*
|
|
973
|
+
* @return {boolean}
|
|
974
|
+
* @package
|
|
975
|
+
*/
|
|
976
|
+
isBoolean() {
|
|
977
|
+
return !this.required && !this.optional && !this.negate;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
var DualOptions = class {
|
|
981
|
+
/**
|
|
982
|
+
* @param {Option[]} options
|
|
983
|
+
*/
|
|
984
|
+
constructor(options) {
|
|
985
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
986
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
987
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
988
|
+
options.forEach((option) => {
|
|
989
|
+
if (option.negate) {
|
|
990
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
991
|
+
} else {
|
|
992
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
993
|
+
}
|
|
994
|
+
});
|
|
995
|
+
this.negativeOptions.forEach((value, key) => {
|
|
996
|
+
if (this.positiveOptions.has(key)) {
|
|
997
|
+
this.dualOptions.add(key);
|
|
998
|
+
}
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1003
|
+
*
|
|
1004
|
+
* @param {*} value
|
|
1005
|
+
* @param {Option} option
|
|
1006
|
+
* @returns {boolean}
|
|
1007
|
+
*/
|
|
1008
|
+
valueFromOption(value, option) {
|
|
1009
|
+
const optionKey = option.attributeName();
|
|
1010
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1011
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1012
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1013
|
+
return option.negate === (negativeValue === value);
|
|
1014
|
+
}
|
|
1015
|
+
};
|
|
1016
|
+
function camelcase(str) {
|
|
1017
|
+
return str.split("-").reduce((str2, word) => {
|
|
1018
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
function splitOptionFlags(flags) {
|
|
1022
|
+
let shortFlag;
|
|
1023
|
+
let longFlag;
|
|
1024
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1025
|
+
const longFlagExp = /^--[^-]/;
|
|
1026
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1027
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1028
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1029
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1030
|
+
shortFlag = flagParts.shift();
|
|
1031
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1032
|
+
shortFlag = longFlag;
|
|
1033
|
+
longFlag = flagParts.shift();
|
|
1034
|
+
}
|
|
1035
|
+
if (flagParts[0].startsWith("-")) {
|
|
1036
|
+
const unsupportedFlag = flagParts[0];
|
|
1037
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1038
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1039
|
+
throw new Error(
|
|
1040
|
+
`${baseError}
|
|
1041
|
+
- a short flag is a single dash and a single character
|
|
1042
|
+
- either use a single dash and a single character (for a short flag)
|
|
1043
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1044
|
+
);
|
|
1045
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1046
|
+
throw new Error(`${baseError}
|
|
1047
|
+
- too many short flags`);
|
|
1048
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1049
|
+
throw new Error(`${baseError}
|
|
1050
|
+
- too many long flags`);
|
|
1051
|
+
throw new Error(`${baseError}
|
|
1052
|
+
- unrecognised flag format`);
|
|
1053
|
+
}
|
|
1054
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1055
|
+
throw new Error(
|
|
1056
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1057
|
+
);
|
|
1058
|
+
return { shortFlag, longFlag };
|
|
1059
|
+
}
|
|
1060
|
+
exports2.Option = Option2;
|
|
1061
|
+
exports2.DualOptions = DualOptions;
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
|
|
1065
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1066
|
+
var require_suggestSimilar = __commonJS({
|
|
1067
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports2) {
|
|
1068
|
+
"use strict";
|
|
1069
|
+
var maxDistance = 3;
|
|
1070
|
+
function editDistance(a, b) {
|
|
1071
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1072
|
+
return Math.max(a.length, b.length);
|
|
1073
|
+
const d = [];
|
|
1074
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1075
|
+
d[i] = [i];
|
|
1076
|
+
}
|
|
1077
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1078
|
+
d[0][j] = j;
|
|
1079
|
+
}
|
|
1080
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1081
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1082
|
+
let cost = 1;
|
|
1083
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1084
|
+
cost = 0;
|
|
1085
|
+
} else {
|
|
1086
|
+
cost = 1;
|
|
1087
|
+
}
|
|
1088
|
+
d[i][j] = Math.min(
|
|
1089
|
+
d[i - 1][j] + 1,
|
|
1090
|
+
// deletion
|
|
1091
|
+
d[i][j - 1] + 1,
|
|
1092
|
+
// insertion
|
|
1093
|
+
d[i - 1][j - 1] + cost
|
|
1094
|
+
// substitution
|
|
1095
|
+
);
|
|
1096
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1097
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return d[a.length][b.length];
|
|
1102
|
+
}
|
|
1103
|
+
function suggestSimilar(word, candidates) {
|
|
1104
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1105
|
+
candidates = Array.from(new Set(candidates));
|
|
1106
|
+
const searchingOptions = word.startsWith("--");
|
|
1107
|
+
if (searchingOptions) {
|
|
1108
|
+
word = word.slice(2);
|
|
1109
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1110
|
+
}
|
|
1111
|
+
let similar = [];
|
|
1112
|
+
let bestDistance = maxDistance;
|
|
1113
|
+
const minSimilarity = 0.4;
|
|
1114
|
+
candidates.forEach((candidate) => {
|
|
1115
|
+
if (candidate.length <= 1) return;
|
|
1116
|
+
const distance = editDistance(word, candidate);
|
|
1117
|
+
const length = Math.max(word.length, candidate.length);
|
|
1118
|
+
const similarity = (length - distance) / length;
|
|
1119
|
+
if (similarity > minSimilarity) {
|
|
1120
|
+
if (distance < bestDistance) {
|
|
1121
|
+
bestDistance = distance;
|
|
1122
|
+
similar = [candidate];
|
|
1123
|
+
} else if (distance === bestDistance) {
|
|
1124
|
+
similar.push(candidate);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
});
|
|
1128
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1129
|
+
if (searchingOptions) {
|
|
1130
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1131
|
+
}
|
|
1132
|
+
if (similar.length > 1) {
|
|
1133
|
+
return `
|
|
1134
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1135
|
+
}
|
|
1136
|
+
if (similar.length === 1) {
|
|
1137
|
+
return `
|
|
1138
|
+
(Did you mean ${similar[0]}?)`;
|
|
1139
|
+
}
|
|
1140
|
+
return "";
|
|
1141
|
+
}
|
|
1142
|
+
exports2.suggestSimilar = suggestSimilar;
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
|
|
1146
|
+
// node_modules/commander/lib/command.js
|
|
1147
|
+
var require_command = __commonJS({
|
|
1148
|
+
"node_modules/commander/lib/command.js"(exports2) {
|
|
1149
|
+
"use strict";
|
|
1150
|
+
var EventEmitter = require("events").EventEmitter;
|
|
1151
|
+
var childProcess = require("child_process");
|
|
1152
|
+
var path = require("path");
|
|
1153
|
+
var fs = require("fs");
|
|
1154
|
+
var process2 = require("process");
|
|
1155
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
1156
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
1157
|
+
var { Help: Help2, stripColor } = require_help();
|
|
1158
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
1159
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
1160
|
+
var Command2 = class _Command extends EventEmitter {
|
|
1161
|
+
/**
|
|
1162
|
+
* Initialize a new `Command`.
|
|
1163
|
+
*
|
|
1164
|
+
* @param {string} [name]
|
|
1165
|
+
*/
|
|
1166
|
+
constructor(name) {
|
|
1167
|
+
super();
|
|
1168
|
+
this.commands = [];
|
|
1169
|
+
this.options = [];
|
|
1170
|
+
this.parent = null;
|
|
1171
|
+
this._allowUnknownOption = false;
|
|
1172
|
+
this._allowExcessArguments = false;
|
|
1173
|
+
this.registeredArguments = [];
|
|
1174
|
+
this._args = this.registeredArguments;
|
|
1175
|
+
this.args = [];
|
|
1176
|
+
this.rawArgs = [];
|
|
1177
|
+
this.processedArgs = [];
|
|
1178
|
+
this._scriptPath = null;
|
|
1179
|
+
this._name = name || "";
|
|
1180
|
+
this._optionValues = {};
|
|
1181
|
+
this._optionValueSources = {};
|
|
1182
|
+
this._storeOptionsAsProperties = false;
|
|
1183
|
+
this._actionHandler = null;
|
|
1184
|
+
this._executableHandler = false;
|
|
1185
|
+
this._executableFile = null;
|
|
1186
|
+
this._executableDir = null;
|
|
1187
|
+
this._defaultCommandName = null;
|
|
1188
|
+
this._exitCallback = null;
|
|
1189
|
+
this._aliases = [];
|
|
1190
|
+
this._combineFlagAndOptionalValue = true;
|
|
1191
|
+
this._description = "";
|
|
1192
|
+
this._summary = "";
|
|
1193
|
+
this._argsDescription = void 0;
|
|
1194
|
+
this._enablePositionalOptions = false;
|
|
1195
|
+
this._passThroughOptions = false;
|
|
1196
|
+
this._lifeCycleHooks = {};
|
|
1197
|
+
this._showHelpAfterError = false;
|
|
1198
|
+
this._showSuggestionAfterError = true;
|
|
1199
|
+
this._savedState = null;
|
|
1200
|
+
this._outputConfiguration = {
|
|
1201
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1202
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1203
|
+
outputError: (str, write) => write(str),
|
|
1204
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1205
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1206
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1207
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1208
|
+
stripColor: (str) => stripColor(str)
|
|
1209
|
+
};
|
|
1210
|
+
this._hidden = false;
|
|
1211
|
+
this._helpOption = void 0;
|
|
1212
|
+
this._addImplicitHelpCommand = void 0;
|
|
1213
|
+
this._helpCommand = void 0;
|
|
1214
|
+
this._helpConfiguration = {};
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1218
|
+
*
|
|
1219
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1220
|
+
*
|
|
1221
|
+
* @param {Command} sourceCommand
|
|
1222
|
+
* @return {Command} `this` command for chaining
|
|
1223
|
+
*/
|
|
1224
|
+
copyInheritedSettings(sourceCommand) {
|
|
1225
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1226
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1227
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1228
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1229
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1230
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1231
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1232
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1233
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1234
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1235
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1236
|
+
return this;
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* @returns {Command[]}
|
|
1240
|
+
* @private
|
|
1241
|
+
*/
|
|
1242
|
+
_getCommandAndAncestors() {
|
|
1243
|
+
const result = [];
|
|
1244
|
+
for (let command = this; command; command = command.parent) {
|
|
1245
|
+
result.push(command);
|
|
1246
|
+
}
|
|
1247
|
+
return result;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Define a command.
|
|
1251
|
+
*
|
|
1252
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1253
|
+
*
|
|
1254
|
+
* @example
|
|
1255
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1256
|
+
* program
|
|
1257
|
+
* .command('clone <source> [destination]')
|
|
1258
|
+
* .description('clone a repository into a newly created directory')
|
|
1259
|
+
* .action((source, destination) => {
|
|
1260
|
+
* console.log('clone command called');
|
|
1261
|
+
* });
|
|
1262
|
+
*
|
|
1263
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1264
|
+
* program
|
|
1265
|
+
* .command('start <service>', 'start named service')
|
|
1266
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1267
|
+
*
|
|
1268
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1269
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1270
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1271
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1272
|
+
*/
|
|
1273
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1274
|
+
let desc = actionOptsOrExecDesc;
|
|
1275
|
+
let opts = execOpts;
|
|
1276
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1277
|
+
opts = desc;
|
|
1278
|
+
desc = null;
|
|
1279
|
+
}
|
|
1280
|
+
opts = opts || {};
|
|
1281
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1282
|
+
const cmd = this.createCommand(name);
|
|
1283
|
+
if (desc) {
|
|
1284
|
+
cmd.description(desc);
|
|
1285
|
+
cmd._executableHandler = true;
|
|
1286
|
+
}
|
|
1287
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1288
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1289
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1290
|
+
if (args) cmd.arguments(args);
|
|
1291
|
+
this._registerCommand(cmd);
|
|
1292
|
+
cmd.parent = this;
|
|
1293
|
+
cmd.copyInheritedSettings(this);
|
|
1294
|
+
if (desc) return this;
|
|
1295
|
+
return cmd;
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* Factory routine to create a new unattached command.
|
|
1299
|
+
*
|
|
1300
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1301
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1302
|
+
*
|
|
1303
|
+
* @param {string} [name]
|
|
1304
|
+
* @return {Command} new command
|
|
1305
|
+
*/
|
|
1306
|
+
createCommand(name) {
|
|
1307
|
+
return new _Command(name);
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1311
|
+
* or by overriding Help properties using configureHelp().
|
|
1312
|
+
*
|
|
1313
|
+
* @return {Help}
|
|
1314
|
+
*/
|
|
1315
|
+
createHelp() {
|
|
1316
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1320
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1321
|
+
*
|
|
1322
|
+
* @param {object} [configuration] - configuration options
|
|
1323
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1324
|
+
*/
|
|
1325
|
+
configureHelp(configuration) {
|
|
1326
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1327
|
+
this._helpConfiguration = configuration;
|
|
1328
|
+
return this;
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1332
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1333
|
+
*
|
|
1334
|
+
* The configuration properties are all functions:
|
|
1335
|
+
*
|
|
1336
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1337
|
+
* writeOut(str)
|
|
1338
|
+
* writeErr(str)
|
|
1339
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1340
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1341
|
+
* // specify width for wrapping help
|
|
1342
|
+
* getOutHelpWidth()
|
|
1343
|
+
* getErrHelpWidth()
|
|
1344
|
+
* // color support, currently only used with Help
|
|
1345
|
+
* getOutHasColors()
|
|
1346
|
+
* getErrHasColors()
|
|
1347
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1348
|
+
*
|
|
1349
|
+
* @param {object} [configuration] - configuration options
|
|
1350
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1351
|
+
*/
|
|
1352
|
+
configureOutput(configuration) {
|
|
1353
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1354
|
+
Object.assign(this._outputConfiguration, configuration);
|
|
1355
|
+
return this;
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Display the help or a custom message after an error occurs.
|
|
1359
|
+
*
|
|
1360
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1361
|
+
* @return {Command} `this` command for chaining
|
|
1362
|
+
*/
|
|
1363
|
+
showHelpAfterError(displayHelp = true) {
|
|
1364
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1365
|
+
this._showHelpAfterError = displayHelp;
|
|
1366
|
+
return this;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1370
|
+
*
|
|
1371
|
+
* @param {boolean} [displaySuggestion]
|
|
1372
|
+
* @return {Command} `this` command for chaining
|
|
1373
|
+
*/
|
|
1374
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1375
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1376
|
+
return this;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Add a prepared subcommand.
|
|
1380
|
+
*
|
|
1381
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1382
|
+
*
|
|
1383
|
+
* @param {Command} cmd - new subcommand
|
|
1384
|
+
* @param {object} [opts] - configuration options
|
|
1385
|
+
* @return {Command} `this` command for chaining
|
|
1386
|
+
*/
|
|
1387
|
+
addCommand(cmd, opts) {
|
|
1388
|
+
if (!cmd._name) {
|
|
1389
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1390
|
+
- specify the name in Command constructor or using .name()`);
|
|
1391
|
+
}
|
|
1392
|
+
opts = opts || {};
|
|
1393
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1394
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1395
|
+
this._registerCommand(cmd);
|
|
1396
|
+
cmd.parent = this;
|
|
1397
|
+
cmd._checkForBrokenPassThrough();
|
|
1398
|
+
return this;
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Factory routine to create a new unattached argument.
|
|
1402
|
+
*
|
|
1403
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1404
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1405
|
+
*
|
|
1406
|
+
* @param {string} name
|
|
1407
|
+
* @param {string} [description]
|
|
1408
|
+
* @return {Argument} new argument
|
|
1409
|
+
*/
|
|
1410
|
+
createArgument(name, description) {
|
|
1411
|
+
return new Argument2(name, description);
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Define argument syntax for command.
|
|
1415
|
+
*
|
|
1416
|
+
* The default is that the argument is required, and you can explicitly
|
|
1417
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1418
|
+
*
|
|
1419
|
+
* @example
|
|
1420
|
+
* program.argument('<input-file>');
|
|
1421
|
+
* program.argument('[output-file]');
|
|
1422
|
+
*
|
|
1423
|
+
* @param {string} name
|
|
1424
|
+
* @param {string} [description]
|
|
1425
|
+
* @param {(Function|*)} [fn] - custom argument processing function
|
|
1426
|
+
* @param {*} [defaultValue]
|
|
1427
|
+
* @return {Command} `this` command for chaining
|
|
1428
|
+
*/
|
|
1429
|
+
argument(name, description, fn, defaultValue) {
|
|
1430
|
+
const argument = this.createArgument(name, description);
|
|
1431
|
+
if (typeof fn === "function") {
|
|
1432
|
+
argument.default(defaultValue).argParser(fn);
|
|
1433
|
+
} else {
|
|
1434
|
+
argument.default(fn);
|
|
1435
|
+
}
|
|
1436
|
+
this.addArgument(argument);
|
|
1437
|
+
return this;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1441
|
+
*
|
|
1442
|
+
* See also .argument().
|
|
1443
|
+
*
|
|
1444
|
+
* @example
|
|
1445
|
+
* program.arguments('<cmd> [env]');
|
|
1446
|
+
*
|
|
1447
|
+
* @param {string} names
|
|
1448
|
+
* @return {Command} `this` command for chaining
|
|
1449
|
+
*/
|
|
1450
|
+
arguments(names) {
|
|
1451
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1452
|
+
this.argument(detail);
|
|
1453
|
+
});
|
|
1454
|
+
return this;
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1458
|
+
*
|
|
1459
|
+
* @param {Argument} argument
|
|
1460
|
+
* @return {Command} `this` command for chaining
|
|
1461
|
+
*/
|
|
1462
|
+
addArgument(argument) {
|
|
1463
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1464
|
+
if (previousArgument && previousArgument.variadic) {
|
|
1465
|
+
throw new Error(
|
|
1466
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1467
|
+
);
|
|
1468
|
+
}
|
|
1469
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1470
|
+
throw new Error(
|
|
1471
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1472
|
+
);
|
|
1473
|
+
}
|
|
1474
|
+
this.registeredArguments.push(argument);
|
|
1475
|
+
return this;
|
|
1476
|
+
}
|
|
1477
|
+
/**
|
|
1478
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1479
|
+
*
|
|
1480
|
+
* @example
|
|
1481
|
+
* program.helpCommand('help [cmd]');
|
|
1482
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1483
|
+
* program.helpCommand(false); // suppress default help command
|
|
1484
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1485
|
+
*
|
|
1486
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1487
|
+
* @param {string} [description] - custom description
|
|
1488
|
+
* @return {Command} `this` command for chaining
|
|
1489
|
+
*/
|
|
1490
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1491
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1492
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1493
|
+
return this;
|
|
1494
|
+
}
|
|
1495
|
+
enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1496
|
+
const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1497
|
+
const helpDescription = description ?? "display help for command";
|
|
1498
|
+
const helpCommand = this.createCommand(helpName);
|
|
1499
|
+
helpCommand.helpOption(false);
|
|
1500
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1501
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1502
|
+
this._addImplicitHelpCommand = true;
|
|
1503
|
+
this._helpCommand = helpCommand;
|
|
1504
|
+
return this;
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Add prepared custom help command.
|
|
1508
|
+
*
|
|
1509
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1510
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1511
|
+
* @return {Command} `this` command for chaining
|
|
1512
|
+
*/
|
|
1513
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1514
|
+
if (typeof helpCommand !== "object") {
|
|
1515
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1516
|
+
return this;
|
|
1517
|
+
}
|
|
1518
|
+
this._addImplicitHelpCommand = true;
|
|
1519
|
+
this._helpCommand = helpCommand;
|
|
1520
|
+
return this;
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Lazy create help command.
|
|
1524
|
+
*
|
|
1525
|
+
* @return {(Command|null)}
|
|
1526
|
+
* @package
|
|
1527
|
+
*/
|
|
1528
|
+
_getHelpCommand() {
|
|
1529
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1530
|
+
if (hasImplicitHelpCommand) {
|
|
1531
|
+
if (this._helpCommand === void 0) {
|
|
1532
|
+
this.helpCommand(void 0, void 0);
|
|
1533
|
+
}
|
|
1534
|
+
return this._helpCommand;
|
|
1535
|
+
}
|
|
1536
|
+
return null;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Add hook for life cycle event.
|
|
1540
|
+
*
|
|
1541
|
+
* @param {string} event
|
|
1542
|
+
* @param {Function} listener
|
|
1543
|
+
* @return {Command} `this` command for chaining
|
|
1544
|
+
*/
|
|
1545
|
+
hook(event, listener) {
|
|
1546
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1547
|
+
if (!allowedValues.includes(event)) {
|
|
1548
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1549
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1550
|
+
}
|
|
1551
|
+
if (this._lifeCycleHooks[event]) {
|
|
1552
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1553
|
+
} else {
|
|
1554
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1555
|
+
}
|
|
1556
|
+
return this;
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1560
|
+
*
|
|
1561
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1562
|
+
* @return {Command} `this` command for chaining
|
|
1563
|
+
*/
|
|
1564
|
+
exitOverride(fn) {
|
|
1565
|
+
if (fn) {
|
|
1566
|
+
this._exitCallback = fn;
|
|
1567
|
+
} else {
|
|
1568
|
+
this._exitCallback = (err) => {
|
|
1569
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1570
|
+
throw err;
|
|
1571
|
+
} else {
|
|
1572
|
+
}
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
return this;
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1579
|
+
*
|
|
1580
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1581
|
+
* @param {string} code an id string representing the error
|
|
1582
|
+
* @param {string} message human-readable description of the error
|
|
1583
|
+
* @return never
|
|
1584
|
+
* @private
|
|
1585
|
+
*/
|
|
1586
|
+
_exit(exitCode, code, message) {
|
|
1587
|
+
if (this._exitCallback) {
|
|
1588
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1589
|
+
}
|
|
1590
|
+
process2.exit(exitCode);
|
|
1591
|
+
}
|
|
1592
|
+
/**
|
|
1593
|
+
* Register callback `fn` for the command.
|
|
1594
|
+
*
|
|
1595
|
+
* @example
|
|
1596
|
+
* program
|
|
1597
|
+
* .command('serve')
|
|
1598
|
+
* .description('start service')
|
|
1599
|
+
* .action(function() {
|
|
1600
|
+
* // do work here
|
|
1601
|
+
* });
|
|
1602
|
+
*
|
|
1603
|
+
* @param {Function} fn
|
|
1604
|
+
* @return {Command} `this` command for chaining
|
|
1605
|
+
*/
|
|
1606
|
+
action(fn) {
|
|
1607
|
+
const listener = (args) => {
|
|
1608
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1609
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1610
|
+
if (this._storeOptionsAsProperties) {
|
|
1611
|
+
actionArgs[expectedArgsCount] = this;
|
|
1612
|
+
} else {
|
|
1613
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1614
|
+
}
|
|
1615
|
+
actionArgs.push(this);
|
|
1616
|
+
return fn.apply(this, actionArgs);
|
|
1617
|
+
};
|
|
1618
|
+
this._actionHandler = listener;
|
|
1619
|
+
return this;
|
|
1620
|
+
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Factory routine to create a new unattached option.
|
|
1623
|
+
*
|
|
1624
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1625
|
+
* create the option. You can override createOption to return a custom option.
|
|
1626
|
+
*
|
|
1627
|
+
* @param {string} flags
|
|
1628
|
+
* @param {string} [description]
|
|
1629
|
+
* @return {Option} new option
|
|
1630
|
+
*/
|
|
1631
|
+
createOption(flags, description) {
|
|
1632
|
+
return new Option2(flags, description);
|
|
1633
|
+
}
|
|
1634
|
+
/**
|
|
1635
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1636
|
+
*
|
|
1637
|
+
* @param {(Option | Argument)} target
|
|
1638
|
+
* @param {string} value
|
|
1639
|
+
* @param {*} previous
|
|
1640
|
+
* @param {string} invalidArgumentMessage
|
|
1641
|
+
* @private
|
|
1642
|
+
*/
|
|
1643
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1644
|
+
try {
|
|
1645
|
+
return target.parseArg(value, previous);
|
|
1646
|
+
} catch (err) {
|
|
1647
|
+
if (err.code === "commander.invalidArgument") {
|
|
1648
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1649
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1650
|
+
}
|
|
1651
|
+
throw err;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* Check for option flag conflicts.
|
|
1656
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1657
|
+
*
|
|
1658
|
+
* @param {Option} option
|
|
1659
|
+
* @private
|
|
1660
|
+
*/
|
|
1661
|
+
_registerOption(option) {
|
|
1662
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1663
|
+
if (matchingOption) {
|
|
1664
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1665
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1666
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1667
|
+
}
|
|
1668
|
+
this.options.push(option);
|
|
1669
|
+
}
|
|
1670
|
+
/**
|
|
1671
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1672
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1673
|
+
*
|
|
1674
|
+
* @param {Command} command
|
|
1675
|
+
* @private
|
|
1676
|
+
*/
|
|
1677
|
+
_registerCommand(command) {
|
|
1678
|
+
const knownBy = (cmd) => {
|
|
1679
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1680
|
+
};
|
|
1681
|
+
const alreadyUsed = knownBy(command).find(
|
|
1682
|
+
(name) => this._findCommand(name)
|
|
1683
|
+
);
|
|
1684
|
+
if (alreadyUsed) {
|
|
1685
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1686
|
+
const newCmd = knownBy(command).join("|");
|
|
1687
|
+
throw new Error(
|
|
1688
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1689
|
+
);
|
|
1690
|
+
}
|
|
1691
|
+
this.commands.push(command);
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Add an option.
|
|
1695
|
+
*
|
|
1696
|
+
* @param {Option} option
|
|
1697
|
+
* @return {Command} `this` command for chaining
|
|
1698
|
+
*/
|
|
1699
|
+
addOption(option) {
|
|
1700
|
+
this._registerOption(option);
|
|
1701
|
+
const oname = option.name();
|
|
1702
|
+
const name = option.attributeName();
|
|
1703
|
+
if (option.negate) {
|
|
1704
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1705
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1706
|
+
this.setOptionValueWithSource(
|
|
1707
|
+
name,
|
|
1708
|
+
option.defaultValue === void 0 ? true : option.defaultValue,
|
|
1709
|
+
"default"
|
|
1710
|
+
);
|
|
1711
|
+
}
|
|
1712
|
+
} else if (option.defaultValue !== void 0) {
|
|
1713
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1714
|
+
}
|
|
1715
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1716
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1717
|
+
val = option.presetArg;
|
|
1718
|
+
}
|
|
1719
|
+
const oldValue = this.getOptionValue(name);
|
|
1720
|
+
if (val !== null && option.parseArg) {
|
|
1721
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1722
|
+
} else if (val !== null && option.variadic) {
|
|
1723
|
+
val = option._concatValue(val, oldValue);
|
|
1724
|
+
}
|
|
1725
|
+
if (val == null) {
|
|
1726
|
+
if (option.negate) {
|
|
1727
|
+
val = false;
|
|
1728
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1729
|
+
val = true;
|
|
1730
|
+
} else {
|
|
1731
|
+
val = "";
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1735
|
+
};
|
|
1736
|
+
this.on("option:" + oname, (val) => {
|
|
1737
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1738
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1739
|
+
});
|
|
1740
|
+
if (option.envVar) {
|
|
1741
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1742
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1743
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
return this;
|
|
1747
|
+
}
|
|
1748
|
+
/**
|
|
1749
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1750
|
+
*
|
|
1751
|
+
* @return {Command} `this` command for chaining
|
|
1752
|
+
* @private
|
|
1753
|
+
*/
|
|
1754
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1755
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1756
|
+
throw new Error(
|
|
1757
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
const option = this.createOption(flags, description);
|
|
1761
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1762
|
+
if (typeof fn === "function") {
|
|
1763
|
+
option.default(defaultValue).argParser(fn);
|
|
1764
|
+
} else if (fn instanceof RegExp) {
|
|
1765
|
+
const regex = fn;
|
|
1766
|
+
fn = (val, def) => {
|
|
1767
|
+
const m = regex.exec(val);
|
|
1768
|
+
return m ? m[0] : def;
|
|
1769
|
+
};
|
|
1770
|
+
option.default(defaultValue).argParser(fn);
|
|
1771
|
+
} else {
|
|
1772
|
+
option.default(fn);
|
|
1773
|
+
}
|
|
1774
|
+
return this.addOption(option);
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1778
|
+
*
|
|
1779
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1780
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1781
|
+
*
|
|
1782
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1783
|
+
*
|
|
1784
|
+
* @example
|
|
1785
|
+
* program
|
|
1786
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1787
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1788
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1789
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1790
|
+
*
|
|
1791
|
+
* @param {string} flags
|
|
1792
|
+
* @param {string} [description]
|
|
1793
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1794
|
+
* @param {*} [defaultValue]
|
|
1795
|
+
* @return {Command} `this` command for chaining
|
|
1796
|
+
*/
|
|
1797
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1798
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1802
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1803
|
+
*
|
|
1804
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1805
|
+
*
|
|
1806
|
+
* @param {string} flags
|
|
1807
|
+
* @param {string} [description]
|
|
1808
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1809
|
+
* @param {*} [defaultValue]
|
|
1810
|
+
* @return {Command} `this` command for chaining
|
|
1811
|
+
*/
|
|
1812
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1813
|
+
return this._optionEx(
|
|
1814
|
+
{ mandatory: true },
|
|
1815
|
+
flags,
|
|
1816
|
+
description,
|
|
1817
|
+
parseArg,
|
|
1818
|
+
defaultValue
|
|
1819
|
+
);
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* Alter parsing of short flags with optional values.
|
|
1823
|
+
*
|
|
1824
|
+
* @example
|
|
1825
|
+
* // for `.option('-f,--flag [value]'):
|
|
1826
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1827
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1828
|
+
*
|
|
1829
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1830
|
+
* @return {Command} `this` command for chaining
|
|
1831
|
+
*/
|
|
1832
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1833
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1834
|
+
return this;
|
|
1835
|
+
}
|
|
1836
|
+
/**
|
|
1837
|
+
* Allow unknown options on the command line.
|
|
1838
|
+
*
|
|
1839
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1840
|
+
* @return {Command} `this` command for chaining
|
|
1841
|
+
*/
|
|
1842
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1843
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1844
|
+
return this;
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1848
|
+
*
|
|
1849
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1850
|
+
* @return {Command} `this` command for chaining
|
|
1851
|
+
*/
|
|
1852
|
+
allowExcessArguments(allowExcess = true) {
|
|
1853
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1854
|
+
return this;
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1858
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1859
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1860
|
+
*
|
|
1861
|
+
* @param {boolean} [positional]
|
|
1862
|
+
* @return {Command} `this` command for chaining
|
|
1863
|
+
*/
|
|
1864
|
+
enablePositionalOptions(positional = true) {
|
|
1865
|
+
this._enablePositionalOptions = !!positional;
|
|
1866
|
+
return this;
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1870
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1871
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1872
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1873
|
+
*
|
|
1874
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1875
|
+
* @return {Command} `this` command for chaining
|
|
1876
|
+
*/
|
|
1877
|
+
passThroughOptions(passThrough = true) {
|
|
1878
|
+
this._passThroughOptions = !!passThrough;
|
|
1879
|
+
this._checkForBrokenPassThrough();
|
|
1880
|
+
return this;
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* @private
|
|
1884
|
+
*/
|
|
1885
|
+
_checkForBrokenPassThrough() {
|
|
1886
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1887
|
+
throw new Error(
|
|
1888
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1889
|
+
);
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Whether to store option values as properties on command object,
|
|
1894
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1895
|
+
*
|
|
1896
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1897
|
+
* @return {Command} `this` command for chaining
|
|
1898
|
+
*/
|
|
1899
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1900
|
+
if (this.options.length) {
|
|
1901
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1902
|
+
}
|
|
1903
|
+
if (Object.keys(this._optionValues).length) {
|
|
1904
|
+
throw new Error(
|
|
1905
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1906
|
+
);
|
|
1907
|
+
}
|
|
1908
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1909
|
+
return this;
|
|
1910
|
+
}
|
|
1911
|
+
/**
|
|
1912
|
+
* Retrieve option value.
|
|
1913
|
+
*
|
|
1914
|
+
* @param {string} key
|
|
1915
|
+
* @return {object} value
|
|
1916
|
+
*/
|
|
1917
|
+
getOptionValue(key) {
|
|
1918
|
+
if (this._storeOptionsAsProperties) {
|
|
1919
|
+
return this[key];
|
|
1920
|
+
}
|
|
1921
|
+
return this._optionValues[key];
|
|
1922
|
+
}
|
|
1923
|
+
/**
|
|
1924
|
+
* Store option value.
|
|
1925
|
+
*
|
|
1926
|
+
* @param {string} key
|
|
1927
|
+
* @param {object} value
|
|
1928
|
+
* @return {Command} `this` command for chaining
|
|
1929
|
+
*/
|
|
1930
|
+
setOptionValue(key, value) {
|
|
1931
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Store option value and where the value came from.
|
|
1935
|
+
*
|
|
1936
|
+
* @param {string} key
|
|
1937
|
+
* @param {object} value
|
|
1938
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1939
|
+
* @return {Command} `this` command for chaining
|
|
1940
|
+
*/
|
|
1941
|
+
setOptionValueWithSource(key, value, source) {
|
|
1942
|
+
if (this._storeOptionsAsProperties) {
|
|
1943
|
+
this[key] = value;
|
|
1944
|
+
} else {
|
|
1945
|
+
this._optionValues[key] = value;
|
|
1946
|
+
}
|
|
1947
|
+
this._optionValueSources[key] = source;
|
|
1948
|
+
return this;
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Get source of option value.
|
|
1952
|
+
* Expected values are default | config | env | cli | implied
|
|
1953
|
+
*
|
|
1954
|
+
* @param {string} key
|
|
1955
|
+
* @return {string}
|
|
1956
|
+
*/
|
|
1957
|
+
getOptionValueSource(key) {
|
|
1958
|
+
return this._optionValueSources[key];
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1962
|
+
* Expected values are default | config | env | cli | implied
|
|
1963
|
+
*
|
|
1964
|
+
* @param {string} key
|
|
1965
|
+
* @return {string}
|
|
1966
|
+
*/
|
|
1967
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1968
|
+
let source;
|
|
1969
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1970
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1971
|
+
source = cmd.getOptionValueSource(key);
|
|
1972
|
+
}
|
|
1973
|
+
});
|
|
1974
|
+
return source;
|
|
1975
|
+
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Get user arguments from implied or explicit arguments.
|
|
1978
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
1979
|
+
*
|
|
1980
|
+
* @private
|
|
1981
|
+
*/
|
|
1982
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1983
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
1984
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1985
|
+
}
|
|
1986
|
+
parseOptions = parseOptions || {};
|
|
1987
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
1988
|
+
if (process2.versions?.electron) {
|
|
1989
|
+
parseOptions.from = "electron";
|
|
1990
|
+
}
|
|
1991
|
+
const execArgv = process2.execArgv ?? [];
|
|
1992
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1993
|
+
parseOptions.from = "eval";
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
if (argv === void 0) {
|
|
1997
|
+
argv = process2.argv;
|
|
1998
|
+
}
|
|
1999
|
+
this.rawArgs = argv.slice();
|
|
2000
|
+
let userArgs;
|
|
2001
|
+
switch (parseOptions.from) {
|
|
2002
|
+
case void 0:
|
|
2003
|
+
case "node":
|
|
2004
|
+
this._scriptPath = argv[1];
|
|
2005
|
+
userArgs = argv.slice(2);
|
|
2006
|
+
break;
|
|
2007
|
+
case "electron":
|
|
2008
|
+
if (process2.defaultApp) {
|
|
2009
|
+
this._scriptPath = argv[1];
|
|
2010
|
+
userArgs = argv.slice(2);
|
|
2011
|
+
} else {
|
|
2012
|
+
userArgs = argv.slice(1);
|
|
2013
|
+
}
|
|
2014
|
+
break;
|
|
2015
|
+
case "user":
|
|
2016
|
+
userArgs = argv.slice(0);
|
|
2017
|
+
break;
|
|
2018
|
+
case "eval":
|
|
2019
|
+
userArgs = argv.slice(1);
|
|
2020
|
+
break;
|
|
2021
|
+
default:
|
|
2022
|
+
throw new Error(
|
|
2023
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2024
|
+
);
|
|
2025
|
+
}
|
|
2026
|
+
if (!this._name && this._scriptPath)
|
|
2027
|
+
this.nameFromFilename(this._scriptPath);
|
|
2028
|
+
this._name = this._name || "program";
|
|
2029
|
+
return userArgs;
|
|
2030
|
+
}
|
|
2031
|
+
/**
|
|
2032
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2033
|
+
*
|
|
2034
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2035
|
+
*
|
|
2036
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2037
|
+
*
|
|
2038
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2039
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2040
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2041
|
+
* - `'user'`: just user arguments
|
|
2042
|
+
*
|
|
2043
|
+
* @example
|
|
2044
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2045
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2046
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2047
|
+
*
|
|
2048
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2049
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2050
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2051
|
+
* @return {Command} `this` command for chaining
|
|
2052
|
+
*/
|
|
2053
|
+
parse(argv, parseOptions) {
|
|
2054
|
+
this._prepareForParse();
|
|
2055
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2056
|
+
this._parseCommand([], userArgs);
|
|
2057
|
+
return this;
|
|
2058
|
+
}
|
|
2059
|
+
/**
|
|
2060
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2061
|
+
*
|
|
2062
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2063
|
+
*
|
|
2064
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2065
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2066
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2067
|
+
* - `'user'`: just user arguments
|
|
2068
|
+
*
|
|
2069
|
+
* @example
|
|
2070
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2071
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2072
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2073
|
+
*
|
|
2074
|
+
* @param {string[]} [argv]
|
|
2075
|
+
* @param {object} [parseOptions]
|
|
2076
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2077
|
+
* @return {Promise}
|
|
2078
|
+
*/
|
|
2079
|
+
async parseAsync(argv, parseOptions) {
|
|
2080
|
+
this._prepareForParse();
|
|
2081
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2082
|
+
await this._parseCommand([], userArgs);
|
|
2083
|
+
return this;
|
|
2084
|
+
}
|
|
2085
|
+
_prepareForParse() {
|
|
2086
|
+
if (this._savedState === null) {
|
|
2087
|
+
this.saveStateBeforeParse();
|
|
2088
|
+
} else {
|
|
2089
|
+
this.restoreStateBeforeParse();
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2094
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2095
|
+
*
|
|
2096
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2097
|
+
*/
|
|
2098
|
+
saveStateBeforeParse() {
|
|
2099
|
+
this._savedState = {
|
|
2100
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2101
|
+
_name: this._name,
|
|
2102
|
+
// option values before parse have default values (including false for negated options)
|
|
2103
|
+
// shallow clones
|
|
2104
|
+
_optionValues: { ...this._optionValues },
|
|
2105
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2106
|
+
};
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* Restore state before parse for calls after the first.
|
|
2110
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2111
|
+
*
|
|
2112
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2113
|
+
*/
|
|
2114
|
+
restoreStateBeforeParse() {
|
|
2115
|
+
if (this._storeOptionsAsProperties)
|
|
2116
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2117
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2118
|
+
this._name = this._savedState._name;
|
|
2119
|
+
this._scriptPath = null;
|
|
2120
|
+
this.rawArgs = [];
|
|
2121
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2122
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2123
|
+
this.args = [];
|
|
2124
|
+
this.processedArgs = [];
|
|
2125
|
+
}
|
|
2126
|
+
/**
|
|
2127
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2128
|
+
*
|
|
2129
|
+
* @param {string} executableFile
|
|
2130
|
+
* @param {string} executableDir
|
|
2131
|
+
* @param {string} subcommandName
|
|
2132
|
+
*/
|
|
2133
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2134
|
+
if (fs.existsSync(executableFile)) return;
|
|
2135
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
2136
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2137
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2138
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2139
|
+
- ${executableDirMessage}`;
|
|
2140
|
+
throw new Error(executableMissing);
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* Execute a sub-command executable.
|
|
2144
|
+
*
|
|
2145
|
+
* @private
|
|
2146
|
+
*/
|
|
2147
|
+
_executeSubCommand(subcommand, args) {
|
|
2148
|
+
args = args.slice();
|
|
2149
|
+
let launchWithNode = false;
|
|
2150
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2151
|
+
function findFile(baseDir, baseName) {
|
|
2152
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2153
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2154
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2155
|
+
const foundExt = sourceExt.find(
|
|
2156
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2157
|
+
);
|
|
2158
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2159
|
+
return void 0;
|
|
2160
|
+
}
|
|
2161
|
+
this._checkForMissingMandatoryOptions();
|
|
2162
|
+
this._checkForConflictingOptions();
|
|
2163
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2164
|
+
let executableDir = this._executableDir || "";
|
|
2165
|
+
if (this._scriptPath) {
|
|
2166
|
+
let resolvedScriptPath;
|
|
2167
|
+
try {
|
|
2168
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2169
|
+
} catch {
|
|
2170
|
+
resolvedScriptPath = this._scriptPath;
|
|
2171
|
+
}
|
|
2172
|
+
executableDir = path.resolve(
|
|
2173
|
+
path.dirname(resolvedScriptPath),
|
|
2174
|
+
executableDir
|
|
2175
|
+
);
|
|
2176
|
+
}
|
|
2177
|
+
if (executableDir) {
|
|
2178
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2179
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2180
|
+
const legacyName = path.basename(
|
|
2181
|
+
this._scriptPath,
|
|
2182
|
+
path.extname(this._scriptPath)
|
|
2183
|
+
);
|
|
2184
|
+
if (legacyName !== this._name) {
|
|
2185
|
+
localFile = findFile(
|
|
2186
|
+
executableDir,
|
|
2187
|
+
`${legacyName}-${subcommand._name}`
|
|
2188
|
+
);
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
executableFile = localFile || executableFile;
|
|
2192
|
+
}
|
|
2193
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2194
|
+
let proc;
|
|
2195
|
+
if (process2.platform !== "win32") {
|
|
2196
|
+
if (launchWithNode) {
|
|
2197
|
+
args.unshift(executableFile);
|
|
2198
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2199
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2200
|
+
} else {
|
|
2201
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2202
|
+
}
|
|
2203
|
+
} else {
|
|
2204
|
+
this._checkForMissingExecutable(
|
|
2205
|
+
executableFile,
|
|
2206
|
+
executableDir,
|
|
2207
|
+
subcommand._name
|
|
2208
|
+
);
|
|
2209
|
+
args.unshift(executableFile);
|
|
2210
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2211
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2212
|
+
}
|
|
2213
|
+
if (!proc.killed) {
|
|
2214
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2215
|
+
signals.forEach((signal) => {
|
|
2216
|
+
process2.on(signal, () => {
|
|
2217
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2218
|
+
proc.kill(signal);
|
|
2219
|
+
}
|
|
2220
|
+
});
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
const exitCallback = this._exitCallback;
|
|
2224
|
+
proc.on("close", (code) => {
|
|
2225
|
+
code = code ?? 1;
|
|
2226
|
+
if (!exitCallback) {
|
|
2227
|
+
process2.exit(code);
|
|
2228
|
+
} else {
|
|
2229
|
+
exitCallback(
|
|
2230
|
+
new CommanderError2(
|
|
2231
|
+
code,
|
|
2232
|
+
"commander.executeSubCommandAsync",
|
|
2233
|
+
"(close)"
|
|
2234
|
+
)
|
|
2235
|
+
);
|
|
2236
|
+
}
|
|
2237
|
+
});
|
|
2238
|
+
proc.on("error", (err) => {
|
|
2239
|
+
if (err.code === "ENOENT") {
|
|
2240
|
+
this._checkForMissingExecutable(
|
|
2241
|
+
executableFile,
|
|
2242
|
+
executableDir,
|
|
2243
|
+
subcommand._name
|
|
2244
|
+
);
|
|
2245
|
+
} else if (err.code === "EACCES") {
|
|
2246
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2247
|
+
}
|
|
2248
|
+
if (!exitCallback) {
|
|
2249
|
+
process2.exit(1);
|
|
2250
|
+
} else {
|
|
2251
|
+
const wrappedError = new CommanderError2(
|
|
2252
|
+
1,
|
|
2253
|
+
"commander.executeSubCommandAsync",
|
|
2254
|
+
"(error)"
|
|
2255
|
+
);
|
|
2256
|
+
wrappedError.nestedError = err;
|
|
2257
|
+
exitCallback(wrappedError);
|
|
2258
|
+
}
|
|
2259
|
+
});
|
|
2260
|
+
this.runningCommand = proc;
|
|
2261
|
+
}
|
|
2262
|
+
/**
|
|
2263
|
+
* @private
|
|
2264
|
+
*/
|
|
2265
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2266
|
+
const subCommand = this._findCommand(commandName);
|
|
2267
|
+
if (!subCommand) this.help({ error: true });
|
|
2268
|
+
subCommand._prepareForParse();
|
|
2269
|
+
let promiseChain;
|
|
2270
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2271
|
+
promiseChain,
|
|
2272
|
+
subCommand,
|
|
2273
|
+
"preSubcommand"
|
|
2274
|
+
);
|
|
2275
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2276
|
+
if (subCommand._executableHandler) {
|
|
2277
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2278
|
+
} else {
|
|
2279
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2280
|
+
}
|
|
2281
|
+
});
|
|
2282
|
+
return promiseChain;
|
|
2283
|
+
}
|
|
2284
|
+
/**
|
|
2285
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2286
|
+
* e.g. help foo
|
|
2287
|
+
*
|
|
2288
|
+
* @private
|
|
2289
|
+
*/
|
|
2290
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2291
|
+
if (!subcommandName) {
|
|
2292
|
+
this.help();
|
|
2293
|
+
}
|
|
2294
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2295
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2296
|
+
subCommand.help();
|
|
2297
|
+
}
|
|
2298
|
+
return this._dispatchSubcommand(
|
|
2299
|
+
subcommandName,
|
|
2300
|
+
[],
|
|
2301
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2302
|
+
);
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* Check this.args against expected this.registeredArguments.
|
|
2306
|
+
*
|
|
2307
|
+
* @private
|
|
2308
|
+
*/
|
|
2309
|
+
_checkNumberOfArguments() {
|
|
2310
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2311
|
+
if (arg.required && this.args[i] == null) {
|
|
2312
|
+
this.missingArgument(arg.name());
|
|
2313
|
+
}
|
|
2314
|
+
});
|
|
2315
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2316
|
+
return;
|
|
2317
|
+
}
|
|
2318
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2319
|
+
this._excessArguments(this.args);
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
/**
|
|
2323
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2324
|
+
*
|
|
2325
|
+
* @private
|
|
2326
|
+
*/
|
|
2327
|
+
_processArguments() {
|
|
2328
|
+
const myParseArg = (argument, value, previous) => {
|
|
2329
|
+
let parsedValue = value;
|
|
2330
|
+
if (value !== null && argument.parseArg) {
|
|
2331
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2332
|
+
parsedValue = this._callParseArg(
|
|
2333
|
+
argument,
|
|
2334
|
+
value,
|
|
2335
|
+
previous,
|
|
2336
|
+
invalidValueMessage
|
|
2337
|
+
);
|
|
2338
|
+
}
|
|
2339
|
+
return parsedValue;
|
|
2340
|
+
};
|
|
2341
|
+
this._checkNumberOfArguments();
|
|
2342
|
+
const processedArgs = [];
|
|
2343
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2344
|
+
let value = declaredArg.defaultValue;
|
|
2345
|
+
if (declaredArg.variadic) {
|
|
2346
|
+
if (index < this.args.length) {
|
|
2347
|
+
value = this.args.slice(index);
|
|
2348
|
+
if (declaredArg.parseArg) {
|
|
2349
|
+
value = value.reduce((processed, v) => {
|
|
2350
|
+
return myParseArg(declaredArg, v, processed);
|
|
2351
|
+
}, declaredArg.defaultValue);
|
|
2352
|
+
}
|
|
2353
|
+
} else if (value === void 0) {
|
|
2354
|
+
value = [];
|
|
2355
|
+
}
|
|
2356
|
+
} else if (index < this.args.length) {
|
|
2357
|
+
value = this.args[index];
|
|
2358
|
+
if (declaredArg.parseArg) {
|
|
2359
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
processedArgs[index] = value;
|
|
2363
|
+
});
|
|
2364
|
+
this.processedArgs = processedArgs;
|
|
2365
|
+
}
|
|
2366
|
+
/**
|
|
2367
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2368
|
+
*
|
|
2369
|
+
* @param {(Promise|undefined)} promise
|
|
2370
|
+
* @param {Function} fn
|
|
2371
|
+
* @return {(Promise|undefined)}
|
|
2372
|
+
* @private
|
|
2373
|
+
*/
|
|
2374
|
+
_chainOrCall(promise, fn) {
|
|
2375
|
+
if (promise && promise.then && typeof promise.then === "function") {
|
|
2376
|
+
return promise.then(() => fn());
|
|
2377
|
+
}
|
|
2378
|
+
return fn();
|
|
2379
|
+
}
|
|
2380
|
+
/**
|
|
2381
|
+
*
|
|
2382
|
+
* @param {(Promise|undefined)} promise
|
|
2383
|
+
* @param {string} event
|
|
2384
|
+
* @return {(Promise|undefined)}
|
|
2385
|
+
* @private
|
|
2386
|
+
*/
|
|
2387
|
+
_chainOrCallHooks(promise, event) {
|
|
2388
|
+
let result = promise;
|
|
2389
|
+
const hooks = [];
|
|
2390
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2391
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2392
|
+
hooks.push({ hookedCommand, callback });
|
|
2393
|
+
});
|
|
2394
|
+
});
|
|
2395
|
+
if (event === "postAction") {
|
|
2396
|
+
hooks.reverse();
|
|
2397
|
+
}
|
|
2398
|
+
hooks.forEach((hookDetail) => {
|
|
2399
|
+
result = this._chainOrCall(result, () => {
|
|
2400
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2401
|
+
});
|
|
2402
|
+
});
|
|
2403
|
+
return result;
|
|
2404
|
+
}
|
|
2405
|
+
/**
|
|
2406
|
+
*
|
|
2407
|
+
* @param {(Promise|undefined)} promise
|
|
2408
|
+
* @param {Command} subCommand
|
|
2409
|
+
* @param {string} event
|
|
2410
|
+
* @return {(Promise|undefined)}
|
|
2411
|
+
* @private
|
|
2412
|
+
*/
|
|
2413
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2414
|
+
let result = promise;
|
|
2415
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2416
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2417
|
+
result = this._chainOrCall(result, () => {
|
|
2418
|
+
return hook(this, subCommand);
|
|
2419
|
+
});
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
return result;
|
|
2423
|
+
}
|
|
2424
|
+
/**
|
|
2425
|
+
* Process arguments in context of this command.
|
|
2426
|
+
* Returns action result, in case it is a promise.
|
|
2427
|
+
*
|
|
2428
|
+
* @private
|
|
2429
|
+
*/
|
|
2430
|
+
_parseCommand(operands, unknown) {
|
|
2431
|
+
const parsed = this.parseOptions(unknown);
|
|
2432
|
+
this._parseOptionsEnv();
|
|
2433
|
+
this._parseOptionsImplied();
|
|
2434
|
+
operands = operands.concat(parsed.operands);
|
|
2435
|
+
unknown = parsed.unknown;
|
|
2436
|
+
this.args = operands.concat(unknown);
|
|
2437
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2438
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2439
|
+
}
|
|
2440
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2441
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2442
|
+
}
|
|
2443
|
+
if (this._defaultCommandName) {
|
|
2444
|
+
this._outputHelpIfRequested(unknown);
|
|
2445
|
+
return this._dispatchSubcommand(
|
|
2446
|
+
this._defaultCommandName,
|
|
2447
|
+
operands,
|
|
2448
|
+
unknown
|
|
2449
|
+
);
|
|
2450
|
+
}
|
|
2451
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2452
|
+
this.help({ error: true });
|
|
2453
|
+
}
|
|
2454
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2455
|
+
this._checkForMissingMandatoryOptions();
|
|
2456
|
+
this._checkForConflictingOptions();
|
|
2457
|
+
const checkForUnknownOptions = () => {
|
|
2458
|
+
if (parsed.unknown.length > 0) {
|
|
2459
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2460
|
+
}
|
|
2461
|
+
};
|
|
2462
|
+
const commandEvent = `command:${this.name()}`;
|
|
2463
|
+
if (this._actionHandler) {
|
|
2464
|
+
checkForUnknownOptions();
|
|
2465
|
+
this._processArguments();
|
|
2466
|
+
let promiseChain;
|
|
2467
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2468
|
+
promiseChain = this._chainOrCall(
|
|
2469
|
+
promiseChain,
|
|
2470
|
+
() => this._actionHandler(this.processedArgs)
|
|
2471
|
+
);
|
|
2472
|
+
if (this.parent) {
|
|
2473
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2474
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2478
|
+
return promiseChain;
|
|
2479
|
+
}
|
|
2480
|
+
if (this.parent && this.parent.listenerCount(commandEvent)) {
|
|
2481
|
+
checkForUnknownOptions();
|
|
2482
|
+
this._processArguments();
|
|
2483
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2484
|
+
} else if (operands.length) {
|
|
2485
|
+
if (this._findCommand("*")) {
|
|
2486
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2487
|
+
}
|
|
2488
|
+
if (this.listenerCount("command:*")) {
|
|
2489
|
+
this.emit("command:*", operands, unknown);
|
|
2490
|
+
} else if (this.commands.length) {
|
|
2491
|
+
this.unknownCommand();
|
|
2492
|
+
} else {
|
|
2493
|
+
checkForUnknownOptions();
|
|
2494
|
+
this._processArguments();
|
|
2495
|
+
}
|
|
2496
|
+
} else if (this.commands.length) {
|
|
2497
|
+
checkForUnknownOptions();
|
|
2498
|
+
this.help({ error: true });
|
|
2499
|
+
} else {
|
|
2500
|
+
checkForUnknownOptions();
|
|
2501
|
+
this._processArguments();
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Find matching command.
|
|
2506
|
+
*
|
|
2507
|
+
* @private
|
|
2508
|
+
* @return {Command | undefined}
|
|
2509
|
+
*/
|
|
2510
|
+
_findCommand(name) {
|
|
2511
|
+
if (!name) return void 0;
|
|
2512
|
+
return this.commands.find(
|
|
2513
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2514
|
+
);
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Return an option matching `arg` if any.
|
|
2518
|
+
*
|
|
2519
|
+
* @param {string} arg
|
|
2520
|
+
* @return {Option}
|
|
2521
|
+
* @package
|
|
2522
|
+
*/
|
|
2523
|
+
_findOption(arg) {
|
|
2524
|
+
return this.options.find((option) => option.is(arg));
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2528
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2529
|
+
*
|
|
2530
|
+
* @private
|
|
2531
|
+
*/
|
|
2532
|
+
_checkForMissingMandatoryOptions() {
|
|
2533
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2534
|
+
cmd.options.forEach((anOption) => {
|
|
2535
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2536
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2537
|
+
}
|
|
2538
|
+
});
|
|
2539
|
+
});
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Display an error message if conflicting options are used together in this.
|
|
2543
|
+
*
|
|
2544
|
+
* @private
|
|
2545
|
+
*/
|
|
2546
|
+
_checkForConflictingLocalOptions() {
|
|
2547
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2548
|
+
const optionKey = option.attributeName();
|
|
2549
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2550
|
+
return false;
|
|
2551
|
+
}
|
|
2552
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2553
|
+
});
|
|
2554
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2555
|
+
(option) => option.conflictsWith.length > 0
|
|
2556
|
+
);
|
|
2557
|
+
optionsWithConflicting.forEach((option) => {
|
|
2558
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2559
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2560
|
+
);
|
|
2561
|
+
if (conflictingAndDefined) {
|
|
2562
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2563
|
+
}
|
|
2564
|
+
});
|
|
2565
|
+
}
|
|
2566
|
+
/**
|
|
2567
|
+
* Display an error message if conflicting options are used together.
|
|
2568
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2569
|
+
*
|
|
2570
|
+
* @private
|
|
2571
|
+
*/
|
|
2572
|
+
_checkForConflictingOptions() {
|
|
2573
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2574
|
+
cmd._checkForConflictingLocalOptions();
|
|
2575
|
+
});
|
|
2576
|
+
}
|
|
2577
|
+
/**
|
|
2578
|
+
* Parse options from `argv` removing known options,
|
|
2579
|
+
* and return argv split into operands and unknown arguments.
|
|
2580
|
+
*
|
|
2581
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2582
|
+
*
|
|
2583
|
+
* Examples:
|
|
2584
|
+
*
|
|
2585
|
+
* argv => operands, unknown
|
|
2586
|
+
* --known kkk op => [op], []
|
|
2587
|
+
* op --known kkk => [op], []
|
|
2588
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2589
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2590
|
+
*
|
|
2591
|
+
* @param {string[]} argv
|
|
2592
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2593
|
+
*/
|
|
2594
|
+
parseOptions(argv) {
|
|
2595
|
+
const operands = [];
|
|
2596
|
+
const unknown = [];
|
|
2597
|
+
let dest = operands;
|
|
2598
|
+
const args = argv.slice();
|
|
2599
|
+
function maybeOption(arg) {
|
|
2600
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2601
|
+
}
|
|
2602
|
+
let activeVariadicOption = null;
|
|
2603
|
+
while (args.length) {
|
|
2604
|
+
const arg = args.shift();
|
|
2605
|
+
if (arg === "--") {
|
|
2606
|
+
if (dest === unknown) dest.push(arg);
|
|
2607
|
+
dest.push(...args);
|
|
2608
|
+
break;
|
|
2609
|
+
}
|
|
2610
|
+
if (activeVariadicOption && !maybeOption(arg)) {
|
|
2611
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2612
|
+
continue;
|
|
2613
|
+
}
|
|
2614
|
+
activeVariadicOption = null;
|
|
2615
|
+
if (maybeOption(arg)) {
|
|
2616
|
+
const option = this._findOption(arg);
|
|
2617
|
+
if (option) {
|
|
2618
|
+
if (option.required) {
|
|
2619
|
+
const value = args.shift();
|
|
2620
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2621
|
+
this.emit(`option:${option.name()}`, value);
|
|
2622
|
+
} else if (option.optional) {
|
|
2623
|
+
let value = null;
|
|
2624
|
+
if (args.length > 0 && !maybeOption(args[0])) {
|
|
2625
|
+
value = args.shift();
|
|
2626
|
+
}
|
|
2627
|
+
this.emit(`option:${option.name()}`, value);
|
|
2628
|
+
} else {
|
|
2629
|
+
this.emit(`option:${option.name()}`);
|
|
2630
|
+
}
|
|
2631
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2632
|
+
continue;
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2636
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2637
|
+
if (option) {
|
|
2638
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2639
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2640
|
+
} else {
|
|
2641
|
+
this.emit(`option:${option.name()}`);
|
|
2642
|
+
args.unshift(`-${arg.slice(2)}`);
|
|
2643
|
+
}
|
|
2644
|
+
continue;
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2648
|
+
const index = arg.indexOf("=");
|
|
2649
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2650
|
+
if (option && (option.required || option.optional)) {
|
|
2651
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2652
|
+
continue;
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
if (maybeOption(arg)) {
|
|
2656
|
+
dest = unknown;
|
|
2657
|
+
}
|
|
2658
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2659
|
+
if (this._findCommand(arg)) {
|
|
2660
|
+
operands.push(arg);
|
|
2661
|
+
if (args.length > 0) unknown.push(...args);
|
|
2662
|
+
break;
|
|
2663
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2664
|
+
operands.push(arg);
|
|
2665
|
+
if (args.length > 0) operands.push(...args);
|
|
2666
|
+
break;
|
|
2667
|
+
} else if (this._defaultCommandName) {
|
|
2668
|
+
unknown.push(arg);
|
|
2669
|
+
if (args.length > 0) unknown.push(...args);
|
|
2670
|
+
break;
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
if (this._passThroughOptions) {
|
|
2674
|
+
dest.push(arg);
|
|
2675
|
+
if (args.length > 0) dest.push(...args);
|
|
2676
|
+
break;
|
|
2677
|
+
}
|
|
2678
|
+
dest.push(arg);
|
|
2679
|
+
}
|
|
2680
|
+
return { operands, unknown };
|
|
2681
|
+
}
|
|
2682
|
+
/**
|
|
2683
|
+
* Return an object containing local option values as key-value pairs.
|
|
2684
|
+
*
|
|
2685
|
+
* @return {object}
|
|
2686
|
+
*/
|
|
2687
|
+
opts() {
|
|
2688
|
+
if (this._storeOptionsAsProperties) {
|
|
2689
|
+
const result = {};
|
|
2690
|
+
const len = this.options.length;
|
|
2691
|
+
for (let i = 0; i < len; i++) {
|
|
2692
|
+
const key = this.options[i].attributeName();
|
|
2693
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2694
|
+
}
|
|
2695
|
+
return result;
|
|
2696
|
+
}
|
|
2697
|
+
return this._optionValues;
|
|
2698
|
+
}
|
|
2699
|
+
/**
|
|
2700
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2701
|
+
*
|
|
2702
|
+
* @return {object}
|
|
2703
|
+
*/
|
|
2704
|
+
optsWithGlobals() {
|
|
2705
|
+
return this._getCommandAndAncestors().reduce(
|
|
2706
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2707
|
+
{}
|
|
2708
|
+
);
|
|
2709
|
+
}
|
|
2710
|
+
/**
|
|
2711
|
+
* Display error message and exit (or call exitOverride).
|
|
2712
|
+
*
|
|
2713
|
+
* @param {string} message
|
|
2714
|
+
* @param {object} [errorOptions]
|
|
2715
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2716
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2717
|
+
*/
|
|
2718
|
+
error(message, errorOptions) {
|
|
2719
|
+
this._outputConfiguration.outputError(
|
|
2720
|
+
`${message}
|
|
2721
|
+
`,
|
|
2722
|
+
this._outputConfiguration.writeErr
|
|
2723
|
+
);
|
|
2724
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2725
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2726
|
+
`);
|
|
2727
|
+
} else if (this._showHelpAfterError) {
|
|
2728
|
+
this._outputConfiguration.writeErr("\n");
|
|
2729
|
+
this.outputHelp({ error: true });
|
|
2730
|
+
}
|
|
2731
|
+
const config = errorOptions || {};
|
|
2732
|
+
const exitCode = config.exitCode || 1;
|
|
2733
|
+
const code = config.code || "commander.error";
|
|
2734
|
+
this._exit(exitCode, code, message);
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* Apply any option related environment variables, if option does
|
|
2738
|
+
* not have a value from cli or client code.
|
|
2739
|
+
*
|
|
2740
|
+
* @private
|
|
2741
|
+
*/
|
|
2742
|
+
_parseOptionsEnv() {
|
|
2743
|
+
this.options.forEach((option) => {
|
|
2744
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2745
|
+
const optionKey = option.attributeName();
|
|
2746
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2747
|
+
this.getOptionValueSource(optionKey)
|
|
2748
|
+
)) {
|
|
2749
|
+
if (option.required || option.optional) {
|
|
2750
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2751
|
+
} else {
|
|
2752
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
});
|
|
2757
|
+
}
|
|
2758
|
+
/**
|
|
2759
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2760
|
+
*
|
|
2761
|
+
* @private
|
|
2762
|
+
*/
|
|
2763
|
+
_parseOptionsImplied() {
|
|
2764
|
+
const dualHelper = new DualOptions(this.options);
|
|
2765
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2766
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2767
|
+
};
|
|
2768
|
+
this.options.filter(
|
|
2769
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2770
|
+
this.getOptionValue(option.attributeName()),
|
|
2771
|
+
option
|
|
2772
|
+
)
|
|
2773
|
+
).forEach((option) => {
|
|
2774
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2775
|
+
this.setOptionValueWithSource(
|
|
2776
|
+
impliedKey,
|
|
2777
|
+
option.implied[impliedKey],
|
|
2778
|
+
"implied"
|
|
2779
|
+
);
|
|
2780
|
+
});
|
|
2781
|
+
});
|
|
2782
|
+
}
|
|
2783
|
+
/**
|
|
2784
|
+
* Argument `name` is missing.
|
|
2785
|
+
*
|
|
2786
|
+
* @param {string} name
|
|
2787
|
+
* @private
|
|
2788
|
+
*/
|
|
2789
|
+
missingArgument(name) {
|
|
2790
|
+
const message = `error: missing required argument '${name}'`;
|
|
2791
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2792
|
+
}
|
|
2793
|
+
/**
|
|
2794
|
+
* `Option` is missing an argument.
|
|
2795
|
+
*
|
|
2796
|
+
* @param {Option} option
|
|
2797
|
+
* @private
|
|
2798
|
+
*/
|
|
2799
|
+
optionMissingArgument(option) {
|
|
2800
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2801
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2802
|
+
}
|
|
2803
|
+
/**
|
|
2804
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2805
|
+
*
|
|
2806
|
+
* @param {Option} option
|
|
2807
|
+
* @private
|
|
2808
|
+
*/
|
|
2809
|
+
missingMandatoryOptionValue(option) {
|
|
2810
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2811
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2812
|
+
}
|
|
2813
|
+
/**
|
|
2814
|
+
* `Option` conflicts with another option.
|
|
2815
|
+
*
|
|
2816
|
+
* @param {Option} option
|
|
2817
|
+
* @param {Option} conflictingOption
|
|
2818
|
+
* @private
|
|
2819
|
+
*/
|
|
2820
|
+
_conflictingOption(option, conflictingOption) {
|
|
2821
|
+
const findBestOptionFromValue = (option2) => {
|
|
2822
|
+
const optionKey = option2.attributeName();
|
|
2823
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2824
|
+
const negativeOption = this.options.find(
|
|
2825
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2826
|
+
);
|
|
2827
|
+
const positiveOption = this.options.find(
|
|
2828
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2829
|
+
);
|
|
2830
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2831
|
+
return negativeOption;
|
|
2832
|
+
}
|
|
2833
|
+
return positiveOption || option2;
|
|
2834
|
+
};
|
|
2835
|
+
const getErrorMessage = (option2) => {
|
|
2836
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2837
|
+
const optionKey = bestOption.attributeName();
|
|
2838
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2839
|
+
if (source === "env") {
|
|
2840
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2841
|
+
}
|
|
2842
|
+
return `option '${bestOption.flags}'`;
|
|
2843
|
+
};
|
|
2844
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2845
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2846
|
+
}
|
|
2847
|
+
/**
|
|
2848
|
+
* Unknown option `flag`.
|
|
2849
|
+
*
|
|
2850
|
+
* @param {string} flag
|
|
2851
|
+
* @private
|
|
2852
|
+
*/
|
|
2853
|
+
unknownOption(flag) {
|
|
2854
|
+
if (this._allowUnknownOption) return;
|
|
2855
|
+
let suggestion = "";
|
|
2856
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2857
|
+
let candidateFlags = [];
|
|
2858
|
+
let command = this;
|
|
2859
|
+
do {
|
|
2860
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2861
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2862
|
+
command = command.parent;
|
|
2863
|
+
} while (command && !command._enablePositionalOptions);
|
|
2864
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2865
|
+
}
|
|
2866
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2867
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* Excess arguments, more than expected.
|
|
2871
|
+
*
|
|
2872
|
+
* @param {string[]} receivedArgs
|
|
2873
|
+
* @private
|
|
2874
|
+
*/
|
|
2875
|
+
_excessArguments(receivedArgs) {
|
|
2876
|
+
if (this._allowExcessArguments) return;
|
|
2877
|
+
const expected = this.registeredArguments.length;
|
|
2878
|
+
const s = expected === 1 ? "" : "s";
|
|
2879
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2880
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2881
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2882
|
+
}
|
|
2883
|
+
/**
|
|
2884
|
+
* Unknown command.
|
|
2885
|
+
*
|
|
2886
|
+
* @private
|
|
2887
|
+
*/
|
|
2888
|
+
unknownCommand() {
|
|
2889
|
+
const unknownName = this.args[0];
|
|
2890
|
+
let suggestion = "";
|
|
2891
|
+
if (this._showSuggestionAfterError) {
|
|
2892
|
+
const candidateNames = [];
|
|
2893
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2894
|
+
candidateNames.push(command.name());
|
|
2895
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2896
|
+
});
|
|
2897
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2898
|
+
}
|
|
2899
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2900
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2901
|
+
}
|
|
2902
|
+
/**
|
|
2903
|
+
* Get or set the program version.
|
|
2904
|
+
*
|
|
2905
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2906
|
+
*
|
|
2907
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2908
|
+
*
|
|
2909
|
+
* @param {string} [str]
|
|
2910
|
+
* @param {string} [flags]
|
|
2911
|
+
* @param {string} [description]
|
|
2912
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2913
|
+
*/
|
|
2914
|
+
version(str, flags, description) {
|
|
2915
|
+
if (str === void 0) return this._version;
|
|
2916
|
+
this._version = str;
|
|
2917
|
+
flags = flags || "-V, --version";
|
|
2918
|
+
description = description || "output the version number";
|
|
2919
|
+
const versionOption = this.createOption(flags, description);
|
|
2920
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2921
|
+
this._registerOption(versionOption);
|
|
2922
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2923
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2924
|
+
`);
|
|
2925
|
+
this._exit(0, "commander.version", str);
|
|
2926
|
+
});
|
|
2927
|
+
return this;
|
|
2928
|
+
}
|
|
2929
|
+
/**
|
|
2930
|
+
* Set the description.
|
|
2931
|
+
*
|
|
2932
|
+
* @param {string} [str]
|
|
2933
|
+
* @param {object} [argsDescription]
|
|
2934
|
+
* @return {(string|Command)}
|
|
2935
|
+
*/
|
|
2936
|
+
description(str, argsDescription) {
|
|
2937
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2938
|
+
return this._description;
|
|
2939
|
+
this._description = str;
|
|
2940
|
+
if (argsDescription) {
|
|
2941
|
+
this._argsDescription = argsDescription;
|
|
2942
|
+
}
|
|
2943
|
+
return this;
|
|
2944
|
+
}
|
|
2945
|
+
/**
|
|
2946
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2947
|
+
*
|
|
2948
|
+
* @param {string} [str]
|
|
2949
|
+
* @return {(string|Command)}
|
|
2950
|
+
*/
|
|
2951
|
+
summary(str) {
|
|
2952
|
+
if (str === void 0) return this._summary;
|
|
2953
|
+
this._summary = str;
|
|
2954
|
+
return this;
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Set an alias for the command.
|
|
2958
|
+
*
|
|
2959
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
2960
|
+
*
|
|
2961
|
+
* @param {string} [alias]
|
|
2962
|
+
* @return {(string|Command)}
|
|
2963
|
+
*/
|
|
2964
|
+
alias(alias) {
|
|
2965
|
+
if (alias === void 0) return this._aliases[0];
|
|
2966
|
+
let command = this;
|
|
2967
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
2968
|
+
command = this.commands[this.commands.length - 1];
|
|
2969
|
+
}
|
|
2970
|
+
if (alias === command._name)
|
|
2971
|
+
throw new Error("Command alias can't be the same as its name");
|
|
2972
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
2973
|
+
if (matchingCommand) {
|
|
2974
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
2975
|
+
throw new Error(
|
|
2976
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
2977
|
+
);
|
|
2978
|
+
}
|
|
2979
|
+
command._aliases.push(alias);
|
|
2980
|
+
return this;
|
|
2981
|
+
}
|
|
2982
|
+
/**
|
|
2983
|
+
* Set aliases for the command.
|
|
2984
|
+
*
|
|
2985
|
+
* Only the first alias is shown in the auto-generated help.
|
|
2986
|
+
*
|
|
2987
|
+
* @param {string[]} [aliases]
|
|
2988
|
+
* @return {(string[]|Command)}
|
|
2989
|
+
*/
|
|
2990
|
+
aliases(aliases) {
|
|
2991
|
+
if (aliases === void 0) return this._aliases;
|
|
2992
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
2993
|
+
return this;
|
|
2994
|
+
}
|
|
2995
|
+
/**
|
|
2996
|
+
* Set / get the command usage `str`.
|
|
2997
|
+
*
|
|
2998
|
+
* @param {string} [str]
|
|
2999
|
+
* @return {(string|Command)}
|
|
3000
|
+
*/
|
|
3001
|
+
usage(str) {
|
|
3002
|
+
if (str === void 0) {
|
|
3003
|
+
if (this._usage) return this._usage;
|
|
3004
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3005
|
+
return humanReadableArgName(arg);
|
|
3006
|
+
});
|
|
3007
|
+
return [].concat(
|
|
3008
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3009
|
+
this.commands.length ? "[command]" : [],
|
|
3010
|
+
this.registeredArguments.length ? args : []
|
|
3011
|
+
).join(" ");
|
|
3012
|
+
}
|
|
3013
|
+
this._usage = str;
|
|
3014
|
+
return this;
|
|
3015
|
+
}
|
|
3016
|
+
/**
|
|
3017
|
+
* Get or set the name of the command.
|
|
3018
|
+
*
|
|
3019
|
+
* @param {string} [str]
|
|
3020
|
+
* @return {(string|Command)}
|
|
3021
|
+
*/
|
|
3022
|
+
name(str) {
|
|
3023
|
+
if (str === void 0) return this._name;
|
|
3024
|
+
this._name = str;
|
|
3025
|
+
return this;
|
|
3026
|
+
}
|
|
3027
|
+
/**
|
|
3028
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3029
|
+
* or require.main.filename, or __filename.
|
|
3030
|
+
*
|
|
3031
|
+
* (Used internally and public although not documented in README.)
|
|
3032
|
+
*
|
|
3033
|
+
* @example
|
|
3034
|
+
* program.nameFromFilename(require.main.filename);
|
|
3035
|
+
*
|
|
3036
|
+
* @param {string} filename
|
|
3037
|
+
* @return {Command}
|
|
3038
|
+
*/
|
|
3039
|
+
nameFromFilename(filename) {
|
|
3040
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3041
|
+
return this;
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3045
|
+
*
|
|
3046
|
+
* @example
|
|
3047
|
+
* program.executableDir(__dirname);
|
|
3048
|
+
* // or
|
|
3049
|
+
* program.executableDir('subcommands');
|
|
3050
|
+
*
|
|
3051
|
+
* @param {string} [path]
|
|
3052
|
+
* @return {(string|null|Command)}
|
|
3053
|
+
*/
|
|
3054
|
+
executableDir(path2) {
|
|
3055
|
+
if (path2 === void 0) return this._executableDir;
|
|
3056
|
+
this._executableDir = path2;
|
|
3057
|
+
return this;
|
|
3058
|
+
}
|
|
3059
|
+
/**
|
|
3060
|
+
* Return program help documentation.
|
|
3061
|
+
*
|
|
3062
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3063
|
+
* @return {string}
|
|
3064
|
+
*/
|
|
3065
|
+
helpInformation(contextOptions) {
|
|
3066
|
+
const helper = this.createHelp();
|
|
3067
|
+
const context = this._getOutputContext(contextOptions);
|
|
3068
|
+
helper.prepareContext({
|
|
3069
|
+
error: context.error,
|
|
3070
|
+
helpWidth: context.helpWidth,
|
|
3071
|
+
outputHasColors: context.hasColors
|
|
3072
|
+
});
|
|
3073
|
+
const text = helper.formatHelp(this, helper);
|
|
3074
|
+
if (context.hasColors) return text;
|
|
3075
|
+
return this._outputConfiguration.stripColor(text);
|
|
3076
|
+
}
|
|
3077
|
+
/**
|
|
3078
|
+
* @typedef HelpContext
|
|
3079
|
+
* @type {object}
|
|
3080
|
+
* @property {boolean} error
|
|
3081
|
+
* @property {number} helpWidth
|
|
3082
|
+
* @property {boolean} hasColors
|
|
3083
|
+
* @property {function} write - includes stripColor if needed
|
|
3084
|
+
*
|
|
3085
|
+
* @returns {HelpContext}
|
|
3086
|
+
* @private
|
|
3087
|
+
*/
|
|
3088
|
+
_getOutputContext(contextOptions) {
|
|
3089
|
+
contextOptions = contextOptions || {};
|
|
3090
|
+
const error = !!contextOptions.error;
|
|
3091
|
+
let baseWrite;
|
|
3092
|
+
let hasColors;
|
|
3093
|
+
let helpWidth;
|
|
3094
|
+
if (error) {
|
|
3095
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3096
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3097
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3098
|
+
} else {
|
|
3099
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3100
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3101
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3102
|
+
}
|
|
3103
|
+
const write = (str) => {
|
|
3104
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3105
|
+
return baseWrite(str);
|
|
3106
|
+
};
|
|
3107
|
+
return { error, write, hasColors, helpWidth };
|
|
3108
|
+
}
|
|
3109
|
+
/**
|
|
3110
|
+
* Output help information for this command.
|
|
3111
|
+
*
|
|
3112
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3113
|
+
*
|
|
3114
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3115
|
+
*/
|
|
3116
|
+
outputHelp(contextOptions) {
|
|
3117
|
+
let deprecatedCallback;
|
|
3118
|
+
if (typeof contextOptions === "function") {
|
|
3119
|
+
deprecatedCallback = contextOptions;
|
|
3120
|
+
contextOptions = void 0;
|
|
3121
|
+
}
|
|
3122
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3123
|
+
const eventContext = {
|
|
3124
|
+
error: outputContext.error,
|
|
3125
|
+
write: outputContext.write,
|
|
3126
|
+
command: this
|
|
3127
|
+
};
|
|
3128
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3129
|
+
this.emit("beforeHelp", eventContext);
|
|
3130
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3131
|
+
if (deprecatedCallback) {
|
|
3132
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3133
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3134
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
outputContext.write(helpInformation);
|
|
3138
|
+
if (this._getHelpOption()?.long) {
|
|
3139
|
+
this.emit(this._getHelpOption().long);
|
|
3140
|
+
}
|
|
3141
|
+
this.emit("afterHelp", eventContext);
|
|
3142
|
+
this._getCommandAndAncestors().forEach(
|
|
3143
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3144
|
+
);
|
|
3145
|
+
}
|
|
3146
|
+
/**
|
|
3147
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3148
|
+
* Pass in false to disable the built-in help option.
|
|
3149
|
+
*
|
|
3150
|
+
* @example
|
|
3151
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3152
|
+
* program.helpOption(false); // disable
|
|
3153
|
+
*
|
|
3154
|
+
* @param {(string | boolean)} flags
|
|
3155
|
+
* @param {string} [description]
|
|
3156
|
+
* @return {Command} `this` command for chaining
|
|
3157
|
+
*/
|
|
3158
|
+
helpOption(flags, description) {
|
|
3159
|
+
if (typeof flags === "boolean") {
|
|
3160
|
+
if (flags) {
|
|
3161
|
+
this._helpOption = this._helpOption ?? void 0;
|
|
3162
|
+
} else {
|
|
3163
|
+
this._helpOption = null;
|
|
3164
|
+
}
|
|
3165
|
+
return this;
|
|
3166
|
+
}
|
|
3167
|
+
flags = flags ?? "-h, --help";
|
|
3168
|
+
description = description ?? "display help for command";
|
|
3169
|
+
this._helpOption = this.createOption(flags, description);
|
|
3170
|
+
return this;
|
|
3171
|
+
}
|
|
3172
|
+
/**
|
|
3173
|
+
* Lazy create help option.
|
|
3174
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3175
|
+
*
|
|
3176
|
+
* @returns {(Option | null)} the help option
|
|
3177
|
+
* @package
|
|
3178
|
+
*/
|
|
3179
|
+
_getHelpOption() {
|
|
3180
|
+
if (this._helpOption === void 0) {
|
|
3181
|
+
this.helpOption(void 0, void 0);
|
|
3182
|
+
}
|
|
3183
|
+
return this._helpOption;
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Supply your own option to use for the built-in help option.
|
|
3187
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3188
|
+
*
|
|
3189
|
+
* @param {Option} option
|
|
3190
|
+
* @return {Command} `this` command for chaining
|
|
3191
|
+
*/
|
|
3192
|
+
addHelpOption(option) {
|
|
3193
|
+
this._helpOption = option;
|
|
3194
|
+
return this;
|
|
3195
|
+
}
|
|
3196
|
+
/**
|
|
3197
|
+
* Output help information and exit.
|
|
3198
|
+
*
|
|
3199
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3200
|
+
*
|
|
3201
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3202
|
+
*/
|
|
3203
|
+
help(contextOptions) {
|
|
3204
|
+
this.outputHelp(contextOptions);
|
|
3205
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3206
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3207
|
+
exitCode = 1;
|
|
3208
|
+
}
|
|
3209
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3210
|
+
}
|
|
3211
|
+
/**
|
|
3212
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3213
|
+
* @typedef HelpTextEventContext
|
|
3214
|
+
* @type {object}
|
|
3215
|
+
* @property {boolean} error
|
|
3216
|
+
* @property {Command} command
|
|
3217
|
+
* @property {function} write
|
|
3218
|
+
*/
|
|
3219
|
+
/**
|
|
3220
|
+
* Add additional text to be displayed with the built-in help.
|
|
3221
|
+
*
|
|
3222
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3223
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3224
|
+
*
|
|
3225
|
+
* @param {string} position - before or after built-in help
|
|
3226
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3227
|
+
* @return {Command} `this` command for chaining
|
|
3228
|
+
*/
|
|
3229
|
+
addHelpText(position, text) {
|
|
3230
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3231
|
+
if (!allowedValues.includes(position)) {
|
|
3232
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3233
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3234
|
+
}
|
|
3235
|
+
const helpEvent = `${position}Help`;
|
|
3236
|
+
this.on(helpEvent, (context) => {
|
|
3237
|
+
let helpStr;
|
|
3238
|
+
if (typeof text === "function") {
|
|
3239
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3240
|
+
} else {
|
|
3241
|
+
helpStr = text;
|
|
3242
|
+
}
|
|
3243
|
+
if (helpStr) {
|
|
3244
|
+
context.write(`${helpStr}
|
|
3245
|
+
`);
|
|
3246
|
+
}
|
|
3247
|
+
});
|
|
3248
|
+
return this;
|
|
3249
|
+
}
|
|
3250
|
+
/**
|
|
3251
|
+
* Output help information if help flags specified
|
|
3252
|
+
*
|
|
3253
|
+
* @param {Array} args - array of options to search for help flags
|
|
3254
|
+
* @private
|
|
3255
|
+
*/
|
|
3256
|
+
_outputHelpIfRequested(args) {
|
|
3257
|
+
const helpOption = this._getHelpOption();
|
|
3258
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3259
|
+
if (helpRequested) {
|
|
3260
|
+
this.outputHelp();
|
|
3261
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3262
|
+
}
|
|
3263
|
+
}
|
|
3264
|
+
};
|
|
3265
|
+
function incrementNodeInspectorPort(args) {
|
|
3266
|
+
return args.map((arg) => {
|
|
3267
|
+
if (!arg.startsWith("--inspect")) {
|
|
3268
|
+
return arg;
|
|
3269
|
+
}
|
|
3270
|
+
let debugOption;
|
|
3271
|
+
let debugHost = "127.0.0.1";
|
|
3272
|
+
let debugPort = "9229";
|
|
3273
|
+
let match;
|
|
3274
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3275
|
+
debugOption = match[1];
|
|
3276
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3277
|
+
debugOption = match[1];
|
|
3278
|
+
if (/^\d+$/.test(match[3])) {
|
|
3279
|
+
debugPort = match[3];
|
|
3280
|
+
} else {
|
|
3281
|
+
debugHost = match[3];
|
|
3282
|
+
}
|
|
3283
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3284
|
+
debugOption = match[1];
|
|
3285
|
+
debugHost = match[3];
|
|
3286
|
+
debugPort = match[4];
|
|
3287
|
+
}
|
|
3288
|
+
if (debugOption && debugPort !== "0") {
|
|
3289
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3290
|
+
}
|
|
3291
|
+
return arg;
|
|
3292
|
+
});
|
|
3293
|
+
}
|
|
3294
|
+
function useColor() {
|
|
3295
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3296
|
+
return false;
|
|
3297
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3298
|
+
return true;
|
|
3299
|
+
return void 0;
|
|
3300
|
+
}
|
|
3301
|
+
exports2.Command = Command2;
|
|
3302
|
+
exports2.useColor = useColor;
|
|
3303
|
+
}
|
|
3304
|
+
});
|
|
3305
|
+
|
|
3306
|
+
// node_modules/commander/index.js
|
|
3307
|
+
var require_commander = __commonJS({
|
|
3308
|
+
"node_modules/commander/index.js"(exports2) {
|
|
3309
|
+
"use strict";
|
|
3310
|
+
var { Argument: Argument2 } = require_argument();
|
|
3311
|
+
var { Command: Command2 } = require_command();
|
|
3312
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
3313
|
+
var { Help: Help2 } = require_help();
|
|
3314
|
+
var { Option: Option2 } = require_option();
|
|
3315
|
+
exports2.program = new Command2();
|
|
3316
|
+
exports2.createCommand = (name) => new Command2(name);
|
|
3317
|
+
exports2.createOption = (flags, description) => new Option2(flags, description);
|
|
3318
|
+
exports2.createArgument = (name, description) => new Argument2(name, description);
|
|
3319
|
+
exports2.Command = Command2;
|
|
3320
|
+
exports2.Option = Option2;
|
|
3321
|
+
exports2.Argument = Argument2;
|
|
3322
|
+
exports2.Help = Help2;
|
|
3323
|
+
exports2.CommanderError = CommanderError2;
|
|
3324
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
3325
|
+
exports2.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
3326
|
+
}
|
|
3327
|
+
});
|
|
3328
|
+
|
|
3329
|
+
// node_modules/commander/esm.mjs
|
|
3330
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3331
|
+
var {
|
|
3332
|
+
program,
|
|
3333
|
+
createCommand,
|
|
3334
|
+
createArgument,
|
|
3335
|
+
createOption,
|
|
3336
|
+
CommanderError,
|
|
3337
|
+
InvalidArgumentError,
|
|
3338
|
+
InvalidOptionArgumentError,
|
|
3339
|
+
// deprecated old name
|
|
3340
|
+
Command,
|
|
3341
|
+
Argument,
|
|
3342
|
+
Option,
|
|
3343
|
+
Help
|
|
3344
|
+
} = import_index.default;
|
|
3345
|
+
|
|
3346
|
+
// src/utils/output.ts
|
|
3347
|
+
var jsonMode = false;
|
|
3348
|
+
function setJsonMode(enabled) {
|
|
3349
|
+
jsonMode = enabled;
|
|
3350
|
+
}
|
|
3351
|
+
function isJsonMode() {
|
|
3352
|
+
return jsonMode;
|
|
3353
|
+
}
|
|
3354
|
+
function output(data) {
|
|
3355
|
+
if (jsonMode) {
|
|
3356
|
+
console.log(JSON.stringify(data, null, 2));
|
|
3357
|
+
} else if (Array.isArray(data)) {
|
|
3358
|
+
console.table(data);
|
|
3359
|
+
} else if (typeof data === "object" && data !== null) {
|
|
3360
|
+
for (const [key, value] of Object.entries(data)) {
|
|
3361
|
+
console.log(`${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
|
|
3362
|
+
}
|
|
3363
|
+
} else {
|
|
3364
|
+
console.log(data);
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
function ok(message) {
|
|
3368
|
+
if (jsonMode) {
|
|
3369
|
+
console.log(JSON.stringify({ ok: true, message }));
|
|
3370
|
+
} else {
|
|
3371
|
+
console.log(`\u2713 ${message}`);
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
function fail(message, code = 1) {
|
|
3375
|
+
if (jsonMode) {
|
|
3376
|
+
console.error(JSON.stringify({ ok: false, error: message }));
|
|
3377
|
+
} else {
|
|
3378
|
+
console.error(`Error: ${message}`);
|
|
3379
|
+
}
|
|
3380
|
+
process.exit(code);
|
|
3381
|
+
}
|
|
3382
|
+
|
|
3383
|
+
// src/utils/token-store.ts
|
|
3384
|
+
var import_node_fs = require("fs");
|
|
3385
|
+
var import_node_os = require("os");
|
|
3386
|
+
var import_node_path = require("path");
|
|
3387
|
+
var CONFIG_DIR = (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "neopress");
|
|
3388
|
+
var TOKENS_FILE = (0, import_node_path.join)(CONFIG_DIR, "tokens.json");
|
|
3389
|
+
function ensureConfigDir() {
|
|
3390
|
+
if (!(0, import_node_fs.existsSync)(CONFIG_DIR)) {
|
|
3391
|
+
(0, import_node_fs.mkdirSync)(CONFIG_DIR, { recursive: true });
|
|
3392
|
+
}
|
|
3393
|
+
}
|
|
3394
|
+
function loadSession() {
|
|
3395
|
+
try {
|
|
3396
|
+
return JSON.parse((0, import_node_fs.readFileSync)(TOKENS_FILE, "utf-8"));
|
|
3397
|
+
} catch {
|
|
3398
|
+
return {};
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
function saveSession(session) {
|
|
3402
|
+
ensureConfigDir();
|
|
3403
|
+
(0, import_node_fs.writeFileSync)(TOKENS_FILE, JSON.stringify(session, null, 2) + "\n");
|
|
3404
|
+
try {
|
|
3405
|
+
(0, import_node_fs.chmodSync)(TOKENS_FILE, 384);
|
|
3406
|
+
} catch {
|
|
3407
|
+
}
|
|
3408
|
+
}
|
|
3409
|
+
function clearSession() {
|
|
3410
|
+
saveSession({});
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
// src/utils/pkce.ts
|
|
3414
|
+
var import_node_crypto = require("crypto");
|
|
3415
|
+
function generateCodeVerifier() {
|
|
3416
|
+
return (0, import_node_crypto.randomBytes)(32).toString("base64url");
|
|
3417
|
+
}
|
|
3418
|
+
function generateCodeChallenge(verifier) {
|
|
3419
|
+
return (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url");
|
|
3420
|
+
}
|
|
3421
|
+
|
|
3422
|
+
// src/utils/callback-server.ts
|
|
3423
|
+
var import_node_http = require("http");
|
|
3424
|
+
var TIMEOUT_MS = 5 * 60 * 1e3;
|
|
3425
|
+
var SUCCESS_HTML = `<!DOCTYPE html>
|
|
3426
|
+
<html>
|
|
3427
|
+
<head><meta charset="utf-8"><title>Neopress CLI</title>
|
|
3428
|
+
<style>
|
|
3429
|
+
body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #fafafa; }
|
|
3430
|
+
.card { text-align: center; padding: 3rem; background: white; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
|
|
3431
|
+
h1 { color: #111; margin-bottom: 0.5rem; }
|
|
3432
|
+
p { color: #666; }
|
|
3433
|
+
</style>
|
|
3434
|
+
</head>
|
|
3435
|
+
<body>
|
|
3436
|
+
<div class="card">
|
|
3437
|
+
<h1>Logged in!</h1>
|
|
3438
|
+
<p>You can close this tab and return to the terminal.</p>
|
|
3439
|
+
</div>
|
|
3440
|
+
</body>
|
|
3441
|
+
</html>`;
|
|
3442
|
+
function createCallbackServer() {
|
|
3443
|
+
let resolvePort;
|
|
3444
|
+
let resolveCode;
|
|
3445
|
+
let rejectAll;
|
|
3446
|
+
const portPromise = new Promise((res, rej) => {
|
|
3447
|
+
resolvePort = res;
|
|
3448
|
+
rejectAll = rej;
|
|
3449
|
+
});
|
|
3450
|
+
const codePromise = new Promise((res) => {
|
|
3451
|
+
resolveCode = res;
|
|
3452
|
+
});
|
|
3453
|
+
const server = (0, import_node_http.createServer)((req, res) => {
|
|
3454
|
+
const url = new URL(req.url || "/", `http://127.0.0.1`);
|
|
3455
|
+
if (url.pathname === "/auth/callback") {
|
|
3456
|
+
const code = url.searchParams.get("code");
|
|
3457
|
+
if (code) {
|
|
3458
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
3459
|
+
res.end(SUCCESS_HTML);
|
|
3460
|
+
resolveCode(code);
|
|
3461
|
+
} else {
|
|
3462
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
3463
|
+
res.end("Missing authorization code");
|
|
3464
|
+
}
|
|
3465
|
+
} else {
|
|
3466
|
+
res.writeHead(404);
|
|
3467
|
+
res.end("Not found");
|
|
3468
|
+
}
|
|
3469
|
+
});
|
|
3470
|
+
server.on("error", (err) => {
|
|
3471
|
+
if (err.code === "EADDRINUSE") {
|
|
3472
|
+
server.listen(0, "127.0.0.1");
|
|
3473
|
+
} else {
|
|
3474
|
+
rejectAll(err);
|
|
3475
|
+
}
|
|
3476
|
+
});
|
|
3477
|
+
server.on("listening", () => {
|
|
3478
|
+
const addr = server.address();
|
|
3479
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
3480
|
+
resolvePort(port);
|
|
3481
|
+
});
|
|
3482
|
+
const timeout = setTimeout(() => {
|
|
3483
|
+
server.close();
|
|
3484
|
+
rejectAll(new Error("Login timed out (5 minutes). Please try again."));
|
|
3485
|
+
}, TIMEOUT_MS);
|
|
3486
|
+
server.on("close", () => clearTimeout(timeout));
|
|
3487
|
+
server.listen(54321, "127.0.0.1");
|
|
3488
|
+
return { server, port: portPromise, code: codePromise };
|
|
3489
|
+
}
|
|
3490
|
+
|
|
3491
|
+
// src/utils/supabase-config.ts
|
|
3492
|
+
function getSupabaseConfig() {
|
|
3493
|
+
return {
|
|
3494
|
+
url: process.env.NEOPRESS_SUPABASE_URL || "https://gxrfyjmsmiakirmtzkmv.supabase.co",
|
|
3495
|
+
anonKey: process.env.NEOPRESS_SUPABASE_ANON_KEY || "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imd4cmZ5am1zbWlha2lybXR6a212Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjIxNDM2MzQsImV4cCI6MjA3NzcxOTYzNH0.Xzx6Xg5O1EBXZ64_5BP7KhsVyafJ0GI-62HcDpq6WRk"
|
|
3496
|
+
};
|
|
3497
|
+
}
|
|
3498
|
+
|
|
3499
|
+
// src/utils/token-refresh.ts
|
|
3500
|
+
var REFRESH_BUFFER_SECONDS = 60;
|
|
3501
|
+
async function exchangeCodeForTokens(code, codeVerifier) {
|
|
3502
|
+
const { url, anonKey } = getSupabaseConfig();
|
|
3503
|
+
const response = await fetch(`${url}/auth/v1/token?grant_type=pkce`, {
|
|
3504
|
+
method: "POST",
|
|
3505
|
+
headers: {
|
|
3506
|
+
"Content-Type": "application/json",
|
|
3507
|
+
"apikey": anonKey
|
|
3508
|
+
},
|
|
3509
|
+
body: JSON.stringify({
|
|
3510
|
+
auth_code: code,
|
|
3511
|
+
code_verifier: codeVerifier
|
|
3512
|
+
})
|
|
3513
|
+
});
|
|
3514
|
+
if (!response.ok) {
|
|
3515
|
+
const err = await response.text();
|
|
3516
|
+
throw new Error(`Token exchange failed: ${err}`);
|
|
3517
|
+
}
|
|
3518
|
+
const data = await response.json();
|
|
3519
|
+
return {
|
|
3520
|
+
accessToken: data.access_token,
|
|
3521
|
+
refreshToken: data.refresh_token,
|
|
3522
|
+
expiresAt: Math.floor(Date.now() / 1e3) + data.expires_in,
|
|
3523
|
+
userId: data.user?.id || ""
|
|
3524
|
+
};
|
|
3525
|
+
}
|
|
3526
|
+
async function refreshAccessToken(refreshToken) {
|
|
3527
|
+
const { url, anonKey } = getSupabaseConfig();
|
|
3528
|
+
const response = await fetch(`${url}/auth/v1/token?grant_type=refresh_token`, {
|
|
3529
|
+
method: "POST",
|
|
3530
|
+
headers: {
|
|
3531
|
+
"Content-Type": "application/json",
|
|
3532
|
+
"apikey": anonKey
|
|
3533
|
+
},
|
|
3534
|
+
body: JSON.stringify({
|
|
3535
|
+
refresh_token: refreshToken
|
|
3536
|
+
})
|
|
3537
|
+
});
|
|
3538
|
+
if (!response.ok) {
|
|
3539
|
+
const err = await response.text();
|
|
3540
|
+
throw new Error(`Token refresh failed: ${err}`);
|
|
3541
|
+
}
|
|
3542
|
+
const data = await response.json();
|
|
3543
|
+
return {
|
|
3544
|
+
accessToken: data.access_token,
|
|
3545
|
+
refreshToken: data.refresh_token,
|
|
3546
|
+
expiresAt: Math.floor(Date.now() / 1e3) + data.expires_in,
|
|
3547
|
+
userId: data.user?.id || ""
|
|
3548
|
+
};
|
|
3549
|
+
}
|
|
3550
|
+
async function getValidAccessToken() {
|
|
3551
|
+
const session = loadSession();
|
|
3552
|
+
if (!session.tokens) return null;
|
|
3553
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3554
|
+
if (session.tokens.expiresAt > now + REFRESH_BUFFER_SECONDS) {
|
|
3555
|
+
return session.tokens.accessToken;
|
|
3556
|
+
}
|
|
3557
|
+
try {
|
|
3558
|
+
const newTokens = await refreshAccessToken(session.tokens.refreshToken);
|
|
3559
|
+
saveSession({ ...session, tokens: newTokens });
|
|
3560
|
+
return newTokens.accessToken;
|
|
3561
|
+
} catch {
|
|
3562
|
+
return null;
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
|
|
3566
|
+
// src/commands/auth.ts
|
|
3567
|
+
function decodeJwtPayload(token) {
|
|
3568
|
+
try {
|
|
3569
|
+
const payload = token.split(".")[1];
|
|
3570
|
+
if (!payload) return null;
|
|
3571
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf-8"));
|
|
3572
|
+
} catch {
|
|
3573
|
+
return null;
|
|
3574
|
+
}
|
|
3575
|
+
}
|
|
3576
|
+
function parseImplicitCallbackTokens(callbackUrl) {
|
|
3577
|
+
const url = new URL(callbackUrl.trim());
|
|
3578
|
+
const fragment = url.hash.startsWith("#") ? url.hash.slice(1) : "";
|
|
3579
|
+
if (!fragment) return null;
|
|
3580
|
+
const params = new URLSearchParams(fragment);
|
|
3581
|
+
const accessToken = params.get("access_token");
|
|
3582
|
+
const refreshToken = params.get("refresh_token");
|
|
3583
|
+
if (!accessToken || !refreshToken) return null;
|
|
3584
|
+
const payload = decodeJwtPayload(accessToken);
|
|
3585
|
+
const expiresAtParam = params.get("expires_at");
|
|
3586
|
+
const expiresInParam = params.get("expires_in");
|
|
3587
|
+
const expiresAt = expiresAtParam ? parseInt(expiresAtParam, 10) : expiresInParam ? Math.floor(Date.now() / 1e3) + parseInt(expiresInParam, 10) : typeof payload?.exp === "number" ? payload.exp : Math.floor(Date.now() / 1e3) + 3600;
|
|
3588
|
+
return {
|
|
3589
|
+
accessToken,
|
|
3590
|
+
refreshToken,
|
|
3591
|
+
expiresAt,
|
|
3592
|
+
userId: typeof payload?.sub === "string" ? payload.sub : ""
|
|
3593
|
+
};
|
|
3594
|
+
}
|
|
3595
|
+
function registerAuthCommands(program3) {
|
|
3596
|
+
program3.command("login").description("Authenticate with Neopress").option("--provider <provider>", "OAuth provider (google)", "google").option("--manual", "Paste the OAuth callback URL manually instead of running a local callback server").action(async (options) => {
|
|
3597
|
+
console.log(options.manual ? "Starting manual browser login..." : "Opening browser for login...");
|
|
3598
|
+
const codeVerifier = generateCodeVerifier();
|
|
3599
|
+
const codeChallenge = generateCodeChallenge(codeVerifier);
|
|
3600
|
+
const { url: supabaseUrl } = getSupabaseConfig();
|
|
3601
|
+
let server = null;
|
|
3602
|
+
let codePromise = null;
|
|
3603
|
+
let redirectUri = "http://127.0.0.1:54321/auth/callback";
|
|
3604
|
+
if (!options.manual) {
|
|
3605
|
+
const callback = createCallbackServer();
|
|
3606
|
+
server = callback.server;
|
|
3607
|
+
codePromise = callback.code;
|
|
3608
|
+
const port = await callback.port;
|
|
3609
|
+
redirectUri = `http://127.0.0.1:${port}/auth/callback`;
|
|
3610
|
+
}
|
|
3611
|
+
const authUrl = new URL(`${supabaseUrl}/auth/v1/authorize`);
|
|
3612
|
+
authUrl.searchParams.set("provider", options.provider);
|
|
3613
|
+
authUrl.searchParams.set("redirect_to", redirectUri);
|
|
3614
|
+
authUrl.searchParams.set("code_challenge", codeChallenge);
|
|
3615
|
+
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
3616
|
+
const openUrl = authUrl.toString();
|
|
3617
|
+
console.log(`Login URL: ${openUrl}`);
|
|
3618
|
+
if (!options.manual) try {
|
|
3619
|
+
const { exec } = await import("child_process");
|
|
3620
|
+
const cmd = process.platform === "darwin" ? `open "${openUrl}"` : process.platform === "win32" ? `start "${openUrl}"` : `xdg-open "${openUrl}"`;
|
|
3621
|
+
exec(cmd);
|
|
3622
|
+
} catch {
|
|
3623
|
+
console.log(`Open this URL in your browser:
|
|
3624
|
+
${openUrl}`);
|
|
3625
|
+
}
|
|
3626
|
+
try {
|
|
3627
|
+
let code;
|
|
3628
|
+
let tokens = null;
|
|
3629
|
+
if (options.manual) {
|
|
3630
|
+
console.log("After approving, paste the full callback URL from your browser address bar.");
|
|
3631
|
+
const { createInterface } = await import("readline/promises");
|
|
3632
|
+
const { stdin, stdout } = await import("process");
|
|
3633
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
3634
|
+
const callbackUrl = await rl.question("Callback URL: ");
|
|
3635
|
+
rl.close();
|
|
3636
|
+
tokens = parseImplicitCallbackTokens(callbackUrl);
|
|
3637
|
+
code = tokens ? null : new URL(callbackUrl.trim()).searchParams.get("code");
|
|
3638
|
+
if (!tokens && !code) {
|
|
3639
|
+
fail("Callback URL does not contain OAuth tokens or a code parameter.");
|
|
3640
|
+
}
|
|
3641
|
+
} else {
|
|
3642
|
+
console.log(`Waiting for login at ${redirectUri}...`);
|
|
3643
|
+
code = await codePromise;
|
|
3644
|
+
}
|
|
3645
|
+
if (!tokens) {
|
|
3646
|
+
if (!code) fail("OAuth callback did not include an authorization code.");
|
|
3647
|
+
console.log("Exchanging code for tokens...");
|
|
3648
|
+
tokens = await exchangeCodeForTokens(code, codeVerifier);
|
|
3649
|
+
}
|
|
3650
|
+
const session = loadSession();
|
|
3651
|
+
saveSession({ ...session, tokens });
|
|
3652
|
+
server?.close();
|
|
3653
|
+
ok(`Logged in as user ${tokens.userId}. Use \`neopress sites use <siteId>\` to select a site.`);
|
|
3654
|
+
} catch (err) {
|
|
3655
|
+
server?.close();
|
|
3656
|
+
fail(err instanceof Error ? err.message : "Login failed");
|
|
3657
|
+
}
|
|
3658
|
+
});
|
|
3659
|
+
program3.command("logout").description("Clear authentication").action(() => {
|
|
3660
|
+
clearSession();
|
|
3661
|
+
ok("Logged out");
|
|
3662
|
+
});
|
|
3663
|
+
program3.command("whoami").description("Show current authentication status").action(async () => {
|
|
3664
|
+
const session = loadSession();
|
|
3665
|
+
if (session.tokens) {
|
|
3666
|
+
const accessToken = await getValidAccessToken();
|
|
3667
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
3668
|
+
const expired = session.tokens.expiresAt <= now;
|
|
3669
|
+
output({
|
|
3670
|
+
authenticated: Boolean(accessToken),
|
|
3671
|
+
method: "oauth",
|
|
3672
|
+
userId: session.tokens.userId,
|
|
3673
|
+
tokenExpired: expired && !accessToken,
|
|
3674
|
+
activeSiteId: session.activeSiteId || null
|
|
3675
|
+
});
|
|
3676
|
+
return;
|
|
3677
|
+
}
|
|
3678
|
+
fail("Not authenticated. Run `neopress login`.");
|
|
3679
|
+
});
|
|
3680
|
+
}
|
|
3681
|
+
|
|
3682
|
+
// ../sdk/dist/errors.js
|
|
3683
|
+
var NeopressApiError = class extends Error {
|
|
3684
|
+
code;
|
|
3685
|
+
status;
|
|
3686
|
+
response;
|
|
3687
|
+
constructor(code, message, status, response) {
|
|
3688
|
+
super(message);
|
|
3689
|
+
this.code = code;
|
|
3690
|
+
this.status = status;
|
|
3691
|
+
this.response = response;
|
|
3692
|
+
this.name = "NeopressApiError";
|
|
3693
|
+
}
|
|
3694
|
+
};
|
|
3695
|
+
|
|
3696
|
+
// ../sdk/dist/endpoints/pages.js
|
|
3697
|
+
var PagesEndpoint = class {
|
|
3698
|
+
client;
|
|
3699
|
+
constructor(client) {
|
|
3700
|
+
this.client = client;
|
|
3701
|
+
}
|
|
3702
|
+
get basePath() {
|
|
3703
|
+
return `${this.client.siteBasePath}/pages`;
|
|
3704
|
+
}
|
|
3705
|
+
async list(params) {
|
|
3706
|
+
const qs = new URLSearchParams();
|
|
3707
|
+
if (params?.page)
|
|
3708
|
+
qs.set("page", String(params.page));
|
|
3709
|
+
if (params?.limit)
|
|
3710
|
+
qs.set("limit", String(params.limit));
|
|
3711
|
+
if (params?.status)
|
|
3712
|
+
qs.set("status", params.status);
|
|
3713
|
+
if (params?.fields)
|
|
3714
|
+
qs.set("fields", params.fields.join(","));
|
|
3715
|
+
const query = qs.toString();
|
|
3716
|
+
return this.client.getList(`${this.basePath}${query ? `?${query}` : ""}`);
|
|
3717
|
+
}
|
|
3718
|
+
async get(pageId) {
|
|
3719
|
+
const res = await this.client.get(`${this.basePath}/${pageId}`);
|
|
3720
|
+
return res.data;
|
|
3721
|
+
}
|
|
3722
|
+
async create(data) {
|
|
3723
|
+
const res = await this.client.post(this.basePath, data);
|
|
3724
|
+
return res.data;
|
|
3725
|
+
}
|
|
3726
|
+
async update(pageId, data) {
|
|
3727
|
+
const res = await this.client.patch(`${this.basePath}/${pageId}`, data);
|
|
3728
|
+
return res.data;
|
|
3729
|
+
}
|
|
3730
|
+
async delete(pageId) {
|
|
3731
|
+
await this.client.delete(`${this.basePath}/${pageId}`);
|
|
3732
|
+
}
|
|
3733
|
+
async compile(pageId) {
|
|
3734
|
+
const res = await this.client.post(`${this.basePath}/${pageId}/compile`);
|
|
3735
|
+
return res.data;
|
|
3736
|
+
}
|
|
3737
|
+
};
|
|
3738
|
+
|
|
3739
|
+
// ../sdk/dist/endpoints/collections.js
|
|
3740
|
+
var CollectionsEndpoint = class {
|
|
3741
|
+
client;
|
|
3742
|
+
constructor(client) {
|
|
3743
|
+
this.client = client;
|
|
3744
|
+
}
|
|
3745
|
+
get basePath() {
|
|
3746
|
+
return `${this.client.siteBasePath}/collections`;
|
|
3747
|
+
}
|
|
3748
|
+
async list() {
|
|
3749
|
+
const res = await this.client.get(this.basePath);
|
|
3750
|
+
return res.data;
|
|
3751
|
+
}
|
|
3752
|
+
async get(collectionId) {
|
|
3753
|
+
const res = await this.client.get(`${this.basePath}/${collectionId}`);
|
|
3754
|
+
return res.data;
|
|
3755
|
+
}
|
|
3756
|
+
async create(data) {
|
|
3757
|
+
const res = await this.client.post(this.basePath, data);
|
|
3758
|
+
return res.data;
|
|
3759
|
+
}
|
|
3760
|
+
async update(collectionId, data) {
|
|
3761
|
+
const res = await this.client.patch(`${this.basePath}/${collectionId}`, data);
|
|
3762
|
+
return res.data;
|
|
3763
|
+
}
|
|
3764
|
+
async delete(collectionId) {
|
|
3765
|
+
await this.client.delete(`${this.basePath}/${collectionId}`);
|
|
3766
|
+
}
|
|
3767
|
+
async getSchema(collectionId) {
|
|
3768
|
+
const res = await this.client.get(`${this.basePath}/${collectionId}/schema`);
|
|
3769
|
+
return res.data;
|
|
3770
|
+
}
|
|
3771
|
+
async updateSchema(collectionId, schema) {
|
|
3772
|
+
const res = await this.client.patch(`${this.basePath}/${collectionId}/schema`, { schema });
|
|
3773
|
+
return res.data;
|
|
3774
|
+
}
|
|
3775
|
+
};
|
|
3776
|
+
|
|
3777
|
+
// ../sdk/dist/endpoints/entries.js
|
|
3778
|
+
var EntriesEndpoint = class {
|
|
3779
|
+
client;
|
|
3780
|
+
constructor(client) {
|
|
3781
|
+
this.client = client;
|
|
3782
|
+
}
|
|
3783
|
+
async list(collectionId, params) {
|
|
3784
|
+
const qs = new URLSearchParams();
|
|
3785
|
+
if (params?.page)
|
|
3786
|
+
qs.set("page", String(params.page));
|
|
3787
|
+
if (params?.limit)
|
|
3788
|
+
qs.set("limit", String(params.limit));
|
|
3789
|
+
if (params?.status)
|
|
3790
|
+
qs.set("status", params.status);
|
|
3791
|
+
if (params?.locale)
|
|
3792
|
+
qs.set("locale", params.locale);
|
|
3793
|
+
const query = qs.toString();
|
|
3794
|
+
return this.client.getList(`${this.client.siteBasePath}/collections/${collectionId}/entries${query ? `?${query}` : ""}`);
|
|
3795
|
+
}
|
|
3796
|
+
async get(entryId) {
|
|
3797
|
+
const res = await this.client.get(`${this.client.siteBasePath}/entries/${entryId}`);
|
|
3798
|
+
return res.data;
|
|
3799
|
+
}
|
|
3800
|
+
async create(collectionId, data) {
|
|
3801
|
+
const res = await this.client.post(`${this.client.siteBasePath}/collections/${collectionId}/entries`, data);
|
|
3802
|
+
return res.data;
|
|
3803
|
+
}
|
|
3804
|
+
async update(entryId, data) {
|
|
3805
|
+
const res = await this.client.patch(`${this.client.siteBasePath}/entries/${entryId}`, data);
|
|
3806
|
+
return res.data;
|
|
3807
|
+
}
|
|
3808
|
+
async delete(entryId) {
|
|
3809
|
+
await this.client.delete(`${this.client.siteBasePath}/entries/${entryId}`);
|
|
3810
|
+
}
|
|
3811
|
+
async publish(entryId) {
|
|
3812
|
+
const res = await this.client.post(`${this.client.siteBasePath}/entries/${entryId}/publish`);
|
|
3813
|
+
return res.data;
|
|
3814
|
+
}
|
|
3815
|
+
async unpublish(entryId) {
|
|
3816
|
+
const res = await this.client.post(`${this.client.siteBasePath}/entries/${entryId}/unpublish`);
|
|
3817
|
+
return res.data;
|
|
3818
|
+
}
|
|
3819
|
+
async listVersions(entryId) {
|
|
3820
|
+
const res = await this.client.get(`${this.client.siteBasePath}/entries/${entryId}/versions`);
|
|
3821
|
+
return res.data;
|
|
3822
|
+
}
|
|
3823
|
+
async pinVersion(entryId, versionId) {
|
|
3824
|
+
const res = await this.client.post(`${this.client.siteBasePath}/entries/${entryId}/versions/${versionId}/pin`);
|
|
3825
|
+
return res.data;
|
|
3826
|
+
}
|
|
3827
|
+
};
|
|
3828
|
+
|
|
3829
|
+
// ../sdk/dist/endpoints/forms.js
|
|
3830
|
+
var FormsEndpoint = class {
|
|
3831
|
+
client;
|
|
3832
|
+
constructor(client) {
|
|
3833
|
+
this.client = client;
|
|
3834
|
+
}
|
|
3835
|
+
get basePath() {
|
|
3836
|
+
return `${this.client.siteBasePath}/forms`;
|
|
3837
|
+
}
|
|
3838
|
+
async list() {
|
|
3839
|
+
const res = await this.client.get(this.basePath);
|
|
3840
|
+
return res.data;
|
|
3841
|
+
}
|
|
3842
|
+
async get(formId) {
|
|
3843
|
+
const res = await this.client.get(`${this.basePath}/${formId}`);
|
|
3844
|
+
return res.data;
|
|
3845
|
+
}
|
|
3846
|
+
async create(data) {
|
|
3847
|
+
const res = await this.client.post(this.basePath, data);
|
|
3848
|
+
return res.data;
|
|
3849
|
+
}
|
|
3850
|
+
async update(formId, data) {
|
|
3851
|
+
const res = await this.client.patch(`${this.basePath}/${formId}`, data);
|
|
3852
|
+
return res.data;
|
|
3853
|
+
}
|
|
3854
|
+
async delete(formId) {
|
|
3855
|
+
await this.client.delete(`${this.basePath}/${formId}`);
|
|
3856
|
+
}
|
|
3857
|
+
async publish(formId) {
|
|
3858
|
+
const res = await this.client.post(`${this.basePath}/${formId}/publish`);
|
|
3859
|
+
return res.data;
|
|
3860
|
+
}
|
|
3861
|
+
async listResponses(formId, params) {
|
|
3862
|
+
const qs = new URLSearchParams();
|
|
3863
|
+
if (params?.page)
|
|
3864
|
+
qs.set("page", String(params.page));
|
|
3865
|
+
if (params?.limit)
|
|
3866
|
+
qs.set("limit", String(params.limit));
|
|
3867
|
+
const query = qs.toString();
|
|
3868
|
+
return this.client.getList(`${this.basePath}/${formId}/responses${query ? `?${query}` : ""}`);
|
|
3869
|
+
}
|
|
3870
|
+
async deleteResponse(formId, responseId) {
|
|
3871
|
+
await this.client.delete(`${this.basePath}/${formId}/responses/${responseId}`);
|
|
3872
|
+
}
|
|
3873
|
+
};
|
|
3874
|
+
|
|
3875
|
+
// ../sdk/dist/endpoints/assets.js
|
|
3876
|
+
var AssetsEndpoint = class {
|
|
3877
|
+
client;
|
|
3878
|
+
constructor(client) {
|
|
3879
|
+
this.client = client;
|
|
3880
|
+
}
|
|
3881
|
+
get basePath() {
|
|
3882
|
+
return `${this.client.siteBasePath}/assets`;
|
|
3883
|
+
}
|
|
3884
|
+
async list(params) {
|
|
3885
|
+
const qs = new URLSearchParams();
|
|
3886
|
+
if (params?.page)
|
|
3887
|
+
qs.set("page", String(params.page));
|
|
3888
|
+
if (params?.limit)
|
|
3889
|
+
qs.set("limit", String(params.limit));
|
|
3890
|
+
const query = qs.toString();
|
|
3891
|
+
return this.client.getList(`${this.basePath}${query ? `?${query}` : ""}`);
|
|
3892
|
+
}
|
|
3893
|
+
async get(assetId) {
|
|
3894
|
+
const res = await this.client.get(`${this.basePath}/${assetId}`);
|
|
3895
|
+
return res.data;
|
|
3896
|
+
}
|
|
3897
|
+
async register(data) {
|
|
3898
|
+
const res = await this.client.post(this.basePath, data);
|
|
3899
|
+
return res.data;
|
|
3900
|
+
}
|
|
3901
|
+
async update(assetId, data) {
|
|
3902
|
+
const res = await this.client.patch(`${this.basePath}/${assetId}`, data);
|
|
3903
|
+
return res.data;
|
|
3904
|
+
}
|
|
3905
|
+
async delete(assetId) {
|
|
3906
|
+
await this.client.delete(`${this.basePath}/${assetId}`);
|
|
3907
|
+
}
|
|
3908
|
+
async presign(data) {
|
|
3909
|
+
const res = await this.client.post(`${this.basePath}/presign`, data);
|
|
3910
|
+
return res.data;
|
|
3911
|
+
}
|
|
3912
|
+
};
|
|
3913
|
+
|
|
3914
|
+
// ../sdk/dist/endpoints/site.js
|
|
3915
|
+
var SiteEndpoint = class {
|
|
3916
|
+
client;
|
|
3917
|
+
constructor(client) {
|
|
3918
|
+
this.client = client;
|
|
3919
|
+
}
|
|
3920
|
+
async list() {
|
|
3921
|
+
const res = await this.client.get("/api/v1/sites");
|
|
3922
|
+
return res.data;
|
|
3923
|
+
}
|
|
3924
|
+
async get() {
|
|
3925
|
+
const res = await this.client.get(this.client.siteBasePath);
|
|
3926
|
+
return res.data;
|
|
3927
|
+
}
|
|
3928
|
+
async create(data) {
|
|
3929
|
+
const res = await this.client.post("/api/v1/sites", data);
|
|
3930
|
+
return res.data;
|
|
3931
|
+
}
|
|
3932
|
+
async update(data) {
|
|
3933
|
+
const res = await this.client.patch(this.client.siteBasePath, data);
|
|
3934
|
+
return res.data;
|
|
3935
|
+
}
|
|
3936
|
+
async getLayout() {
|
|
3937
|
+
const res = await this.client.get(`${this.client.siteBasePath}/layout`);
|
|
3938
|
+
return res.data;
|
|
3939
|
+
}
|
|
3940
|
+
async updateLayout(data) {
|
|
3941
|
+
const res = await this.client.patch(`${this.client.siteBasePath}/layout`, data);
|
|
3942
|
+
return res.data;
|
|
3943
|
+
}
|
|
3944
|
+
};
|
|
3945
|
+
|
|
3946
|
+
// ../sdk/dist/endpoints/redirects.js
|
|
3947
|
+
var RedirectsEndpoint = class {
|
|
3948
|
+
client;
|
|
3949
|
+
constructor(client) {
|
|
3950
|
+
this.client = client;
|
|
3951
|
+
}
|
|
3952
|
+
get basePath() {
|
|
3953
|
+
return `${this.client.siteBasePath}/redirects`;
|
|
3954
|
+
}
|
|
3955
|
+
async list() {
|
|
3956
|
+
const res = await this.client.get(this.basePath);
|
|
3957
|
+
return res.data;
|
|
3958
|
+
}
|
|
3959
|
+
async create(data) {
|
|
3960
|
+
const res = await this.client.post(this.basePath, data);
|
|
3961
|
+
return res.data;
|
|
3962
|
+
}
|
|
3963
|
+
async update(ruleId, data) {
|
|
3964
|
+
const res = await this.client.patch(`${this.basePath}/${ruleId}`, data);
|
|
3965
|
+
return res.data;
|
|
3966
|
+
}
|
|
3967
|
+
async delete(ruleId) {
|
|
3968
|
+
await this.client.delete(`${this.basePath}/${ruleId}`);
|
|
3969
|
+
}
|
|
3970
|
+
};
|
|
3971
|
+
|
|
3972
|
+
// ../sdk/dist/endpoints/publish.js
|
|
3973
|
+
var PublishEndpoint = class {
|
|
3974
|
+
client;
|
|
3975
|
+
constructor(client) {
|
|
3976
|
+
this.client = client;
|
|
3977
|
+
}
|
|
3978
|
+
async preview() {
|
|
3979
|
+
const res = await this.client.get(`${this.client.siteBasePath}/publish`);
|
|
3980
|
+
return res.data;
|
|
3981
|
+
}
|
|
3982
|
+
async site() {
|
|
3983
|
+
const res = await this.client.post(`${this.client.siteBasePath}/publish`);
|
|
3984
|
+
return res.data;
|
|
3985
|
+
}
|
|
3986
|
+
};
|
|
3987
|
+
|
|
3988
|
+
// ../sdk/dist/endpoints/entry-references.js
|
|
3989
|
+
var EntryReferencesEndpoint = class {
|
|
3990
|
+
client;
|
|
3991
|
+
constructor(client) {
|
|
3992
|
+
this.client = client;
|
|
3993
|
+
}
|
|
3994
|
+
get basePath() {
|
|
3995
|
+
return `${this.client.siteBasePath}/entry-references`;
|
|
3996
|
+
}
|
|
3997
|
+
async list(params) {
|
|
3998
|
+
const qs = new URLSearchParams();
|
|
3999
|
+
if (params?.fromEntryId)
|
|
4000
|
+
qs.set("fromEntryId", String(params.fromEntryId));
|
|
4001
|
+
if (params?.toEntryId)
|
|
4002
|
+
qs.set("toEntryId", String(params.toEntryId));
|
|
4003
|
+
const query = qs.toString();
|
|
4004
|
+
const res = await this.client.get(`${this.basePath}${query ? `?${query}` : ""}`);
|
|
4005
|
+
return res.data;
|
|
4006
|
+
}
|
|
4007
|
+
async create(data) {
|
|
4008
|
+
const res = await this.client.post(this.basePath, data);
|
|
4009
|
+
return res.data;
|
|
4010
|
+
}
|
|
4011
|
+
async delete(referenceId) {
|
|
4012
|
+
await this.client.delete(`${this.basePath}/${referenceId}`);
|
|
4013
|
+
}
|
|
4014
|
+
};
|
|
4015
|
+
|
|
4016
|
+
// ../sdk/dist/endpoints/analytics.js
|
|
4017
|
+
var RESERVED_ANALYTICS_PARAMS = /* @__PURE__ */ new Set([
|
|
4018
|
+
"pipe",
|
|
4019
|
+
"site",
|
|
4020
|
+
"site_id",
|
|
4021
|
+
"timezone",
|
|
4022
|
+
"token",
|
|
4023
|
+
"q"
|
|
4024
|
+
]);
|
|
4025
|
+
function setQueryValue(qs, key, value) {
|
|
4026
|
+
if (value === void 0)
|
|
4027
|
+
return;
|
|
4028
|
+
qs.set(key, String(value));
|
|
4029
|
+
}
|
|
4030
|
+
function appendCommonAnalyticsParams(qs, params) {
|
|
4031
|
+
setQueryValue(qs, "date_from", params?.dateFrom);
|
|
4032
|
+
setQueryValue(qs, "date_to", params?.dateTo);
|
|
4033
|
+
setQueryValue(qs, "timezone", params?.timezone);
|
|
4034
|
+
setQueryValue(qs, "limit", params?.limit);
|
|
4035
|
+
for (const [key, value] of Object.entries(params?.params ?? {})) {
|
|
4036
|
+
if (RESERVED_ANALYTICS_PARAMS.has(key))
|
|
4037
|
+
continue;
|
|
4038
|
+
setQueryValue(qs, key, value);
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
var AnalyticsEndpoint = class {
|
|
4042
|
+
client;
|
|
4043
|
+
constructor(client) {
|
|
4044
|
+
this.client = client;
|
|
4045
|
+
}
|
|
4046
|
+
get basePath() {
|
|
4047
|
+
return `${this.client.siteBasePath}/analytics`;
|
|
4048
|
+
}
|
|
4049
|
+
async query(params) {
|
|
4050
|
+
const qs = new URLSearchParams();
|
|
4051
|
+
qs.set("pipe", params.pipe);
|
|
4052
|
+
appendCommonAnalyticsParams(qs, params);
|
|
4053
|
+
const res = await this.client.get(`${this.basePath}/query?${qs.toString()}`);
|
|
4054
|
+
return res.data;
|
|
4055
|
+
}
|
|
4056
|
+
async pageviews(params) {
|
|
4057
|
+
return this.query({ pipe: "get_pageviews", ...params });
|
|
4058
|
+
}
|
|
4059
|
+
async summary(params) {
|
|
4060
|
+
return this.query({ pipe: "get_engagement_summary", ...params });
|
|
4061
|
+
}
|
|
4062
|
+
async topPages(params) {
|
|
4063
|
+
return this.query({ pipe: "get_top_pages", ...params });
|
|
4064
|
+
}
|
|
4065
|
+
async trafficSources(params) {
|
|
4066
|
+
return this.query({ pipe: "get_traffic_sources", ...params });
|
|
4067
|
+
}
|
|
4068
|
+
async formAnalytics(params) {
|
|
4069
|
+
return this.query({ pipe: "get_form_analytics", ...params });
|
|
4070
|
+
}
|
|
4071
|
+
async crawlerSummary(params) {
|
|
4072
|
+
return this.query({ pipe: "get_crawler_summary", ...params });
|
|
4073
|
+
}
|
|
4074
|
+
async searchConsole(params) {
|
|
4075
|
+
const qs = new URLSearchParams();
|
|
4076
|
+
qs.set("date_from", params.dateFrom);
|
|
4077
|
+
qs.set("date_to", params.dateTo);
|
|
4078
|
+
if (params.dimensions)
|
|
4079
|
+
qs.set("dimensions", params.dimensions.join(","));
|
|
4080
|
+
if (params.queryFilter)
|
|
4081
|
+
qs.set("query_filter", params.queryFilter);
|
|
4082
|
+
if (params.pageFilter)
|
|
4083
|
+
qs.set("page_filter", params.pageFilter);
|
|
4084
|
+
if (params.rowLimit)
|
|
4085
|
+
qs.set("row_limit", String(params.rowLimit));
|
|
4086
|
+
const res = await this.client.get(`${this.basePath}/search-console?${qs.toString()}`);
|
|
4087
|
+
return res.data;
|
|
4088
|
+
}
|
|
4089
|
+
};
|
|
4090
|
+
|
|
4091
|
+
// ../sdk/dist/client.js
|
|
4092
|
+
var NeopressClient = class {
|
|
4093
|
+
baseUrl;
|
|
4094
|
+
accessToken;
|
|
4095
|
+
siteId;
|
|
4096
|
+
timeout;
|
|
4097
|
+
pages;
|
|
4098
|
+
collections;
|
|
4099
|
+
entries;
|
|
4100
|
+
forms;
|
|
4101
|
+
assets;
|
|
4102
|
+
site;
|
|
4103
|
+
redirects;
|
|
4104
|
+
publish;
|
|
4105
|
+
entryReferences;
|
|
4106
|
+
analytics;
|
|
4107
|
+
constructor(options) {
|
|
4108
|
+
this.baseUrl = (options.baseUrl || "https://app.neopress.ai").replace(/\/$/, "");
|
|
4109
|
+
this.accessToken = options.accessToken || "";
|
|
4110
|
+
this.siteId = options.siteId;
|
|
4111
|
+
this.timeout = options.timeout ?? 3e4;
|
|
4112
|
+
this.pages = new PagesEndpoint(this);
|
|
4113
|
+
this.collections = new CollectionsEndpoint(this);
|
|
4114
|
+
this.entries = new EntriesEndpoint(this);
|
|
4115
|
+
this.forms = new FormsEndpoint(this);
|
|
4116
|
+
this.assets = new AssetsEndpoint(this);
|
|
4117
|
+
this.site = new SiteEndpoint(this);
|
|
4118
|
+
this.redirects = new RedirectsEndpoint(this);
|
|
4119
|
+
this.publish = new PublishEndpoint(this);
|
|
4120
|
+
this.entryReferences = new EntryReferencesEndpoint(this);
|
|
4121
|
+
this.analytics = new AnalyticsEndpoint(this);
|
|
4122
|
+
}
|
|
4123
|
+
get siteBasePath() {
|
|
4124
|
+
return `/api/v1/sites/${this.siteId}`;
|
|
4125
|
+
}
|
|
4126
|
+
async request(method, path, body) {
|
|
4127
|
+
const url = `${this.baseUrl}${path}`;
|
|
4128
|
+
const headers = {
|
|
4129
|
+
"Authorization": `Bearer ${this.accessToken}`
|
|
4130
|
+
};
|
|
4131
|
+
if (body !== void 0) {
|
|
4132
|
+
headers["Content-Type"] = "application/json";
|
|
4133
|
+
}
|
|
4134
|
+
const controller = new AbortController();
|
|
4135
|
+
const timeout = setTimeout(() => controller.abort(), this.timeout);
|
|
4136
|
+
let response;
|
|
4137
|
+
try {
|
|
4138
|
+
response = await fetch(url, {
|
|
4139
|
+
method,
|
|
4140
|
+
headers,
|
|
4141
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
4142
|
+
signal: controller.signal
|
|
4143
|
+
});
|
|
4144
|
+
} catch (err) {
|
|
4145
|
+
clearTimeout(timeout);
|
|
4146
|
+
if (err?.name === "AbortError") {
|
|
4147
|
+
throw new NeopressApiError("TIMEOUT", `Request timed out: ${method} ${path}`, 0);
|
|
4148
|
+
}
|
|
4149
|
+
throw new NeopressApiError("CONNECTION_ERROR", `Cannot connect to ${this.baseUrl} \u2014 is the dev server running?`, 0);
|
|
4150
|
+
}
|
|
4151
|
+
clearTimeout(timeout);
|
|
4152
|
+
const json = await response.json();
|
|
4153
|
+
if (!response.ok) {
|
|
4154
|
+
const err = json?.error || {};
|
|
4155
|
+
throw new NeopressApiError(err.code || "UNKNOWN", err.message || response.statusText, response.status, json);
|
|
4156
|
+
}
|
|
4157
|
+
return json;
|
|
4158
|
+
}
|
|
4159
|
+
async get(path) {
|
|
4160
|
+
return this.request("GET", path);
|
|
4161
|
+
}
|
|
4162
|
+
async getList(path) {
|
|
4163
|
+
return this.request("GET", path);
|
|
4164
|
+
}
|
|
4165
|
+
async post(path, body) {
|
|
4166
|
+
return this.request("POST", path, body);
|
|
4167
|
+
}
|
|
4168
|
+
async patch(path, body) {
|
|
4169
|
+
return this.request("PATCH", path, body);
|
|
4170
|
+
}
|
|
4171
|
+
async delete(path) {
|
|
4172
|
+
return this.request("DELETE", path);
|
|
4173
|
+
}
|
|
4174
|
+
};
|
|
4175
|
+
|
|
4176
|
+
// src/utils/config.ts
|
|
4177
|
+
var import_node_fs2 = require("fs");
|
|
4178
|
+
var import_node_path2 = require("path");
|
|
4179
|
+
var PROJECT_CONFIG = ".neopressrc.json";
|
|
4180
|
+
var WORKSPACE_CONFIG = ".neopress/config.json";
|
|
4181
|
+
function readProjectConfig() {
|
|
4182
|
+
let config = {};
|
|
4183
|
+
for (const file of [PROJECT_CONFIG, WORKSPACE_CONFIG]) {
|
|
4184
|
+
try {
|
|
4185
|
+
const parsed = JSON.parse((0, import_node_fs2.readFileSync)(file, "utf-8"));
|
|
4186
|
+
config = {
|
|
4187
|
+
...config,
|
|
4188
|
+
...typeof parsed.siteId === "number" ? { siteId: parsed.siteId } : {},
|
|
4189
|
+
...typeof parsed.baseUrl === "string" ? { baseUrl: parsed.baseUrl } : {}
|
|
4190
|
+
};
|
|
4191
|
+
} catch {
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
return config;
|
|
4195
|
+
}
|
|
4196
|
+
function writeWorkspaceConfig(next) {
|
|
4197
|
+
(0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(WORKSPACE_CONFIG), { recursive: true });
|
|
4198
|
+
(0, import_node_fs2.writeFileSync)(WORKSPACE_CONFIG, JSON.stringify(next, null, 2) + "\n", "utf-8");
|
|
4199
|
+
}
|
|
4200
|
+
function getSiteId() {
|
|
4201
|
+
const envSiteId = process.env.NEOPRESS_SITE_ID;
|
|
4202
|
+
if (envSiteId) return parseInt(envSiteId, 10);
|
|
4203
|
+
const projectConfig = readProjectConfig();
|
|
4204
|
+
if (projectConfig.siteId) return projectConfig.siteId;
|
|
4205
|
+
return loadSession().activeSiteId;
|
|
4206
|
+
}
|
|
4207
|
+
function getBaseUrl() {
|
|
4208
|
+
return process.env.NEOPRESS_BASE_URL || readProjectConfig().baseUrl || "https://app.neopress.ai";
|
|
4209
|
+
}
|
|
4210
|
+
function setActiveSiteId(siteId) {
|
|
4211
|
+
const session = loadSession();
|
|
4212
|
+
saveSession({ ...session, activeSiteId: siteId });
|
|
4213
|
+
if ((0, import_node_fs2.existsSync)(".neopress") || (0, import_node_fs2.existsSync)(WORKSPACE_CONFIG)) {
|
|
4214
|
+
writeWorkspaceConfig({ ...readProjectConfig(), siteId });
|
|
4215
|
+
}
|
|
4216
|
+
}
|
|
4217
|
+
|
|
4218
|
+
// src/utils/client.ts
|
|
4219
|
+
async function getClientAsync(siteIdOverride) {
|
|
4220
|
+
const siteId = siteIdOverride ?? getSiteId();
|
|
4221
|
+
if (!siteId) {
|
|
4222
|
+
fail("No site selected. Run `neopress sites use <siteId>` or set NEOPRESS_SITE_ID.");
|
|
4223
|
+
}
|
|
4224
|
+
if (process.env.NEOPRESS_ACCESS_TOKEN) {
|
|
4225
|
+
return new NeopressClient({
|
|
4226
|
+
accessToken: process.env.NEOPRESS_ACCESS_TOKEN,
|
|
4227
|
+
siteId,
|
|
4228
|
+
baseUrl: getBaseUrl()
|
|
4229
|
+
});
|
|
4230
|
+
}
|
|
4231
|
+
const accessToken = await getValidAccessToken();
|
|
4232
|
+
if (!accessToken) {
|
|
4233
|
+
fail("Session expired. Run `neopress login` again.");
|
|
4234
|
+
}
|
|
4235
|
+
return new NeopressClient({
|
|
4236
|
+
accessToken,
|
|
4237
|
+
siteId,
|
|
4238
|
+
baseUrl: getBaseUrl()
|
|
4239
|
+
});
|
|
4240
|
+
}
|
|
4241
|
+
|
|
4242
|
+
// src/commands/sites.ts
|
|
4243
|
+
function registerSiteCommands(program3) {
|
|
4244
|
+
const sites = program3.command("sites").description("Manage sites");
|
|
4245
|
+
sites.command("list").description("List accessible sites").action(async () => {
|
|
4246
|
+
const token = process.env.NEOPRESS_ACCESS_TOKEN || await getValidAccessToken() || void 0;
|
|
4247
|
+
if (!token) {
|
|
4248
|
+
fail("Not authenticated. Run `neopress login`.");
|
|
4249
|
+
}
|
|
4250
|
+
const client = new NeopressClient({
|
|
4251
|
+
accessToken: token,
|
|
4252
|
+
siteId: 0,
|
|
4253
|
+
baseUrl: getBaseUrl()
|
|
4254
|
+
});
|
|
4255
|
+
const sitesList = await client.site.list();
|
|
4256
|
+
output(sitesList);
|
|
4257
|
+
});
|
|
4258
|
+
sites.command("use <siteIdOrHandle>").description("Set active site (ID or handle)").action(async (siteIdOrHandle) => {
|
|
4259
|
+
const id = parseInt(siteIdOrHandle, 10);
|
|
4260
|
+
if (!isNaN(id)) {
|
|
4261
|
+
setActiveSiteId(id);
|
|
4262
|
+
ok(`Active site set to ${id}`);
|
|
4263
|
+
return;
|
|
4264
|
+
}
|
|
4265
|
+
const token = process.env.NEOPRESS_ACCESS_TOKEN || await getValidAccessToken() || void 0;
|
|
4266
|
+
if (!token) {
|
|
4267
|
+
fail("Not authenticated. Run `neopress login`.");
|
|
4268
|
+
}
|
|
4269
|
+
const client = new NeopressClient({
|
|
4270
|
+
accessToken: token,
|
|
4271
|
+
siteId: 0,
|
|
4272
|
+
baseUrl: getBaseUrl()
|
|
4273
|
+
});
|
|
4274
|
+
const sitesList = await client.site.list();
|
|
4275
|
+
const match = sitesList.find((s) => s.handle === siteIdOrHandle);
|
|
4276
|
+
if (!match) {
|
|
4277
|
+
fail(`Site "${siteIdOrHandle}" not found. Run \`neopress sites list\` to see available sites.`);
|
|
4278
|
+
}
|
|
4279
|
+
setActiveSiteId(match.id);
|
|
4280
|
+
ok(`Active site set to ${match.id} (${match.handle})`);
|
|
4281
|
+
});
|
|
4282
|
+
sites.command("create").description("Create a new site").option("--name <name>", "Site name").option("--handle <handle>", "Site handle").option("--prompt <prompt>", "Prompt to generate site name/handle").option("--language <locale>", "Default content locale", "en").option("--use", "Set the created site as active").action(async (options) => {
|
|
4283
|
+
if (!options.prompt && !(options.name && options.handle)) {
|
|
4284
|
+
fail("Provide --prompt or both --name and --handle.");
|
|
4285
|
+
}
|
|
4286
|
+
const token = process.env.NEOPRESS_ACCESS_TOKEN || await getValidAccessToken() || void 0;
|
|
4287
|
+
if (!token) {
|
|
4288
|
+
fail("Not authenticated. Run `neopress login`.");
|
|
4289
|
+
}
|
|
4290
|
+
const client = new NeopressClient({
|
|
4291
|
+
accessToken: token,
|
|
4292
|
+
siteId: 0,
|
|
4293
|
+
baseUrl: getBaseUrl()
|
|
4294
|
+
});
|
|
4295
|
+
const site = await client.site.create({
|
|
4296
|
+
siteName: options.name,
|
|
4297
|
+
siteHandle: options.handle,
|
|
4298
|
+
prompt: options.prompt,
|
|
4299
|
+
language: options.language
|
|
4300
|
+
});
|
|
4301
|
+
if (options.use) {
|
|
4302
|
+
setActiveSiteId(site.id);
|
|
4303
|
+
}
|
|
4304
|
+
output(site);
|
|
4305
|
+
if (options.use && !isJsonMode()) ok(`Active site set to ${site.id}`);
|
|
4306
|
+
});
|
|
4307
|
+
sites.command("get").description("Get current site info").action(async () => {
|
|
4308
|
+
const client = await getClientAsync();
|
|
4309
|
+
const site = await client.site.get();
|
|
4310
|
+
output(site);
|
|
4311
|
+
});
|
|
4312
|
+
sites.command("update").description("Update site settings").option("--name <name>", "Site name").option("--locale-config <json>", "Locale config JSON").action(async (options) => {
|
|
4313
|
+
const client = await getClientAsync();
|
|
4314
|
+
const data = {};
|
|
4315
|
+
if (options.name) data.name = options.name;
|
|
4316
|
+
if (options.localeConfig) {
|
|
4317
|
+
try {
|
|
4318
|
+
data.localeConfig = JSON.parse(options.localeConfig);
|
|
4319
|
+
} catch {
|
|
4320
|
+
fail("--locale-config must be valid JSON.");
|
|
4321
|
+
}
|
|
4322
|
+
}
|
|
4323
|
+
if (Object.keys(data).length === 0) {
|
|
4324
|
+
fail("No fields to update. Use --name or --locale-config.");
|
|
4325
|
+
}
|
|
4326
|
+
const site = await client.site.update(data);
|
|
4327
|
+
output(site);
|
|
4328
|
+
});
|
|
4329
|
+
}
|
|
4330
|
+
|
|
4331
|
+
// src/commands/pages.ts
|
|
4332
|
+
var import_node_fs3 = require("fs");
|
|
4333
|
+
function parseJsonInput(input) {
|
|
4334
|
+
if (!input) return void 0;
|
|
4335
|
+
return input.startsWith("@") ? JSON.parse((0, import_node_fs3.readFileSync)(input.slice(1), "utf-8")) : JSON.parse(input);
|
|
4336
|
+
}
|
|
4337
|
+
function parseLocaleList(input) {
|
|
4338
|
+
if (!input) return void 0;
|
|
4339
|
+
if (input.startsWith("@") || input.trim().startsWith("[")) {
|
|
4340
|
+
const parsed = parseJsonInput(input);
|
|
4341
|
+
if (!Array.isArray(parsed) || !parsed.every((item) => typeof item === "string")) {
|
|
4342
|
+
fail("--public-locales must be a comma-separated list or JSON string array.");
|
|
4343
|
+
}
|
|
4344
|
+
return parsed;
|
|
4345
|
+
}
|
|
4346
|
+
return input.split(",").map((locale) => locale.trim()).filter(Boolean);
|
|
4347
|
+
}
|
|
4348
|
+
function mergeQueryConfigIntoDraftMeta(draftMetaInput, queryConfigInput) {
|
|
4349
|
+
const draftMeta = parseJsonInput(draftMetaInput);
|
|
4350
|
+
const queryConfig = parseJsonInput(queryConfigInput);
|
|
4351
|
+
if (draftMeta === void 0 && queryConfig === void 0) {
|
|
4352
|
+
return void 0;
|
|
4353
|
+
}
|
|
4354
|
+
if (queryConfig === void 0) {
|
|
4355
|
+
return draftMeta;
|
|
4356
|
+
}
|
|
4357
|
+
if (draftMeta !== void 0 && (typeof draftMeta !== "object" || draftMeta === null || Array.isArray(draftMeta))) {
|
|
4358
|
+
fail("--draft-meta must be a JSON object when used with --query-config.");
|
|
4359
|
+
}
|
|
4360
|
+
return {
|
|
4361
|
+
...draftMeta || {},
|
|
4362
|
+
queryConfig
|
|
4363
|
+
};
|
|
4364
|
+
}
|
|
4365
|
+
function registerPageCommands(program3) {
|
|
4366
|
+
const pages = program3.command("pages").description("Manage pages");
|
|
4367
|
+
pages.command("list").description("List pages").option("--status <status>", "Filter by status (draft/published)").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "20").action(async (options) => {
|
|
4368
|
+
const client = await getClientAsync();
|
|
4369
|
+
const res = await client.pages.list({
|
|
4370
|
+
status: options.status,
|
|
4371
|
+
page: parseInt(options.page, 10),
|
|
4372
|
+
limit: parseInt(options.limit, 10)
|
|
4373
|
+
});
|
|
4374
|
+
output(res);
|
|
4375
|
+
});
|
|
4376
|
+
pages.command("get <pageId>").description("Get page details").action(async (pageId) => {
|
|
4377
|
+
const client = await getClientAsync();
|
|
4378
|
+
const page = await client.pages.get(parseInt(pageId, 10));
|
|
4379
|
+
output(page);
|
|
4380
|
+
});
|
|
4381
|
+
pages.command("create").description("Create a new page").requiredOption("--path <path>", "Page path (e.g., /about)").option("--title <title>", "Page title").option("--tsx <file>", "TSX file path").option("--i18n <json>", "Page i18n JSON string or @file path").option("--public-locales <locales>", "Comma-separated locale list or JSON string array").option("--metadata <json>", "Page metadata JSON string or @file path").option("--draft-meta <json>", "Draft runtime metadata JSON string or @file path").option("--query-config <json>", "Query config JSON string or @file path; stored as draftMeta.queryConfig").option("--collection <id>", "Collection ID for dynamic pages").option("--type <type>", "Page type (static/dynamic)", "static").action(async (options) => {
|
|
4382
|
+
const client = await getClientAsync();
|
|
4383
|
+
const draftTsx = options.tsx ? (0, import_node_fs3.readFileSync)(options.tsx, "utf-8") : void 0;
|
|
4384
|
+
const draftI18n = parseJsonInput(options.i18n);
|
|
4385
|
+
const draftPublicLocales = parseLocaleList(options.publicLocales);
|
|
4386
|
+
const metadata = parseJsonInput(options.metadata);
|
|
4387
|
+
const draftMeta = mergeQueryConfigIntoDraftMeta(options.draftMeta, options.queryConfig);
|
|
4388
|
+
const collectionId = options.collection ? parseInt(options.collection, 10) : void 0;
|
|
4389
|
+
const page = await client.pages.create({
|
|
4390
|
+
path: options.path,
|
|
4391
|
+
title: options.title,
|
|
4392
|
+
type: options.type,
|
|
4393
|
+
draftTsx,
|
|
4394
|
+
draftI18n,
|
|
4395
|
+
draftPublicLocales,
|
|
4396
|
+
draftMeta,
|
|
4397
|
+
metadata,
|
|
4398
|
+
collectionId
|
|
4399
|
+
});
|
|
4400
|
+
output(page);
|
|
4401
|
+
});
|
|
4402
|
+
pages.command("update <pageId>").description("Update a page").option("--path <path>", "New page path").option("--title <title>", "New title").option("--tsx <file>", "TSX file path").option("--i18n <json>", "Page i18n JSON string or @file path").option("--public-locales <locales>", "Comma-separated locale list or JSON string array").option("--metadata <json>", "Page metadata JSON string or @file path").option("--draft-meta <json>", "Draft runtime metadata JSON string or @file path").option("--query-config <json>", "Query config JSON string or @file path; stored as draftMeta.queryConfig").option("--collection <id>", "Collection ID for dynamic pages").action(async (pageId, options) => {
|
|
4403
|
+
const client = await getClientAsync();
|
|
4404
|
+
const data = {};
|
|
4405
|
+
if (options.path) data.path = options.path;
|
|
4406
|
+
if (options.title) data.title = options.title;
|
|
4407
|
+
if (options.tsx) data.draftTsx = (0, import_node_fs3.readFileSync)(options.tsx, "utf-8");
|
|
4408
|
+
if (options.i18n) data.draftI18n = parseJsonInput(options.i18n);
|
|
4409
|
+
if (options.publicLocales) data.draftPublicLocales = parseLocaleList(options.publicLocales);
|
|
4410
|
+
if (options.metadata) data.metadata = parseJsonInput(options.metadata);
|
|
4411
|
+
if (options.draftMeta || options.queryConfig) {
|
|
4412
|
+
data.draftMeta = mergeQueryConfigIntoDraftMeta(options.draftMeta, options.queryConfig);
|
|
4413
|
+
}
|
|
4414
|
+
if (options.collection) data.collectionId = parseInt(options.collection, 10);
|
|
4415
|
+
if (Object.keys(data).length === 0) {
|
|
4416
|
+
fail("No fields to update. Use --path, --title, --tsx, --i18n, --public-locales, --metadata, --draft-meta, --query-config, or --collection.");
|
|
4417
|
+
}
|
|
4418
|
+
const page = await client.pages.update(parseInt(pageId, 10), data);
|
|
4419
|
+
output(page);
|
|
4420
|
+
});
|
|
4421
|
+
pages.command("delete <pageId>").description("Delete a page").action(async (pageId) => {
|
|
4422
|
+
const client = await getClientAsync();
|
|
4423
|
+
await client.pages.delete(parseInt(pageId, 10));
|
|
4424
|
+
ok(`Page ${pageId} deleted`);
|
|
4425
|
+
});
|
|
4426
|
+
pages.command("compile <pageId>").description("Validate TSX compilation").action(async (pageId) => {
|
|
4427
|
+
const client = await getClientAsync();
|
|
4428
|
+
const result = await client.pages.compile(parseInt(pageId, 10));
|
|
4429
|
+
output(result);
|
|
4430
|
+
});
|
|
4431
|
+
}
|
|
4432
|
+
|
|
4433
|
+
// src/commands/collections.ts
|
|
4434
|
+
var import_node_fs4 = require("fs");
|
|
4435
|
+
function parseJsonInput2(input) {
|
|
4436
|
+
if (!input) return void 0;
|
|
4437
|
+
return input.startsWith("@") ? JSON.parse((0, import_node_fs4.readFileSync)(input.slice(1), "utf-8")) : JSON.parse(input);
|
|
4438
|
+
}
|
|
4439
|
+
function registerCollectionCommands(program3) {
|
|
4440
|
+
const collections = program3.command("collections").description("Manage collections");
|
|
4441
|
+
collections.command("list").description("List collections").action(async () => {
|
|
4442
|
+
const client = await getClientAsync();
|
|
4443
|
+
const data = await client.collections.list();
|
|
4444
|
+
output(data);
|
|
4445
|
+
});
|
|
4446
|
+
collections.command("get <collectionId>").description("Get collection details").action(async (collectionId) => {
|
|
4447
|
+
const client = await getClientAsync();
|
|
4448
|
+
const data = await client.collections.get(parseInt(collectionId, 10));
|
|
4449
|
+
output(data);
|
|
4450
|
+
});
|
|
4451
|
+
collections.command("create").description("Create a collection").requiredOption("--name <name>", "Collection name").option("--schema <json>", "Draft schema as JSON string or @file path").action(async (options) => {
|
|
4452
|
+
const client = await getClientAsync();
|
|
4453
|
+
const data = await client.collections.create({
|
|
4454
|
+
name: options.name,
|
|
4455
|
+
draftSchema: parseJsonInput2(options.schema)
|
|
4456
|
+
});
|
|
4457
|
+
output(data);
|
|
4458
|
+
});
|
|
4459
|
+
collections.command("update <collectionId>").description("Update a collection").option("--name <name>", "Collection name").option("--schema <json>", "Draft schema as JSON string or @file path").action(async (collectionId, options) => {
|
|
4460
|
+
const client = await getClientAsync();
|
|
4461
|
+
const data = {};
|
|
4462
|
+
if (options.name) data.name = options.name;
|
|
4463
|
+
if (options.schema) data.draftSchema = parseJsonInput2(options.schema);
|
|
4464
|
+
if (Object.keys(data).length === 0) {
|
|
4465
|
+
fail("No fields to update. Use --name or --schema.");
|
|
4466
|
+
}
|
|
4467
|
+
const collection = await client.collections.update(
|
|
4468
|
+
parseInt(collectionId, 10),
|
|
4469
|
+
data
|
|
4470
|
+
);
|
|
4471
|
+
output(collection);
|
|
4472
|
+
});
|
|
4473
|
+
collections.command("delete <collectionId>").description("Delete a collection").action(async (collectionId) => {
|
|
4474
|
+
const client = await getClientAsync();
|
|
4475
|
+
await client.collections.delete(parseInt(collectionId, 10));
|
|
4476
|
+
ok(`Collection ${collectionId} deleted`);
|
|
4477
|
+
});
|
|
4478
|
+
}
|
|
4479
|
+
|
|
4480
|
+
// src/commands/entries.ts
|
|
4481
|
+
var import_node_fs5 = require("fs");
|
|
4482
|
+
function registerEntryCommands(program3) {
|
|
4483
|
+
const entries = program3.command("entries").description("Manage entries");
|
|
4484
|
+
entries.command("list").description("List entries in a collection").requiredOption("--collection <id>", "Collection ID").option("--status <status>", "Filter by status").option("--locale <locale>", "Filter by locale").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "20").action(async (options) => {
|
|
4485
|
+
const client = await getClientAsync();
|
|
4486
|
+
const res = await client.entries.list(parseInt(options.collection, 10), {
|
|
4487
|
+
status: options.status,
|
|
4488
|
+
locale: options.locale,
|
|
4489
|
+
page: parseInt(options.page, 10),
|
|
4490
|
+
limit: parseInt(options.limit, 10)
|
|
4491
|
+
});
|
|
4492
|
+
output(res);
|
|
4493
|
+
});
|
|
4494
|
+
entries.command("get <entryId>").description("Get entry details").action(async (entryId) => {
|
|
4495
|
+
const client = await getClientAsync();
|
|
4496
|
+
const data = await client.entries.get(parseInt(entryId, 10));
|
|
4497
|
+
output(data);
|
|
4498
|
+
});
|
|
4499
|
+
entries.command("create").description("Create an entry").requiredOption("--collection <id>", "Collection ID").option("--data <json>", "Entry data as JSON string or @file path").option("--title <title>", "Entry title").option("--slug <slug>", "Entry slug").option("--locale <locale>", "Entry locale").action(async (options) => {
|
|
4500
|
+
const client = await getClientAsync();
|
|
4501
|
+
let data;
|
|
4502
|
+
if (options.data?.startsWith("@")) {
|
|
4503
|
+
data = JSON.parse((0, import_node_fs5.readFileSync)(options.data.slice(1), "utf-8"));
|
|
4504
|
+
} else if (options.data) {
|
|
4505
|
+
data = JSON.parse(options.data);
|
|
4506
|
+
} else {
|
|
4507
|
+
fail("--data is required. Use JSON string or @filepath.");
|
|
4508
|
+
}
|
|
4509
|
+
const entry = await client.entries.create(parseInt(options.collection, 10), {
|
|
4510
|
+
data,
|
|
4511
|
+
title: options.title,
|
|
4512
|
+
slug: options.slug,
|
|
4513
|
+
locale: options.locale
|
|
4514
|
+
});
|
|
4515
|
+
output(entry);
|
|
4516
|
+
});
|
|
4517
|
+
entries.command("update <entryId>").description("Update an entry").option("--data <json>", "Entry data as JSON string or @file path").option("--title <title>", "Entry title").option("--slug <slug>", "Entry slug").option("--locale <locale>", "Entry locale").action(async (entryId, options) => {
|
|
4518
|
+
const client = await getClientAsync();
|
|
4519
|
+
const updateData = {};
|
|
4520
|
+
if (options.data) {
|
|
4521
|
+
updateData.data = options.data.startsWith("@") ? JSON.parse((0, import_node_fs5.readFileSync)(options.data.slice(1), "utf-8")) : JSON.parse(options.data);
|
|
4522
|
+
}
|
|
4523
|
+
if (options.title) updateData.title = options.title;
|
|
4524
|
+
if (options.slug) updateData.slug = options.slug;
|
|
4525
|
+
if (options.locale) updateData.locale = options.locale;
|
|
4526
|
+
if (Object.keys(updateData).length === 0) {
|
|
4527
|
+
fail("No fields to update.");
|
|
4528
|
+
}
|
|
4529
|
+
const entry = await client.entries.update(parseInt(entryId, 10), updateData);
|
|
4530
|
+
output(entry);
|
|
4531
|
+
});
|
|
4532
|
+
entries.command("delete <entryId>").description("Delete an entry").action(async (entryId) => {
|
|
4533
|
+
const client = await getClientAsync();
|
|
4534
|
+
await client.entries.delete(parseInt(entryId, 10));
|
|
4535
|
+
ok(`Entry ${entryId} deleted`);
|
|
4536
|
+
});
|
|
4537
|
+
entries.command("publish <entryId>").description("Publish an entry").action(async (entryId) => {
|
|
4538
|
+
const client = await getClientAsync();
|
|
4539
|
+
const result = await client.entries.publish(parseInt(entryId, 10));
|
|
4540
|
+
output(result);
|
|
4541
|
+
});
|
|
4542
|
+
entries.command("unpublish <entryId>").description("Unpublish an entry").action(async (entryId) => {
|
|
4543
|
+
const client = await getClientAsync();
|
|
4544
|
+
const result = await client.entries.unpublish(parseInt(entryId, 10));
|
|
4545
|
+
output(result);
|
|
4546
|
+
});
|
|
4547
|
+
}
|
|
4548
|
+
|
|
4549
|
+
// src/commands/forms.ts
|
|
4550
|
+
var import_node_fs6 = require("fs");
|
|
4551
|
+
function parseJsonInput3(input) {
|
|
4552
|
+
if (!input) return void 0;
|
|
4553
|
+
return input.startsWith("@") ? JSON.parse((0, import_node_fs6.readFileSync)(input.slice(1), "utf-8")) : JSON.parse(input);
|
|
4554
|
+
}
|
|
4555
|
+
function registerFormCommands(program3) {
|
|
4556
|
+
const forms = program3.command("forms").description("Manage forms");
|
|
4557
|
+
forms.command("list").description("List forms").action(async () => {
|
|
4558
|
+
const client = await getClientAsync();
|
|
4559
|
+
const data = await client.forms.list();
|
|
4560
|
+
output(data);
|
|
4561
|
+
});
|
|
4562
|
+
forms.command("get <formId>").description("Get form details").action(async (formId) => {
|
|
4563
|
+
const client = await getClientAsync();
|
|
4564
|
+
const data = await client.forms.get(parseInt(formId, 10));
|
|
4565
|
+
output(data);
|
|
4566
|
+
});
|
|
4567
|
+
forms.command("create").description("Create a form").requiredOption("--name <name>", "Form name").option("--schema <json>", "Draft form schema JSON string or @file path").option("--layout <json>", "Draft form layout JSON string or @file path").option("--style <json>", "Draft form style JSON string or @file path").option("--i18n <json>", "Draft form i18n JSON string or @file path").option("--settings <json>", "Form settings JSON string or @file path").action(async (options) => {
|
|
4568
|
+
const client = await getClientAsync();
|
|
4569
|
+
const data = await client.forms.create({
|
|
4570
|
+
name: options.name,
|
|
4571
|
+
draftSchema: parseJsonInput3(options.schema),
|
|
4572
|
+
draftLayout: parseJsonInput3(options.layout),
|
|
4573
|
+
draftStyle: parseJsonInput3(options.style),
|
|
4574
|
+
draftI18n: parseJsonInput3(options.i18n),
|
|
4575
|
+
settings: parseJsonInput3(options.settings)
|
|
4576
|
+
});
|
|
4577
|
+
output(data);
|
|
4578
|
+
});
|
|
4579
|
+
forms.command("update <formId>").description("Update a form").option("--name <name>", "Form name").option("--schema <json>", "Draft form schema JSON string or @file path").option("--layout <json>", "Draft form layout JSON string or @file path").option("--style <json>", "Draft form style JSON string or @file path").option("--i18n <json>", "Draft form i18n JSON string or @file path").option("--settings <json>", "Form settings JSON string or @file path").action(async (formId, options) => {
|
|
4580
|
+
const client = await getClientAsync();
|
|
4581
|
+
const data = {};
|
|
4582
|
+
if (options.name) data.name = options.name;
|
|
4583
|
+
if (options.schema) data.draftSchema = parseJsonInput3(options.schema);
|
|
4584
|
+
if (options.layout) data.draftLayout = parseJsonInput3(options.layout);
|
|
4585
|
+
if (options.style) data.draftStyle = parseJsonInput3(options.style);
|
|
4586
|
+
if (options.i18n) data.draftI18n = parseJsonInput3(options.i18n);
|
|
4587
|
+
if (options.settings) data.settings = parseJsonInput3(options.settings);
|
|
4588
|
+
if (Object.keys(data).length === 0) {
|
|
4589
|
+
fail("No fields to update. Use --name, --schema, --layout, --style, --i18n, or --settings.");
|
|
4590
|
+
}
|
|
4591
|
+
const updated = await client.forms.update(parseInt(formId, 10), data);
|
|
4592
|
+
output(updated);
|
|
4593
|
+
});
|
|
4594
|
+
forms.command("publish <formId>").description("Publish a form").action(async (formId) => {
|
|
4595
|
+
const client = await getClientAsync();
|
|
4596
|
+
const result = await client.forms.publish(parseInt(formId, 10));
|
|
4597
|
+
output(result);
|
|
4598
|
+
});
|
|
4599
|
+
forms.command("responses <formId>").description("List form responses").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "20").action(async (formId, options) => {
|
|
4600
|
+
const client = await getClientAsync();
|
|
4601
|
+
const res = await client.forms.listResponses(parseInt(formId, 10), {
|
|
4602
|
+
page: parseInt(options.page, 10),
|
|
4603
|
+
limit: parseInt(options.limit, 10)
|
|
4604
|
+
});
|
|
4605
|
+
output(res);
|
|
4606
|
+
});
|
|
4607
|
+
forms.command("delete <formId>").description("Delete a form").action(async (formId) => {
|
|
4608
|
+
const client = await getClientAsync();
|
|
4609
|
+
await client.forms.delete(parseInt(formId, 10));
|
|
4610
|
+
ok(`Form ${formId} deleted`);
|
|
4611
|
+
});
|
|
4612
|
+
}
|
|
4613
|
+
|
|
4614
|
+
// src/commands/assets.ts
|
|
4615
|
+
var import_node_fs7 = require("fs");
|
|
4616
|
+
var import_node_path3 = require("path");
|
|
4617
|
+
function registerAssetCommands(program3) {
|
|
4618
|
+
const assets = program3.command("assets").description("Manage assets");
|
|
4619
|
+
assets.command("list").description("List assets").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "20").action(async (options) => {
|
|
4620
|
+
const client = await getClientAsync();
|
|
4621
|
+
const res = await client.assets.list({
|
|
4622
|
+
page: parseInt(options.page, 10),
|
|
4623
|
+
limit: parseInt(options.limit, 10)
|
|
4624
|
+
});
|
|
4625
|
+
output(res);
|
|
4626
|
+
});
|
|
4627
|
+
assets.command("upload <filePath>").description("Upload a file (presign \u2192 upload \u2192 register)").option("--folder <folder>", "Target folder path").action(async (filePath, options) => {
|
|
4628
|
+
const client = await getClientAsync();
|
|
4629
|
+
const fileName = (0, import_node_path3.basename)(filePath);
|
|
4630
|
+
const stats = (0, import_node_fs7.statSync)(filePath);
|
|
4631
|
+
const fileBuffer = (0, import_node_fs7.readFileSync)(filePath);
|
|
4632
|
+
const ext = fileName.split(".").pop()?.toLowerCase() || "";
|
|
4633
|
+
const contentTypeMap = {
|
|
4634
|
+
png: "image/png",
|
|
4635
|
+
jpg: "image/jpeg",
|
|
4636
|
+
jpeg: "image/jpeg",
|
|
4637
|
+
gif: "image/gif",
|
|
4638
|
+
webp: "image/webp",
|
|
4639
|
+
svg: "image/svg+xml",
|
|
4640
|
+
pdf: "application/pdf",
|
|
4641
|
+
mp4: "video/mp4"
|
|
4642
|
+
};
|
|
4643
|
+
const contentType = contentTypeMap[ext] || "application/octet-stream";
|
|
4644
|
+
const folder = options.folder || "uploads";
|
|
4645
|
+
const fileKey = `${folder}/${Date.now()}-${fileName}`;
|
|
4646
|
+
const { presignedUrl, publicUrl } = await client.assets.presign({
|
|
4647
|
+
fileKey,
|
|
4648
|
+
contentType,
|
|
4649
|
+
contentLength: stats.size
|
|
4650
|
+
});
|
|
4651
|
+
const uploadRes = await fetch(presignedUrl, {
|
|
4652
|
+
method: "PUT",
|
|
4653
|
+
headers: { "Content-Type": contentType },
|
|
4654
|
+
body: fileBuffer
|
|
4655
|
+
});
|
|
4656
|
+
if (!uploadRes.ok) {
|
|
4657
|
+
fail(`Upload failed: ${uploadRes.statusText}`);
|
|
4658
|
+
}
|
|
4659
|
+
const asset = await client.assets.register({
|
|
4660
|
+
assetUrl: publicUrl,
|
|
4661
|
+
displayName: fileName,
|
|
4662
|
+
mimeType: contentType,
|
|
4663
|
+
size: stats.size,
|
|
4664
|
+
folderPath: options.folder || null
|
|
4665
|
+
});
|
|
4666
|
+
output(asset);
|
|
4667
|
+
if (!isJsonMode()) ok(`Uploaded ${fileName} \u2192 ${publicUrl}`);
|
|
4668
|
+
});
|
|
4669
|
+
}
|
|
4670
|
+
|
|
4671
|
+
// src/commands/publish.ts
|
|
4672
|
+
function registerPublishCommands(program3) {
|
|
4673
|
+
const publish = program3.command("publish").description("Publish site or preview changes").action(async () => {
|
|
4674
|
+
const client = await getClientAsync();
|
|
4675
|
+
const result = await client.publish.site();
|
|
4676
|
+
output(result);
|
|
4677
|
+
if (!isJsonMode()) ok("Site published");
|
|
4678
|
+
});
|
|
4679
|
+
publish.command("preview").description("Preview pending publish changes").action(async () => {
|
|
4680
|
+
const client = await getClientAsync();
|
|
4681
|
+
const result = await client.publish.preview();
|
|
4682
|
+
output(result);
|
|
4683
|
+
});
|
|
4684
|
+
}
|
|
4685
|
+
|
|
4686
|
+
// src/commands/redirects.ts
|
|
4687
|
+
function registerRedirectCommands(program3) {
|
|
4688
|
+
const redirects = program3.command("redirects").description("Manage redirect rules");
|
|
4689
|
+
redirects.command("list").description("List redirect rules").action(async () => {
|
|
4690
|
+
const client = await getClientAsync();
|
|
4691
|
+
const data = await client.redirects.list();
|
|
4692
|
+
output(data);
|
|
4693
|
+
});
|
|
4694
|
+
redirects.command("create").description("Create a redirect rule").requiredOption("--source <path>", "Source path").requiredOption("--dest <path>", "Destination path").option("--type <type>", "Redirect type (307/308)", "307").action(async (options) => {
|
|
4695
|
+
const client = await getClientAsync();
|
|
4696
|
+
const rule = await client.redirects.create({
|
|
4697
|
+
source: options.source,
|
|
4698
|
+
destination: options.dest,
|
|
4699
|
+
redirectType: parseInt(options.type, 10)
|
|
4700
|
+
});
|
|
4701
|
+
output(rule);
|
|
4702
|
+
});
|
|
4703
|
+
redirects.command("delete <ruleId>").description("Delete a redirect rule").action(async (ruleId) => {
|
|
4704
|
+
const client = await getClientAsync();
|
|
4705
|
+
await client.redirects.delete(parseInt(ruleId, 10));
|
|
4706
|
+
ok(`Redirect rule ${ruleId} deleted`);
|
|
4707
|
+
});
|
|
4708
|
+
}
|
|
4709
|
+
|
|
4710
|
+
// src/commands/layout.ts
|
|
4711
|
+
var import_node_fs8 = require("fs");
|
|
4712
|
+
function registerLayoutCommands(program3) {
|
|
4713
|
+
const layout = program3.command("layout").description("Manage site layout");
|
|
4714
|
+
layout.command("get").description("Get current site layout").action(async () => {
|
|
4715
|
+
const client = await getClientAsync();
|
|
4716
|
+
const data = await client.site.getLayout();
|
|
4717
|
+
output(data);
|
|
4718
|
+
});
|
|
4719
|
+
layout.command("update").description("Update site layout").option("--tsx <file>", "Layout TSX file path").option("--not-found-tsx <file>", "Not-found page TSX file path").option("--global-css <file>", "Global CSS file path").action(async (options) => {
|
|
4720
|
+
const client = await getClientAsync();
|
|
4721
|
+
const data = {};
|
|
4722
|
+
if (options.tsx) data.draftTsx = (0, import_node_fs8.readFileSync)(options.tsx, "utf-8");
|
|
4723
|
+
if (options.notFoundTsx) data.draftNotFoundTsx = (0, import_node_fs8.readFileSync)(options.notFoundTsx, "utf-8");
|
|
4724
|
+
if (options.globalCss) data.draftGlobalCss = (0, import_node_fs8.readFileSync)(options.globalCss, "utf-8");
|
|
4725
|
+
if (Object.keys(data).length === 0) {
|
|
4726
|
+
fail("No fields to update. Use --tsx, --not-found-tsx, or --global-css.");
|
|
4727
|
+
}
|
|
4728
|
+
const updated = await client.site.updateLayout(data);
|
|
4729
|
+
output(updated);
|
|
4730
|
+
});
|
|
4731
|
+
}
|
|
4732
|
+
|
|
4733
|
+
// src/commands/entry-references.ts
|
|
4734
|
+
function registerEntryReferenceCommands(program3) {
|
|
4735
|
+
const refs = program3.command("entry-references").description("Manage entry reference relations");
|
|
4736
|
+
refs.command("list").description("List entry references").option("--from-entry <id>", "Filter by source entry ID").option("--to-entry <id>", "Filter by target entry ID").action(async (options) => {
|
|
4737
|
+
const client = await getClientAsync();
|
|
4738
|
+
const data = await client.entryReferences.list({
|
|
4739
|
+
fromEntryId: options.fromEntry ? parseInt(options.fromEntry, 10) : void 0,
|
|
4740
|
+
toEntryId: options.toEntry ? parseInt(options.toEntry, 10) : void 0
|
|
4741
|
+
});
|
|
4742
|
+
output(data);
|
|
4743
|
+
});
|
|
4744
|
+
refs.command("create").description("Create an entry reference").requiredOption("--from-entry <id>", "Source entry ID").requiredOption("--to-entry <id>", "Target entry ID").requiredOption("--field <key>", "Reference field key from the source collection schema").action(async (options) => {
|
|
4745
|
+
const client = await getClientAsync();
|
|
4746
|
+
const fromEntryId = parseInt(options.fromEntry, 10);
|
|
4747
|
+
const toEntryId = parseInt(options.toEntry, 10);
|
|
4748
|
+
if (Number.isNaN(fromEntryId) || Number.isNaN(toEntryId)) {
|
|
4749
|
+
fail("--from-entry and --to-entry must be numeric entry IDs.");
|
|
4750
|
+
}
|
|
4751
|
+
const data = await client.entryReferences.create({
|
|
4752
|
+
fromEntryId,
|
|
4753
|
+
toEntryId,
|
|
4754
|
+
fieldKey: options.field
|
|
4755
|
+
});
|
|
4756
|
+
output(data);
|
|
4757
|
+
});
|
|
4758
|
+
refs.command("delete <referenceId>").description("Delete an entry reference").action(async (referenceId) => {
|
|
4759
|
+
const client = await getClientAsync();
|
|
4760
|
+
await client.entryReferences.delete(parseInt(referenceId, 10));
|
|
4761
|
+
ok(`Entry reference ${referenceId} deleted`);
|
|
4762
|
+
});
|
|
4763
|
+
}
|
|
4764
|
+
|
|
4765
|
+
// src/commands/analytics.ts
|
|
4766
|
+
var import_node_fs9 = require("fs");
|
|
4767
|
+
function parseJsonObjectInput(input) {
|
|
4768
|
+
if (!input) return void 0;
|
|
4769
|
+
const parsed = input.startsWith("@") ? JSON.parse((0, import_node_fs9.readFileSync)(input.slice(1), "utf-8")) : JSON.parse(input);
|
|
4770
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
4771
|
+
fail("--params must be a JSON object");
|
|
4772
|
+
}
|
|
4773
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
4774
|
+
if (!["string", "number", "boolean"].includes(typeof value)) {
|
|
4775
|
+
fail(`--params.${key} must be a string, number, or boolean`);
|
|
4776
|
+
}
|
|
4777
|
+
}
|
|
4778
|
+
return parsed;
|
|
4779
|
+
}
|
|
4780
|
+
function parseOptionalInt(raw, optionName) {
|
|
4781
|
+
if (!raw) return void 0;
|
|
4782
|
+
const value = Number(raw);
|
|
4783
|
+
if (!Number.isInteger(value) || value < 1) {
|
|
4784
|
+
fail(`${optionName} must be a positive integer`);
|
|
4785
|
+
}
|
|
4786
|
+
return value;
|
|
4787
|
+
}
|
|
4788
|
+
function addDateOptions(command) {
|
|
4789
|
+
return command.option("--date-from <date>", "Start date in YYYY-MM-DD").option("--date-to <date>", "End date in YYYY-MM-DD").option("--timezone <timezone>", "IANA timezone, e.g. Asia/Seoul").option("--limit <n>", "Maximum rows to return").option("--params <json>", "Additional analytics params as JSON object or @file path");
|
|
4790
|
+
}
|
|
4791
|
+
function readDateOptions(options) {
|
|
4792
|
+
return {
|
|
4793
|
+
dateFrom: options.dateFrom,
|
|
4794
|
+
dateTo: options.dateTo,
|
|
4795
|
+
timezone: options.timezone,
|
|
4796
|
+
limit: parseOptionalInt(options.limit, "--limit"),
|
|
4797
|
+
params: parseJsonObjectInput(options.params)
|
|
4798
|
+
};
|
|
4799
|
+
}
|
|
4800
|
+
function parseSearchConsoleDimensions(raw) {
|
|
4801
|
+
const valid = /* @__PURE__ */ new Set(["query", "page", "country", "device"]);
|
|
4802
|
+
const dimensions = raw.split(",").map((dimension) => dimension.trim()).filter(Boolean);
|
|
4803
|
+
for (const dimension of dimensions) {
|
|
4804
|
+
if (!valid.has(dimension)) {
|
|
4805
|
+
fail(`Invalid Search Console dimension: ${dimension}`);
|
|
4806
|
+
}
|
|
4807
|
+
}
|
|
4808
|
+
return dimensions;
|
|
4809
|
+
}
|
|
4810
|
+
function registerAnalyticsCommands(program3) {
|
|
4811
|
+
const analytics = program3.command("analytics").description("Read site analytics and Search Console data");
|
|
4812
|
+
addDateOptions(
|
|
4813
|
+
analytics.command("query").description("Run an allowed analytics pipe").requiredOption("--pipe <pipe>", "Analytics pipe name")
|
|
4814
|
+
).action(async (options) => {
|
|
4815
|
+
const client = await getClientAsync();
|
|
4816
|
+
const data = await client.analytics.query({
|
|
4817
|
+
pipe: options.pipe,
|
|
4818
|
+
...readDateOptions(options)
|
|
4819
|
+
});
|
|
4820
|
+
output(data);
|
|
4821
|
+
});
|
|
4822
|
+
addDateOptions(
|
|
4823
|
+
analytics.command("pageviews").description("Get pageview timeseries data")
|
|
4824
|
+
).action(async (options) => {
|
|
4825
|
+
const client = await getClientAsync();
|
|
4826
|
+
output(await client.analytics.pageviews(readDateOptions(options)));
|
|
4827
|
+
});
|
|
4828
|
+
addDateOptions(
|
|
4829
|
+
analytics.command("summary").description("Get engagement summary")
|
|
4830
|
+
).action(async (options) => {
|
|
4831
|
+
const client = await getClientAsync();
|
|
4832
|
+
output(await client.analytics.summary(readDateOptions(options)));
|
|
4833
|
+
});
|
|
4834
|
+
addDateOptions(
|
|
4835
|
+
analytics.command("pages").description("Get top pages")
|
|
4836
|
+
).action(async (options) => {
|
|
4837
|
+
const client = await getClientAsync();
|
|
4838
|
+
output(await client.analytics.topPages(readDateOptions(options)));
|
|
4839
|
+
});
|
|
4840
|
+
addDateOptions(
|
|
4841
|
+
analytics.command("sources").description("Get traffic sources")
|
|
4842
|
+
).action(async (options) => {
|
|
4843
|
+
const client = await getClientAsync();
|
|
4844
|
+
output(await client.analytics.trafficSources(readDateOptions(options)));
|
|
4845
|
+
});
|
|
4846
|
+
addDateOptions(
|
|
4847
|
+
analytics.command("forms").description("Get form analytics")
|
|
4848
|
+
).action(async (options) => {
|
|
4849
|
+
const client = await getClientAsync();
|
|
4850
|
+
output(await client.analytics.formAnalytics(readDateOptions(options)));
|
|
4851
|
+
});
|
|
4852
|
+
addDateOptions(
|
|
4853
|
+
analytics.command("crawlers").description("Get AI crawler summary")
|
|
4854
|
+
).action(async (options) => {
|
|
4855
|
+
const client = await getClientAsync();
|
|
4856
|
+
output(await client.analytics.crawlerSummary(readDateOptions(options)));
|
|
4857
|
+
});
|
|
4858
|
+
analytics.command("search-console").description("Query Google Search Console performance data").requiredOption("--date-from <date>", "Start date in YYYY-MM-DD").requiredOption("--date-to <date>", "End date in YYYY-MM-DD").option("--dimensions <csv>", "CSV dimensions: query,page,country,device", "query").option("--query-filter <query>", "Exact query filter").option("--page-filter <url>", "Exact page URL filter").option("--row-limit <n>", "Maximum rows to return", "100").action(async (options) => {
|
|
4859
|
+
const client = await getClientAsync();
|
|
4860
|
+
const data = await client.analytics.searchConsole({
|
|
4861
|
+
dateFrom: options.dateFrom,
|
|
4862
|
+
dateTo: options.dateTo,
|
|
4863
|
+
dimensions: parseSearchConsoleDimensions(String(options.dimensions)),
|
|
4864
|
+
queryFilter: options.queryFilter,
|
|
4865
|
+
pageFilter: options.pageFilter,
|
|
4866
|
+
rowLimit: parseOptionalInt(options.rowLimit, "--row-limit")
|
|
4867
|
+
});
|
|
4868
|
+
output(data);
|
|
4869
|
+
});
|
|
4870
|
+
}
|
|
4871
|
+
|
|
4872
|
+
// src/bin.ts
|
|
4873
|
+
var program2 = new Command();
|
|
4874
|
+
program2.name("neopress").description("Neopress CLI \u2014 manage your site from the terminal").version("0.1.0").option("--json", "Output in JSON format (for AI tools and pipes)").option("--no-input", "Non-interactive mode").hook("preAction", (thisCommand) => {
|
|
4875
|
+
const opts = thisCommand.optsWithGlobals();
|
|
4876
|
+
if (opts.json) setJsonMode(true);
|
|
4877
|
+
});
|
|
4878
|
+
registerAuthCommands(program2);
|
|
4879
|
+
registerSiteCommands(program2);
|
|
4880
|
+
registerPageCommands(program2);
|
|
4881
|
+
registerCollectionCommands(program2);
|
|
4882
|
+
registerEntryCommands(program2);
|
|
4883
|
+
registerFormCommands(program2);
|
|
4884
|
+
registerAssetCommands(program2);
|
|
4885
|
+
registerPublishCommands(program2);
|
|
4886
|
+
registerRedirectCommands(program2);
|
|
4887
|
+
registerLayoutCommands(program2);
|
|
4888
|
+
registerEntryReferenceCommands(program2);
|
|
4889
|
+
registerAnalyticsCommands(program2);
|
|
4890
|
+
program2.parseAsync(process.argv).catch((err) => {
|
|
4891
|
+
if (err?.code) {
|
|
4892
|
+
console.error(JSON.stringify({ ok: false, error: err.message, code: err.code }));
|
|
4893
|
+
} else {
|
|
4894
|
+
console.error(err.message || err);
|
|
4895
|
+
}
|
|
4896
|
+
process.exit(1);
|
|
4897
|
+
});
|