@chilfish/gallery-dl-instagram 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.
@@ -0,0 +1,3160 @@
1
+ #!/usr/bin/env node
2
+ import { a as extractCsrfFromCookies, i as createWebClient, n as createLogger, r as createStorage, t as createHttpClient } from "../adapter-Bt86eL1R.mjs";
3
+ import { F as ConfigManager, M as DownloadJob, P as PrintJob, c as InstagramStoriesExtractor, d as InstagramUserExtractor, i as InstagramPostExtractor, l as InstagramTagExtractor, n as InstagramHighlightsExtractor, s as InstagramSavedExtractor } from "../extractors-Byw-2lPL.mjs";
4
+ import { createRequire } from "module";
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
28
+ //#endregion
29
+ //#region node_modules/commander/lib/error.js
30
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
31
+ /**
32
+ * CommanderError class
33
+ */
34
+ var CommanderError = class extends Error {
35
+ /**
36
+ * Constructs the CommanderError class
37
+ * @param {number} exitCode suggested exit code which could be used with process.exit
38
+ * @param {string} code an id string representing the error
39
+ * @param {string} message human-readable description of the error
40
+ */
41
+ constructor(exitCode, code, message) {
42
+ super(message);
43
+ Error.captureStackTrace(this, this.constructor);
44
+ this.name = this.constructor.name;
45
+ this.code = code;
46
+ this.exitCode = exitCode;
47
+ this.nestedError = void 0;
48
+ }
49
+ };
50
+ /**
51
+ * InvalidArgumentError class
52
+ */
53
+ var InvalidArgumentError = class extends CommanderError {
54
+ /**
55
+ * Constructs the InvalidArgumentError class
56
+ * @param {string} [message] explanation of why argument is invalid
57
+ */
58
+ constructor(message) {
59
+ super(1, "commander.invalidArgument", message);
60
+ Error.captureStackTrace(this, this.constructor);
61
+ this.name = this.constructor.name;
62
+ }
63
+ };
64
+ exports.CommanderError = CommanderError;
65
+ exports.InvalidArgumentError = InvalidArgumentError;
66
+ }));
67
+ //#endregion
68
+ //#region node_modules/commander/lib/argument.js
69
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
70
+ const { InvalidArgumentError } = require_error();
71
+ var Argument = class {
72
+ /**
73
+ * Initialize a new command argument with the given name and description.
74
+ * The default is that the argument is required, and you can explicitly
75
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
76
+ *
77
+ * @param {string} name
78
+ * @param {string} [description]
79
+ */
80
+ constructor(name, description) {
81
+ this.description = description || "";
82
+ this.variadic = false;
83
+ this.parseArg = void 0;
84
+ this.defaultValue = void 0;
85
+ this.defaultValueDescription = void 0;
86
+ this.argChoices = void 0;
87
+ switch (name[0]) {
88
+ case "<":
89
+ this.required = true;
90
+ this._name = name.slice(1, -1);
91
+ break;
92
+ case "[":
93
+ this.required = false;
94
+ this._name = name.slice(1, -1);
95
+ break;
96
+ default:
97
+ this.required = true;
98
+ this._name = name;
99
+ break;
100
+ }
101
+ if (this._name.endsWith("...")) {
102
+ this.variadic = true;
103
+ this._name = this._name.slice(0, -3);
104
+ }
105
+ }
106
+ /**
107
+ * Return argument name.
108
+ *
109
+ * @return {string}
110
+ */
111
+ name() {
112
+ return this._name;
113
+ }
114
+ /**
115
+ * @package
116
+ */
117
+ _collectValue(value, previous) {
118
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
119
+ previous.push(value);
120
+ return previous;
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)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
154
+ if (this.variadic) return this._collectValue(arg, previous);
155
+ return arg;
156
+ };
157
+ return this;
158
+ }
159
+ /**
160
+ * Make argument required.
161
+ *
162
+ * @returns {Argument}
163
+ */
164
+ argRequired() {
165
+ this.required = true;
166
+ return this;
167
+ }
168
+ /**
169
+ * Make argument optional.
170
+ *
171
+ * @returns {Argument}
172
+ */
173
+ argOptional() {
174
+ this.required = false;
175
+ return this;
176
+ }
177
+ };
178
+ /**
179
+ * Takes an argument and returns its human readable equivalent for help usage.
180
+ *
181
+ * @param {Argument} arg
182
+ * @return {string}
183
+ * @private
184
+ */
185
+ function humanReadableArgName(arg) {
186
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
187
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
188
+ }
189
+ exports.Argument = Argument;
190
+ exports.humanReadableArgName = humanReadableArgName;
191
+ }));
192
+ //#endregion
193
+ //#region node_modules/commander/lib/help.js
194
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
195
+ const { humanReadableArgName } = require_argument();
196
+ /**
197
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
198
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
199
+ * @typedef { import("./argument.js").Argument } Argument
200
+ * @typedef { import("./command.js").Command } Command
201
+ * @typedef { import("./option.js").Option } Option
202
+ */
203
+ var Help = class {
204
+ constructor() {
205
+ this.helpWidth = void 0;
206
+ this.minWidthToWrap = 40;
207
+ this.sortSubcommands = false;
208
+ this.sortOptions = false;
209
+ this.showGlobalOptions = false;
210
+ }
211
+ /**
212
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
213
+ * and just before calling `formatHelp()`.
214
+ *
215
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
216
+ *
217
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
218
+ */
219
+ prepareContext(contextOptions) {
220
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
221
+ }
222
+ /**
223
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
224
+ *
225
+ * @param {Command} cmd
226
+ * @returns {Command[]}
227
+ */
228
+ visibleCommands(cmd) {
229
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
230
+ const helpCommand = cmd._getHelpCommand();
231
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
232
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
233
+ return a.name().localeCompare(b.name());
234
+ });
235
+ return visibleCommands;
236
+ }
237
+ /**
238
+ * Compare options for sort.
239
+ *
240
+ * @param {Option} a
241
+ * @param {Option} b
242
+ * @returns {number}
243
+ */
244
+ compareOptions(a, b) {
245
+ const getSortKey = (option) => {
246
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
247
+ };
248
+ return getSortKey(a).localeCompare(getSortKey(b));
249
+ }
250
+ /**
251
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
252
+ *
253
+ * @param {Command} cmd
254
+ * @returns {Option[]}
255
+ */
256
+ visibleOptions(cmd) {
257
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
258
+ const helpOption = cmd._getHelpOption();
259
+ if (helpOption && !helpOption.hidden) {
260
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
261
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
262
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
263
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
264
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
265
+ }
266
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
267
+ return visibleOptions;
268
+ }
269
+ /**
270
+ * Get an array of the visible global options. (Not including help.)
271
+ *
272
+ * @param {Command} cmd
273
+ * @returns {Option[]}
274
+ */
275
+ visibleGlobalOptions(cmd) {
276
+ if (!this.showGlobalOptions) return [];
277
+ const globalOptions = [];
278
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
279
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
280
+ globalOptions.push(...visibleOptions);
281
+ }
282
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
283
+ return globalOptions;
284
+ }
285
+ /**
286
+ * Get an array of the arguments if any have a description.
287
+ *
288
+ * @param {Command} cmd
289
+ * @returns {Argument[]}
290
+ */
291
+ visibleArguments(cmd) {
292
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
293
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
294
+ });
295
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
296
+ return [];
297
+ }
298
+ /**
299
+ * Get the command term to show in the list of subcommands.
300
+ *
301
+ * @param {Command} cmd
302
+ * @returns {string}
303
+ */
304
+ subcommandTerm(cmd) {
305
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
306
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
307
+ }
308
+ /**
309
+ * Get the option term to show in the list of options.
310
+ *
311
+ * @param {Option} option
312
+ * @returns {string}
313
+ */
314
+ optionTerm(option) {
315
+ return option.flags;
316
+ }
317
+ /**
318
+ * Get the argument term to show in the list of arguments.
319
+ *
320
+ * @param {Argument} argument
321
+ * @returns {string}
322
+ */
323
+ argumentTerm(argument) {
324
+ return argument.name();
325
+ }
326
+ /**
327
+ * Get the longest command term length.
328
+ *
329
+ * @param {Command} cmd
330
+ * @param {Help} helper
331
+ * @returns {number}
332
+ */
333
+ longestSubcommandTermLength(cmd, helper) {
334
+ return helper.visibleCommands(cmd).reduce((max, command) => {
335
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
336
+ }, 0);
337
+ }
338
+ /**
339
+ * Get the longest option term length.
340
+ *
341
+ * @param {Command} cmd
342
+ * @param {Help} helper
343
+ * @returns {number}
344
+ */
345
+ longestOptionTermLength(cmd, helper) {
346
+ return helper.visibleOptions(cmd).reduce((max, option) => {
347
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
348
+ }, 0);
349
+ }
350
+ /**
351
+ * Get the longest global option term length.
352
+ *
353
+ * @param {Command} cmd
354
+ * @param {Help} helper
355
+ * @returns {number}
356
+ */
357
+ longestGlobalOptionTermLength(cmd, helper) {
358
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
359
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
360
+ }, 0);
361
+ }
362
+ /**
363
+ * Get the longest argument term length.
364
+ *
365
+ * @param {Command} cmd
366
+ * @param {Help} helper
367
+ * @returns {number}
368
+ */
369
+ longestArgumentTermLength(cmd, helper) {
370
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
371
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
372
+ }, 0);
373
+ }
374
+ /**
375
+ * Get the command usage to be displayed at the top of the built-in help.
376
+ *
377
+ * @param {Command} cmd
378
+ * @returns {string}
379
+ */
380
+ commandUsage(cmd) {
381
+ let cmdName = cmd._name;
382
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
383
+ let ancestorCmdNames = "";
384
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
385
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
386
+ }
387
+ /**
388
+ * Get the description for the command.
389
+ *
390
+ * @param {Command} cmd
391
+ * @returns {string}
392
+ */
393
+ commandDescription(cmd) {
394
+ return cmd.description();
395
+ }
396
+ /**
397
+ * Get the subcommand summary to show in the list of subcommands.
398
+ * (Fallback to description for backwards compatibility.)
399
+ *
400
+ * @param {Command} cmd
401
+ * @returns {string}
402
+ */
403
+ subcommandDescription(cmd) {
404
+ return cmd.summary() || cmd.description();
405
+ }
406
+ /**
407
+ * Get the option description to show in the list of options.
408
+ *
409
+ * @param {Option} option
410
+ * @return {string}
411
+ */
412
+ optionDescription(option) {
413
+ const extraInfo = [];
414
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
415
+ if (option.defaultValue !== void 0) {
416
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
417
+ }
418
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
419
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
420
+ if (extraInfo.length > 0) {
421
+ const extraDescription = `(${extraInfo.join(", ")})`;
422
+ if (option.description) return `${option.description} ${extraDescription}`;
423
+ return extraDescription;
424
+ }
425
+ return option.description;
426
+ }
427
+ /**
428
+ * Get the argument description to show in the list of arguments.
429
+ *
430
+ * @param {Argument} argument
431
+ * @return {string}
432
+ */
433
+ argumentDescription(argument) {
434
+ const extraInfo = [];
435
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
436
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
437
+ if (extraInfo.length > 0) {
438
+ const extraDescription = `(${extraInfo.join(", ")})`;
439
+ if (argument.description) return `${argument.description} ${extraDescription}`;
440
+ return extraDescription;
441
+ }
442
+ return argument.description;
443
+ }
444
+ /**
445
+ * Format a list of items, given a heading and an array of formatted items.
446
+ *
447
+ * @param {string} heading
448
+ * @param {string[]} items
449
+ * @param {Help} helper
450
+ * @returns string[]
451
+ */
452
+ formatItemList(heading, items, helper) {
453
+ if (items.length === 0) return [];
454
+ return [
455
+ helper.styleTitle(heading),
456
+ ...items,
457
+ ""
458
+ ];
459
+ }
460
+ /**
461
+ * Group items by their help group heading.
462
+ *
463
+ * @param {Command[] | Option[]} unsortedItems
464
+ * @param {Command[] | Option[]} visibleItems
465
+ * @param {Function} getGroup
466
+ * @returns {Map<string, Command[] | Option[]>}
467
+ */
468
+ groupItems(unsortedItems, visibleItems, getGroup) {
469
+ const result = /* @__PURE__ */ new Map();
470
+ unsortedItems.forEach((item) => {
471
+ const group = getGroup(item);
472
+ if (!result.has(group)) result.set(group, []);
473
+ });
474
+ visibleItems.forEach((item) => {
475
+ const group = getGroup(item);
476
+ if (!result.has(group)) result.set(group, []);
477
+ result.get(group).push(item);
478
+ });
479
+ return result;
480
+ }
481
+ /**
482
+ * Generate the built-in help text.
483
+ *
484
+ * @param {Command} cmd
485
+ * @param {Help} helper
486
+ * @returns {string}
487
+ */
488
+ formatHelp(cmd, helper) {
489
+ const termWidth = helper.padWidth(cmd, helper);
490
+ const helpWidth = helper.helpWidth ?? 80;
491
+ function callFormatItem(term, description) {
492
+ return helper.formatItem(term, termWidth, description, helper);
493
+ }
494
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
495
+ const commandDescription = helper.commandDescription(cmd);
496
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
497
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
498
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
499
+ });
500
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
501
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
502
+ const optionList = options.map((option) => {
503
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
504
+ });
505
+ output = output.concat(this.formatItemList(group, optionList, helper));
506
+ });
507
+ if (helper.showGlobalOptions) {
508
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
509
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
510
+ });
511
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
512
+ }
513
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
514
+ const commandList = commands.map((sub) => {
515
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
516
+ });
517
+ output = output.concat(this.formatItemList(group, commandList, helper));
518
+ });
519
+ return output.join("\n");
520
+ }
521
+ /**
522
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
523
+ *
524
+ * @param {string} str
525
+ * @returns {number}
526
+ */
527
+ displayWidth(str) {
528
+ return stripColor(str).length;
529
+ }
530
+ /**
531
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
532
+ *
533
+ * @param {string} str
534
+ * @returns {string}
535
+ */
536
+ styleTitle(str) {
537
+ return str;
538
+ }
539
+ styleUsage(str) {
540
+ return str.split(" ").map((word) => {
541
+ if (word === "[options]") return this.styleOptionText(word);
542
+ if (word === "[command]") return this.styleSubcommandText(word);
543
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
544
+ return this.styleCommandText(word);
545
+ }).join(" ");
546
+ }
547
+ styleCommandDescription(str) {
548
+ return this.styleDescriptionText(str);
549
+ }
550
+ styleOptionDescription(str) {
551
+ return this.styleDescriptionText(str);
552
+ }
553
+ styleSubcommandDescription(str) {
554
+ return this.styleDescriptionText(str);
555
+ }
556
+ styleArgumentDescription(str) {
557
+ return this.styleDescriptionText(str);
558
+ }
559
+ styleDescriptionText(str) {
560
+ return str;
561
+ }
562
+ styleOptionTerm(str) {
563
+ return this.styleOptionText(str);
564
+ }
565
+ styleSubcommandTerm(str) {
566
+ return str.split(" ").map((word) => {
567
+ if (word === "[options]") return this.styleOptionText(word);
568
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
569
+ return this.styleSubcommandText(word);
570
+ }).join(" ");
571
+ }
572
+ styleArgumentTerm(str) {
573
+ return this.styleArgumentText(str);
574
+ }
575
+ styleOptionText(str) {
576
+ return str;
577
+ }
578
+ styleArgumentText(str) {
579
+ return str;
580
+ }
581
+ styleSubcommandText(str) {
582
+ return str;
583
+ }
584
+ styleCommandText(str) {
585
+ return str;
586
+ }
587
+ /**
588
+ * Calculate the pad width from the maximum term length.
589
+ *
590
+ * @param {Command} cmd
591
+ * @param {Help} helper
592
+ * @returns {number}
593
+ */
594
+ padWidth(cmd, helper) {
595
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
596
+ }
597
+ /**
598
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
599
+ *
600
+ * @param {string} str
601
+ * @returns {boolean}
602
+ */
603
+ preformatted(str) {
604
+ return /\n[^\S\r\n]/.test(str);
605
+ }
606
+ /**
607
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
608
+ *
609
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
610
+ * TTT DDD DDDD
611
+ * DD DDD
612
+ *
613
+ * @param {string} term
614
+ * @param {number} termWidth
615
+ * @param {string} description
616
+ * @param {Help} helper
617
+ * @returns {string}
618
+ */
619
+ formatItem(term, termWidth, description, helper) {
620
+ const itemIndent = 2;
621
+ const itemIndentStr = " ".repeat(itemIndent);
622
+ if (!description) return itemIndentStr + term;
623
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
624
+ const spacerWidth = 2;
625
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
626
+ let formattedDescription;
627
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
628
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
629
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
630
+ }
631
+ /**
632
+ * Wrap a string at whitespace, preserving existing line breaks.
633
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
634
+ *
635
+ * @param {string} str
636
+ * @param {number} width
637
+ * @returns {string}
638
+ */
639
+ boxWrap(str, width) {
640
+ if (width < this.minWidthToWrap) return str;
641
+ const rawLines = str.split(/\r\n|\n/);
642
+ const chunkPattern = /[\s]*[^\s]+/g;
643
+ const wrappedLines = [];
644
+ rawLines.forEach((line) => {
645
+ const chunks = line.match(chunkPattern);
646
+ if (chunks === null) {
647
+ wrappedLines.push("");
648
+ return;
649
+ }
650
+ let sumChunks = [chunks.shift()];
651
+ let sumWidth = this.displayWidth(sumChunks[0]);
652
+ chunks.forEach((chunk) => {
653
+ const visibleWidth = this.displayWidth(chunk);
654
+ if (sumWidth + visibleWidth <= width) {
655
+ sumChunks.push(chunk);
656
+ sumWidth += visibleWidth;
657
+ return;
658
+ }
659
+ wrappedLines.push(sumChunks.join(""));
660
+ const nextChunk = chunk.trimStart();
661
+ sumChunks = [nextChunk];
662
+ sumWidth = this.displayWidth(nextChunk);
663
+ });
664
+ wrappedLines.push(sumChunks.join(""));
665
+ });
666
+ return wrappedLines.join("\n");
667
+ }
668
+ };
669
+ /**
670
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
671
+ *
672
+ * @param {string} str
673
+ * @returns {string}
674
+ * @package
675
+ */
676
+ function stripColor(str) {
677
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
678
+ }
679
+ exports.Help = Help;
680
+ exports.stripColor = stripColor;
681
+ }));
682
+ //#endregion
683
+ //#region node_modules/commander/lib/option.js
684
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
685
+ const { InvalidArgumentError } = require_error();
686
+ var Option = class {
687
+ /**
688
+ * Initialize a new `Option` with the given `flags` and `description`.
689
+ *
690
+ * @param {string} flags
691
+ * @param {string} [description]
692
+ */
693
+ constructor(flags, description) {
694
+ this.flags = flags;
695
+ this.description = description || "";
696
+ this.required = flags.includes("<");
697
+ this.optional = flags.includes("[");
698
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
699
+ this.mandatory = false;
700
+ const optionFlags = splitOptionFlags(flags);
701
+ this.short = optionFlags.shortFlag;
702
+ this.long = optionFlags.longFlag;
703
+ this.negate = false;
704
+ if (this.long) this.negate = this.long.startsWith("--no-");
705
+ this.defaultValue = void 0;
706
+ this.defaultValueDescription = void 0;
707
+ this.presetArg = void 0;
708
+ this.envVar = void 0;
709
+ this.parseArg = void 0;
710
+ this.hidden = false;
711
+ this.argChoices = void 0;
712
+ this.conflictsWith = [];
713
+ this.implied = void 0;
714
+ this.helpGroupHeading = void 0;
715
+ }
716
+ /**
717
+ * Set the default value, and optionally supply the description to be displayed in the help.
718
+ *
719
+ * @param {*} value
720
+ * @param {string} [description]
721
+ * @return {Option}
722
+ */
723
+ default(value, description) {
724
+ this.defaultValue = value;
725
+ this.defaultValueDescription = description;
726
+ return this;
727
+ }
728
+ /**
729
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
730
+ * The custom processing (parseArg) is called.
731
+ *
732
+ * @example
733
+ * new Option('--color').default('GREYSCALE').preset('RGB');
734
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
735
+ *
736
+ * @param {*} arg
737
+ * @return {Option}
738
+ */
739
+ preset(arg) {
740
+ this.presetArg = arg;
741
+ return this;
742
+ }
743
+ /**
744
+ * Add option name(s) that conflict with this option.
745
+ * An error will be displayed if conflicting options are found during parsing.
746
+ *
747
+ * @example
748
+ * new Option('--rgb').conflicts('cmyk');
749
+ * new Option('--js').conflicts(['ts', 'jsx']);
750
+ *
751
+ * @param {(string | string[])} names
752
+ * @return {Option}
753
+ */
754
+ conflicts(names) {
755
+ this.conflictsWith = this.conflictsWith.concat(names);
756
+ return this;
757
+ }
758
+ /**
759
+ * Specify implied option values for when this option is set and the implied options are not.
760
+ *
761
+ * The custom processing (parseArg) is not called on the implied values.
762
+ *
763
+ * @example
764
+ * program
765
+ * .addOption(new Option('--log', 'write logging information to file'))
766
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
767
+ *
768
+ * @param {object} impliedOptionValues
769
+ * @return {Option}
770
+ */
771
+ implies(impliedOptionValues) {
772
+ let newImplied = impliedOptionValues;
773
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
774
+ this.implied = Object.assign(this.implied || {}, newImplied);
775
+ return this;
776
+ }
777
+ /**
778
+ * Set environment variable to check for option value.
779
+ *
780
+ * An environment variable is only used if when processed the current option value is
781
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
782
+ *
783
+ * @param {string} name
784
+ * @return {Option}
785
+ */
786
+ env(name) {
787
+ this.envVar = name;
788
+ return this;
789
+ }
790
+ /**
791
+ * Set the custom handler for processing CLI option arguments into option values.
792
+ *
793
+ * @param {Function} [fn]
794
+ * @return {Option}
795
+ */
796
+ argParser(fn) {
797
+ this.parseArg = fn;
798
+ return this;
799
+ }
800
+ /**
801
+ * Whether the option is mandatory and must have a value after parsing.
802
+ *
803
+ * @param {boolean} [mandatory=true]
804
+ * @return {Option}
805
+ */
806
+ makeOptionMandatory(mandatory = true) {
807
+ this.mandatory = !!mandatory;
808
+ return this;
809
+ }
810
+ /**
811
+ * Hide option in help.
812
+ *
813
+ * @param {boolean} [hide=true]
814
+ * @return {Option}
815
+ */
816
+ hideHelp(hide = true) {
817
+ this.hidden = !!hide;
818
+ return this;
819
+ }
820
+ /**
821
+ * @package
822
+ */
823
+ _collectValue(value, previous) {
824
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
825
+ previous.push(value);
826
+ return previous;
827
+ }
828
+ /**
829
+ * Only allow option value to be one of choices.
830
+ *
831
+ * @param {string[]} values
832
+ * @return {Option}
833
+ */
834
+ choices(values) {
835
+ this.argChoices = values.slice();
836
+ this.parseArg = (arg, previous) => {
837
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
838
+ if (this.variadic) return this._collectValue(arg, previous);
839
+ return arg;
840
+ };
841
+ return this;
842
+ }
843
+ /**
844
+ * Return option name.
845
+ *
846
+ * @return {string}
847
+ */
848
+ name() {
849
+ if (this.long) return this.long.replace(/^--/, "");
850
+ return this.short.replace(/^-/, "");
851
+ }
852
+ /**
853
+ * Return option name, in a camelcase format that can be used
854
+ * as an object attribute key.
855
+ *
856
+ * @return {string}
857
+ */
858
+ attributeName() {
859
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
860
+ return camelcase(this.name());
861
+ }
862
+ /**
863
+ * Set the help group heading.
864
+ *
865
+ * @param {string} heading
866
+ * @return {Option}
867
+ */
868
+ helpGroup(heading) {
869
+ this.helpGroupHeading = heading;
870
+ return this;
871
+ }
872
+ /**
873
+ * Check if `arg` matches the short or long flag.
874
+ *
875
+ * @param {string} arg
876
+ * @return {boolean}
877
+ * @package
878
+ */
879
+ is(arg) {
880
+ return this.short === arg || this.long === arg;
881
+ }
882
+ /**
883
+ * Return whether a boolean option.
884
+ *
885
+ * Options are one of boolean, negated, required argument, or optional argument.
886
+ *
887
+ * @return {boolean}
888
+ * @package
889
+ */
890
+ isBoolean() {
891
+ return !this.required && !this.optional && !this.negate;
892
+ }
893
+ };
894
+ /**
895
+ * This class is to make it easier to work with dual options, without changing the existing
896
+ * implementation. We support separate dual options for separate positive and negative options,
897
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
898
+ * use cases, but is tricky for others where we want separate behaviours despite
899
+ * the single shared option value.
900
+ */
901
+ var DualOptions = class {
902
+ /**
903
+ * @param {Option[]} options
904
+ */
905
+ constructor(options) {
906
+ this.positiveOptions = /* @__PURE__ */ new Map();
907
+ this.negativeOptions = /* @__PURE__ */ new Map();
908
+ this.dualOptions = /* @__PURE__ */ new Set();
909
+ options.forEach((option) => {
910
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
911
+ else this.positiveOptions.set(option.attributeName(), option);
912
+ });
913
+ this.negativeOptions.forEach((value, key) => {
914
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
915
+ });
916
+ }
917
+ /**
918
+ * Did the value come from the option, and not from possible matching dual option?
919
+ *
920
+ * @param {*} value
921
+ * @param {Option} option
922
+ * @returns {boolean}
923
+ */
924
+ valueFromOption(value, option) {
925
+ const optionKey = option.attributeName();
926
+ if (!this.dualOptions.has(optionKey)) return true;
927
+ const preset = this.negativeOptions.get(optionKey).presetArg;
928
+ const negativeValue = preset !== void 0 ? preset : false;
929
+ return option.negate === (negativeValue === value);
930
+ }
931
+ };
932
+ /**
933
+ * Convert string from kebab-case to camelCase.
934
+ *
935
+ * @param {string} str
936
+ * @return {string}
937
+ * @private
938
+ */
939
+ function camelcase(str) {
940
+ return str.split("-").reduce((str, word) => {
941
+ return str + word[0].toUpperCase() + word.slice(1);
942
+ });
943
+ }
944
+ /**
945
+ * Split the short and long flag out of something like '-m,--mixed <value>'
946
+ *
947
+ * @private
948
+ */
949
+ function splitOptionFlags(flags) {
950
+ let shortFlag;
951
+ let longFlag;
952
+ const shortFlagExp = /^-[^-]$/;
953
+ const longFlagExp = /^--[^-]/;
954
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
955
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
956
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
957
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
958
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
959
+ shortFlag = longFlag;
960
+ longFlag = flagParts.shift();
961
+ }
962
+ if (flagParts[0].startsWith("-")) {
963
+ const unsupportedFlag = flagParts[0];
964
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
965
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
966
+ - a short flag is a single dash and a single character
967
+ - either use a single dash and a single character (for a short flag)
968
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
969
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
970
+ - too many short flags`);
971
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
972
+ - too many long flags`);
973
+ throw new Error(`${baseError}
974
+ - unrecognised flag format`);
975
+ }
976
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
977
+ return {
978
+ shortFlag,
979
+ longFlag
980
+ };
981
+ }
982
+ exports.Option = Option;
983
+ exports.DualOptions = DualOptions;
984
+ }));
985
+ //#endregion
986
+ //#region node_modules/commander/lib/suggestSimilar.js
987
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
988
+ const maxDistance = 3;
989
+ function editDistance(a, b) {
990
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
991
+ const d = [];
992
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
993
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
994
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
995
+ let cost = 1;
996
+ if (a[i - 1] === b[j - 1]) cost = 0;
997
+ else cost = 1;
998
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
999
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1000
+ }
1001
+ return d[a.length][b.length];
1002
+ }
1003
+ /**
1004
+ * Find close matches, restricted to same number of edits.
1005
+ *
1006
+ * @param {string} word
1007
+ * @param {string[]} candidates
1008
+ * @returns {string}
1009
+ */
1010
+ function suggestSimilar(word, candidates) {
1011
+ if (!candidates || candidates.length === 0) return "";
1012
+ candidates = Array.from(new Set(candidates));
1013
+ const searchingOptions = word.startsWith("--");
1014
+ if (searchingOptions) {
1015
+ word = word.slice(2);
1016
+ candidates = candidates.map((candidate) => candidate.slice(2));
1017
+ }
1018
+ let similar = [];
1019
+ let bestDistance = maxDistance;
1020
+ const minSimilarity = .4;
1021
+ candidates.forEach((candidate) => {
1022
+ if (candidate.length <= 1) return;
1023
+ const distance = editDistance(word, candidate);
1024
+ const length = Math.max(word.length, candidate.length);
1025
+ if ((length - distance) / length > minSimilarity) {
1026
+ if (distance < bestDistance) {
1027
+ bestDistance = distance;
1028
+ similar = [candidate];
1029
+ } else if (distance === bestDistance) similar.push(candidate);
1030
+ }
1031
+ });
1032
+ similar.sort((a, b) => a.localeCompare(b));
1033
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1034
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1035
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1036
+ return "";
1037
+ }
1038
+ exports.suggestSimilar = suggestSimilar;
1039
+ }));
1040
+ //#endregion
1041
+ //#region node_modules/commander/lib/command.js
1042
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1043
+ const EventEmitter = __require("events").EventEmitter;
1044
+ const childProcess = __require("child_process");
1045
+ const path = __require("path");
1046
+ const fs = __require("fs");
1047
+ const process$1 = __require("process");
1048
+ const { Argument, humanReadableArgName } = require_argument();
1049
+ const { CommanderError } = require_error();
1050
+ const { Help, stripColor } = require_help();
1051
+ const { Option, DualOptions } = require_option();
1052
+ const { suggestSimilar } = require_suggestSimilar();
1053
+ var Command = class Command extends EventEmitter {
1054
+ /**
1055
+ * Initialize a new `Command`.
1056
+ *
1057
+ * @param {string} [name]
1058
+ */
1059
+ constructor(name) {
1060
+ super();
1061
+ /** @type {Command[]} */
1062
+ this.commands = [];
1063
+ /** @type {Option[]} */
1064
+ this.options = [];
1065
+ this.parent = null;
1066
+ this._allowUnknownOption = false;
1067
+ this._allowExcessArguments = false;
1068
+ /** @type {Argument[]} */
1069
+ this.registeredArguments = [];
1070
+ this._args = this.registeredArguments;
1071
+ /** @type {string[]} */
1072
+ this.args = [];
1073
+ this.rawArgs = [];
1074
+ this.processedArgs = [];
1075
+ this._scriptPath = null;
1076
+ this._name = name || "";
1077
+ this._optionValues = {};
1078
+ this._optionValueSources = {};
1079
+ this._storeOptionsAsProperties = false;
1080
+ this._actionHandler = null;
1081
+ this._executableHandler = false;
1082
+ this._executableFile = null;
1083
+ this._executableDir = null;
1084
+ this._defaultCommandName = null;
1085
+ this._exitCallback = null;
1086
+ this._aliases = [];
1087
+ this._combineFlagAndOptionalValue = true;
1088
+ this._description = "";
1089
+ this._summary = "";
1090
+ this._argsDescription = void 0;
1091
+ this._enablePositionalOptions = false;
1092
+ this._passThroughOptions = false;
1093
+ this._lifeCycleHooks = {};
1094
+ /** @type {(boolean | string)} */
1095
+ this._showHelpAfterError = false;
1096
+ this._showSuggestionAfterError = true;
1097
+ this._savedState = null;
1098
+ this._outputConfiguration = {
1099
+ writeOut: (str) => process$1.stdout.write(str),
1100
+ writeErr: (str) => process$1.stderr.write(str),
1101
+ outputError: (str, write) => write(str),
1102
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1103
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1104
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1105
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1106
+ stripColor: (str) => stripColor(str)
1107
+ };
1108
+ this._hidden = false;
1109
+ /** @type {(Option | null | undefined)} */
1110
+ this._helpOption = void 0;
1111
+ this._addImplicitHelpCommand = void 0;
1112
+ /** @type {Command} */
1113
+ this._helpCommand = void 0;
1114
+ this._helpConfiguration = {};
1115
+ /** @type {string | undefined} */
1116
+ this._helpGroupHeading = void 0;
1117
+ /** @type {string | undefined} */
1118
+ this._defaultCommandGroup = void 0;
1119
+ /** @type {string | undefined} */
1120
+ this._defaultOptionGroup = void 0;
1121
+ }
1122
+ /**
1123
+ * Copy settings that are useful to have in common across root command and subcommands.
1124
+ *
1125
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1126
+ *
1127
+ * @param {Command} sourceCommand
1128
+ * @return {Command} `this` command for chaining
1129
+ */
1130
+ copyInheritedSettings(sourceCommand) {
1131
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1132
+ this._helpOption = sourceCommand._helpOption;
1133
+ this._helpCommand = sourceCommand._helpCommand;
1134
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1135
+ this._exitCallback = sourceCommand._exitCallback;
1136
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1137
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1138
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1139
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1140
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1141
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1142
+ return this;
1143
+ }
1144
+ /**
1145
+ * @returns {Command[]}
1146
+ * @private
1147
+ */
1148
+ _getCommandAndAncestors() {
1149
+ const result = [];
1150
+ for (let command = this; command; command = command.parent) result.push(command);
1151
+ return result;
1152
+ }
1153
+ /**
1154
+ * Define a command.
1155
+ *
1156
+ * There are two styles of command: pay attention to where to put the description.
1157
+ *
1158
+ * @example
1159
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1160
+ * program
1161
+ * .command('clone <source> [destination]')
1162
+ * .description('clone a repository into a newly created directory')
1163
+ * .action((source, destination) => {
1164
+ * console.log('clone command called');
1165
+ * });
1166
+ *
1167
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1168
+ * program
1169
+ * .command('start <service>', 'start named service')
1170
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1171
+ *
1172
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1173
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1174
+ * @param {object} [execOpts] - configuration options (for executable)
1175
+ * @return {Command} returns new command for action handler, or `this` for executable command
1176
+ */
1177
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1178
+ let desc = actionOptsOrExecDesc;
1179
+ let opts = execOpts;
1180
+ if (typeof desc === "object" && desc !== null) {
1181
+ opts = desc;
1182
+ desc = null;
1183
+ }
1184
+ opts = opts || {};
1185
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1186
+ const cmd = this.createCommand(name);
1187
+ if (desc) {
1188
+ cmd.description(desc);
1189
+ cmd._executableHandler = true;
1190
+ }
1191
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1192
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1193
+ cmd._executableFile = opts.executableFile || null;
1194
+ if (args) cmd.arguments(args);
1195
+ this._registerCommand(cmd);
1196
+ cmd.parent = this;
1197
+ cmd.copyInheritedSettings(this);
1198
+ if (desc) return this;
1199
+ return cmd;
1200
+ }
1201
+ /**
1202
+ * Factory routine to create a new unattached command.
1203
+ *
1204
+ * See .command() for creating an attached subcommand, which uses this routine to
1205
+ * create the command. You can override createCommand to customise subcommands.
1206
+ *
1207
+ * @param {string} [name]
1208
+ * @return {Command} new command
1209
+ */
1210
+ createCommand(name) {
1211
+ return new Command(name);
1212
+ }
1213
+ /**
1214
+ * You can customise the help with a subclass of Help by overriding createHelp,
1215
+ * or by overriding Help properties using configureHelp().
1216
+ *
1217
+ * @return {Help}
1218
+ */
1219
+ createHelp() {
1220
+ return Object.assign(new Help(), this.configureHelp());
1221
+ }
1222
+ /**
1223
+ * You can customise the help by overriding Help properties using configureHelp(),
1224
+ * or with a subclass of Help by overriding createHelp().
1225
+ *
1226
+ * @param {object} [configuration] - configuration options
1227
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1228
+ */
1229
+ configureHelp(configuration) {
1230
+ if (configuration === void 0) return this._helpConfiguration;
1231
+ this._helpConfiguration = configuration;
1232
+ return this;
1233
+ }
1234
+ /**
1235
+ * The default output goes to stdout and stderr. You can customise this for special
1236
+ * applications. You can also customise the display of errors by overriding outputError.
1237
+ *
1238
+ * The configuration properties are all functions:
1239
+ *
1240
+ * // change how output being written, defaults to stdout and stderr
1241
+ * writeOut(str)
1242
+ * writeErr(str)
1243
+ * // change how output being written for errors, defaults to writeErr
1244
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1245
+ * // specify width for wrapping help
1246
+ * getOutHelpWidth()
1247
+ * getErrHelpWidth()
1248
+ * // color support, currently only used with Help
1249
+ * getOutHasColors()
1250
+ * getErrHasColors()
1251
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1252
+ *
1253
+ * @param {object} [configuration] - configuration options
1254
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1255
+ */
1256
+ configureOutput(configuration) {
1257
+ if (configuration === void 0) return this._outputConfiguration;
1258
+ this._outputConfiguration = {
1259
+ ...this._outputConfiguration,
1260
+ ...configuration
1261
+ };
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Display the help or a custom message after an error occurs.
1266
+ *
1267
+ * @param {(boolean|string)} [displayHelp]
1268
+ * @return {Command} `this` command for chaining
1269
+ */
1270
+ showHelpAfterError(displayHelp = true) {
1271
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1272
+ this._showHelpAfterError = displayHelp;
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1277
+ *
1278
+ * @param {boolean} [displaySuggestion]
1279
+ * @return {Command} `this` command for chaining
1280
+ */
1281
+ showSuggestionAfterError(displaySuggestion = true) {
1282
+ this._showSuggestionAfterError = !!displaySuggestion;
1283
+ return this;
1284
+ }
1285
+ /**
1286
+ * Add a prepared subcommand.
1287
+ *
1288
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1289
+ *
1290
+ * @param {Command} cmd - new subcommand
1291
+ * @param {object} [opts] - configuration options
1292
+ * @return {Command} `this` command for chaining
1293
+ */
1294
+ addCommand(cmd, opts) {
1295
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1296
+ - specify the name in Command constructor or using .name()`);
1297
+ opts = opts || {};
1298
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1299
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1300
+ this._registerCommand(cmd);
1301
+ cmd.parent = this;
1302
+ cmd._checkForBrokenPassThrough();
1303
+ return this;
1304
+ }
1305
+ /**
1306
+ * Factory routine to create a new unattached argument.
1307
+ *
1308
+ * See .argument() for creating an attached argument, which uses this routine to
1309
+ * create the argument. You can override createArgument to return a custom argument.
1310
+ *
1311
+ * @param {string} name
1312
+ * @param {string} [description]
1313
+ * @return {Argument} new argument
1314
+ */
1315
+ createArgument(name, description) {
1316
+ return new Argument(name, description);
1317
+ }
1318
+ /**
1319
+ * Define argument syntax for command.
1320
+ *
1321
+ * The default is that the argument is required, and you can explicitly
1322
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1323
+ *
1324
+ * @example
1325
+ * program.argument('<input-file>');
1326
+ * program.argument('[output-file]');
1327
+ *
1328
+ * @param {string} name
1329
+ * @param {string} [description]
1330
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1331
+ * @param {*} [defaultValue]
1332
+ * @return {Command} `this` command for chaining
1333
+ */
1334
+ argument(name, description, parseArg, defaultValue) {
1335
+ const argument = this.createArgument(name, description);
1336
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1337
+ else argument.default(parseArg);
1338
+ this.addArgument(argument);
1339
+ return this;
1340
+ }
1341
+ /**
1342
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1343
+ *
1344
+ * See also .argument().
1345
+ *
1346
+ * @example
1347
+ * program.arguments('<cmd> [env]');
1348
+ *
1349
+ * @param {string} names
1350
+ * @return {Command} `this` command for chaining
1351
+ */
1352
+ arguments(names) {
1353
+ names.trim().split(/ +/).forEach((detail) => {
1354
+ this.argument(detail);
1355
+ });
1356
+ return this;
1357
+ }
1358
+ /**
1359
+ * Define argument syntax for command, adding a prepared argument.
1360
+ *
1361
+ * @param {Argument} argument
1362
+ * @return {Command} `this` command for chaining
1363
+ */
1364
+ addArgument(argument) {
1365
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1366
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1367
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1368
+ this.registeredArguments.push(argument);
1369
+ return this;
1370
+ }
1371
+ /**
1372
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1373
+ *
1374
+ * @example
1375
+ * program.helpCommand('help [cmd]');
1376
+ * program.helpCommand('help [cmd]', 'show help');
1377
+ * program.helpCommand(false); // suppress default help command
1378
+ * program.helpCommand(true); // add help command even if no subcommands
1379
+ *
1380
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1381
+ * @param {string} [description] - custom description
1382
+ * @return {Command} `this` command for chaining
1383
+ */
1384
+ helpCommand(enableOrNameAndArgs, description) {
1385
+ if (typeof enableOrNameAndArgs === "boolean") {
1386
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1387
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1388
+ return this;
1389
+ }
1390
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1391
+ const helpDescription = description ?? "display help for command";
1392
+ const helpCommand = this.createCommand(helpName);
1393
+ helpCommand.helpOption(false);
1394
+ if (helpArgs) helpCommand.arguments(helpArgs);
1395
+ if (helpDescription) helpCommand.description(helpDescription);
1396
+ this._addImplicitHelpCommand = true;
1397
+ this._helpCommand = helpCommand;
1398
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1399
+ return this;
1400
+ }
1401
+ /**
1402
+ * Add prepared custom help command.
1403
+ *
1404
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1405
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1406
+ * @return {Command} `this` command for chaining
1407
+ */
1408
+ addHelpCommand(helpCommand, deprecatedDescription) {
1409
+ if (typeof helpCommand !== "object") {
1410
+ this.helpCommand(helpCommand, deprecatedDescription);
1411
+ return this;
1412
+ }
1413
+ this._addImplicitHelpCommand = true;
1414
+ this._helpCommand = helpCommand;
1415
+ this._initCommandGroup(helpCommand);
1416
+ return this;
1417
+ }
1418
+ /**
1419
+ * Lazy create help command.
1420
+ *
1421
+ * @return {(Command|null)}
1422
+ * @package
1423
+ */
1424
+ _getHelpCommand() {
1425
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1426
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1427
+ return this._helpCommand;
1428
+ }
1429
+ return null;
1430
+ }
1431
+ /**
1432
+ * Add hook for life cycle event.
1433
+ *
1434
+ * @param {string} event
1435
+ * @param {Function} listener
1436
+ * @return {Command} `this` command for chaining
1437
+ */
1438
+ hook(event, listener) {
1439
+ const allowedValues = [
1440
+ "preSubcommand",
1441
+ "preAction",
1442
+ "postAction"
1443
+ ];
1444
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1445
+ Expecting one of '${allowedValues.join("', '")}'`);
1446
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1447
+ else this._lifeCycleHooks[event] = [listener];
1448
+ return this;
1449
+ }
1450
+ /**
1451
+ * Register callback to use as replacement for calling process.exit.
1452
+ *
1453
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1454
+ * @return {Command} `this` command for chaining
1455
+ */
1456
+ exitOverride(fn) {
1457
+ if (fn) this._exitCallback = fn;
1458
+ else this._exitCallback = (err) => {
1459
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1460
+ };
1461
+ return this;
1462
+ }
1463
+ /**
1464
+ * Call process.exit, and _exitCallback if defined.
1465
+ *
1466
+ * @param {number} exitCode exit code for using with process.exit
1467
+ * @param {string} code an id string representing the error
1468
+ * @param {string} message human-readable description of the error
1469
+ * @return never
1470
+ * @private
1471
+ */
1472
+ _exit(exitCode, code, message) {
1473
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1474
+ process$1.exit(exitCode);
1475
+ }
1476
+ /**
1477
+ * Register callback `fn` for the command.
1478
+ *
1479
+ * @example
1480
+ * program
1481
+ * .command('serve')
1482
+ * .description('start service')
1483
+ * .action(function() {
1484
+ * // do work here
1485
+ * });
1486
+ *
1487
+ * @param {Function} fn
1488
+ * @return {Command} `this` command for chaining
1489
+ */
1490
+ action(fn) {
1491
+ const listener = (args) => {
1492
+ const expectedArgsCount = this.registeredArguments.length;
1493
+ const actionArgs = args.slice(0, expectedArgsCount);
1494
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1495
+ else actionArgs[expectedArgsCount] = this.opts();
1496
+ actionArgs.push(this);
1497
+ return fn.apply(this, actionArgs);
1498
+ };
1499
+ this._actionHandler = listener;
1500
+ return this;
1501
+ }
1502
+ /**
1503
+ * Factory routine to create a new unattached option.
1504
+ *
1505
+ * See .option() for creating an attached option, which uses this routine to
1506
+ * create the option. You can override createOption to return a custom option.
1507
+ *
1508
+ * @param {string} flags
1509
+ * @param {string} [description]
1510
+ * @return {Option} new option
1511
+ */
1512
+ createOption(flags, description) {
1513
+ return new Option(flags, description);
1514
+ }
1515
+ /**
1516
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1517
+ *
1518
+ * @param {(Option | Argument)} target
1519
+ * @param {string} value
1520
+ * @param {*} previous
1521
+ * @param {string} invalidArgumentMessage
1522
+ * @private
1523
+ */
1524
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1525
+ try {
1526
+ return target.parseArg(value, previous);
1527
+ } catch (err) {
1528
+ if (err.code === "commander.invalidArgument") {
1529
+ const message = `${invalidArgumentMessage} ${err.message}`;
1530
+ this.error(message, {
1531
+ exitCode: err.exitCode,
1532
+ code: err.code
1533
+ });
1534
+ }
1535
+ throw err;
1536
+ }
1537
+ }
1538
+ /**
1539
+ * Check for option flag conflicts.
1540
+ * Register option if no conflicts found, or throw on conflict.
1541
+ *
1542
+ * @param {Option} option
1543
+ * @private
1544
+ */
1545
+ _registerOption(option) {
1546
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1547
+ if (matchingOption) {
1548
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1549
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1550
+ - already used by option '${matchingOption.flags}'`);
1551
+ }
1552
+ this._initOptionGroup(option);
1553
+ this.options.push(option);
1554
+ }
1555
+ /**
1556
+ * Check for command name and alias conflicts with existing commands.
1557
+ * Register command if no conflicts found, or throw on conflict.
1558
+ *
1559
+ * @param {Command} command
1560
+ * @private
1561
+ */
1562
+ _registerCommand(command) {
1563
+ const knownBy = (cmd) => {
1564
+ return [cmd.name()].concat(cmd.aliases());
1565
+ };
1566
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1567
+ if (alreadyUsed) {
1568
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1569
+ const newCmd = knownBy(command).join("|");
1570
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1571
+ }
1572
+ this._initCommandGroup(command);
1573
+ this.commands.push(command);
1574
+ }
1575
+ /**
1576
+ * Add an option.
1577
+ *
1578
+ * @param {Option} option
1579
+ * @return {Command} `this` command for chaining
1580
+ */
1581
+ addOption(option) {
1582
+ this._registerOption(option);
1583
+ const oname = option.name();
1584
+ const name = option.attributeName();
1585
+ if (option.negate) {
1586
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1587
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1588
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1589
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1590
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1591
+ const oldValue = this.getOptionValue(name);
1592
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1593
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1594
+ if (val == null) if (option.negate) val = false;
1595
+ else if (option.isBoolean() || option.optional) val = true;
1596
+ else val = "";
1597
+ this.setOptionValueWithSource(name, val, valueSource);
1598
+ };
1599
+ this.on("option:" + oname, (val) => {
1600
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1601
+ });
1602
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1603
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1604
+ });
1605
+ return this;
1606
+ }
1607
+ /**
1608
+ * Internal implementation shared by .option() and .requiredOption()
1609
+ *
1610
+ * @return {Command} `this` command for chaining
1611
+ * @private
1612
+ */
1613
+ _optionEx(config, flags, description, fn, defaultValue) {
1614
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1615
+ const option = this.createOption(flags, description);
1616
+ option.makeOptionMandatory(!!config.mandatory);
1617
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1618
+ else if (fn instanceof RegExp) {
1619
+ const regex = fn;
1620
+ fn = (val, def) => {
1621
+ const m = regex.exec(val);
1622
+ return m ? m[0] : def;
1623
+ };
1624
+ option.default(defaultValue).argParser(fn);
1625
+ } else option.default(fn);
1626
+ return this.addOption(option);
1627
+ }
1628
+ /**
1629
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1630
+ *
1631
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1632
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1633
+ *
1634
+ * See the README for more details, and see also addOption() and requiredOption().
1635
+ *
1636
+ * @example
1637
+ * program
1638
+ * .option('-p, --pepper', 'add pepper')
1639
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1640
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1641
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1642
+ *
1643
+ * @param {string} flags
1644
+ * @param {string} [description]
1645
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1646
+ * @param {*} [defaultValue]
1647
+ * @return {Command} `this` command for chaining
1648
+ */
1649
+ option(flags, description, parseArg, defaultValue) {
1650
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1651
+ }
1652
+ /**
1653
+ * Add a required option which must have a value after parsing. This usually means
1654
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1655
+ *
1656
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1657
+ *
1658
+ * @param {string} flags
1659
+ * @param {string} [description]
1660
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1661
+ * @param {*} [defaultValue]
1662
+ * @return {Command} `this` command for chaining
1663
+ */
1664
+ requiredOption(flags, description, parseArg, defaultValue) {
1665
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1666
+ }
1667
+ /**
1668
+ * Alter parsing of short flags with optional values.
1669
+ *
1670
+ * @example
1671
+ * // for `.option('-f,--flag [value]'):
1672
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1673
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1674
+ *
1675
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1676
+ * @return {Command} `this` command for chaining
1677
+ */
1678
+ combineFlagAndOptionalValue(combine = true) {
1679
+ this._combineFlagAndOptionalValue = !!combine;
1680
+ return this;
1681
+ }
1682
+ /**
1683
+ * Allow unknown options on the command line.
1684
+ *
1685
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1686
+ * @return {Command} `this` command for chaining
1687
+ */
1688
+ allowUnknownOption(allowUnknown = true) {
1689
+ this._allowUnknownOption = !!allowUnknown;
1690
+ return this;
1691
+ }
1692
+ /**
1693
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1694
+ *
1695
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1696
+ * @return {Command} `this` command for chaining
1697
+ */
1698
+ allowExcessArguments(allowExcess = true) {
1699
+ this._allowExcessArguments = !!allowExcess;
1700
+ return this;
1701
+ }
1702
+ /**
1703
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1704
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1705
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1706
+ *
1707
+ * @param {boolean} [positional]
1708
+ * @return {Command} `this` command for chaining
1709
+ */
1710
+ enablePositionalOptions(positional = true) {
1711
+ this._enablePositionalOptions = !!positional;
1712
+ return this;
1713
+ }
1714
+ /**
1715
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1716
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1717
+ * positional options to have been enabled on the program (parent commands).
1718
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1719
+ *
1720
+ * @param {boolean} [passThrough] for unknown options.
1721
+ * @return {Command} `this` command for chaining
1722
+ */
1723
+ passThroughOptions(passThrough = true) {
1724
+ this._passThroughOptions = !!passThrough;
1725
+ this._checkForBrokenPassThrough();
1726
+ return this;
1727
+ }
1728
+ /**
1729
+ * @private
1730
+ */
1731
+ _checkForBrokenPassThrough() {
1732
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1733
+ }
1734
+ /**
1735
+ * Whether to store option values as properties on command object,
1736
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1737
+ *
1738
+ * @param {boolean} [storeAsProperties=true]
1739
+ * @return {Command} `this` command for chaining
1740
+ */
1741
+ storeOptionsAsProperties(storeAsProperties = true) {
1742
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1743
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1744
+ this._storeOptionsAsProperties = !!storeAsProperties;
1745
+ return this;
1746
+ }
1747
+ /**
1748
+ * Retrieve option value.
1749
+ *
1750
+ * @param {string} key
1751
+ * @return {object} value
1752
+ */
1753
+ getOptionValue(key) {
1754
+ if (this._storeOptionsAsProperties) return this[key];
1755
+ return this._optionValues[key];
1756
+ }
1757
+ /**
1758
+ * Store option value.
1759
+ *
1760
+ * @param {string} key
1761
+ * @param {object} value
1762
+ * @return {Command} `this` command for chaining
1763
+ */
1764
+ setOptionValue(key, value) {
1765
+ return this.setOptionValueWithSource(key, value, void 0);
1766
+ }
1767
+ /**
1768
+ * Store option value and where the value came from.
1769
+ *
1770
+ * @param {string} key
1771
+ * @param {object} value
1772
+ * @param {string} source - expected values are default/config/env/cli/implied
1773
+ * @return {Command} `this` command for chaining
1774
+ */
1775
+ setOptionValueWithSource(key, value, source) {
1776
+ if (this._storeOptionsAsProperties) this[key] = value;
1777
+ else this._optionValues[key] = value;
1778
+ this._optionValueSources[key] = source;
1779
+ return this;
1780
+ }
1781
+ /**
1782
+ * Get source of option value.
1783
+ * Expected values are default | config | env | cli | implied
1784
+ *
1785
+ * @param {string} key
1786
+ * @return {string}
1787
+ */
1788
+ getOptionValueSource(key) {
1789
+ return this._optionValueSources[key];
1790
+ }
1791
+ /**
1792
+ * Get source of option value. See also .optsWithGlobals().
1793
+ * Expected values are default | config | env | cli | implied
1794
+ *
1795
+ * @param {string} key
1796
+ * @return {string}
1797
+ */
1798
+ getOptionValueSourceWithGlobals(key) {
1799
+ let source;
1800
+ this._getCommandAndAncestors().forEach((cmd) => {
1801
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1802
+ });
1803
+ return source;
1804
+ }
1805
+ /**
1806
+ * Get user arguments from implied or explicit arguments.
1807
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1808
+ *
1809
+ * @private
1810
+ */
1811
+ _prepareUserArgs(argv, parseOptions) {
1812
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1813
+ parseOptions = parseOptions || {};
1814
+ if (argv === void 0 && parseOptions.from === void 0) {
1815
+ if (process$1.versions?.electron) parseOptions.from = "electron";
1816
+ const execArgv = process$1.execArgv ?? [];
1817
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1818
+ }
1819
+ if (argv === void 0) argv = process$1.argv;
1820
+ this.rawArgs = argv.slice();
1821
+ let userArgs;
1822
+ switch (parseOptions.from) {
1823
+ case void 0:
1824
+ case "node":
1825
+ this._scriptPath = argv[1];
1826
+ userArgs = argv.slice(2);
1827
+ break;
1828
+ case "electron":
1829
+ if (process$1.defaultApp) {
1830
+ this._scriptPath = argv[1];
1831
+ userArgs = argv.slice(2);
1832
+ } else userArgs = argv.slice(1);
1833
+ break;
1834
+ case "user":
1835
+ userArgs = argv.slice(0);
1836
+ break;
1837
+ case "eval":
1838
+ userArgs = argv.slice(1);
1839
+ break;
1840
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1841
+ }
1842
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1843
+ this._name = this._name || "program";
1844
+ return userArgs;
1845
+ }
1846
+ /**
1847
+ * Parse `argv`, setting options and invoking commands when defined.
1848
+ *
1849
+ * Use parseAsync instead of parse if any of your action handlers are async.
1850
+ *
1851
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1852
+ *
1853
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1854
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1855
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1856
+ * - `'user'`: just user arguments
1857
+ *
1858
+ * @example
1859
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1860
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1861
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1862
+ *
1863
+ * @param {string[]} [argv] - optional, defaults to process.argv
1864
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1865
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1866
+ * @return {Command} `this` command for chaining
1867
+ */
1868
+ parse(argv, parseOptions) {
1869
+ this._prepareForParse();
1870
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1871
+ this._parseCommand([], userArgs);
1872
+ return this;
1873
+ }
1874
+ /**
1875
+ * Parse `argv`, setting options and invoking commands when defined.
1876
+ *
1877
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1878
+ *
1879
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1880
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1881
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1882
+ * - `'user'`: just user arguments
1883
+ *
1884
+ * @example
1885
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1886
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1887
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1888
+ *
1889
+ * @param {string[]} [argv]
1890
+ * @param {object} [parseOptions]
1891
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1892
+ * @return {Promise}
1893
+ */
1894
+ async parseAsync(argv, parseOptions) {
1895
+ this._prepareForParse();
1896
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1897
+ await this._parseCommand([], userArgs);
1898
+ return this;
1899
+ }
1900
+ _prepareForParse() {
1901
+ if (this._savedState === null) this.saveStateBeforeParse();
1902
+ else this.restoreStateBeforeParse();
1903
+ }
1904
+ /**
1905
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1906
+ * Not usually called directly, but available for subclasses to save their custom state.
1907
+ *
1908
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1909
+ */
1910
+ saveStateBeforeParse() {
1911
+ this._savedState = {
1912
+ _name: this._name,
1913
+ _optionValues: { ...this._optionValues },
1914
+ _optionValueSources: { ...this._optionValueSources }
1915
+ };
1916
+ }
1917
+ /**
1918
+ * Restore state before parse for calls after the first.
1919
+ * Not usually called directly, but available for subclasses to save their custom state.
1920
+ *
1921
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1922
+ */
1923
+ restoreStateBeforeParse() {
1924
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1925
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1926
+ this._name = this._savedState._name;
1927
+ this._scriptPath = null;
1928
+ this.rawArgs = [];
1929
+ this._optionValues = { ...this._savedState._optionValues };
1930
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1931
+ this.args = [];
1932
+ this.processedArgs = [];
1933
+ }
1934
+ /**
1935
+ * Throw if expected executable is missing. Add lots of help for author.
1936
+ *
1937
+ * @param {string} executableFile
1938
+ * @param {string} executableDir
1939
+ * @param {string} subcommandName
1940
+ */
1941
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1942
+ if (fs.existsSync(executableFile)) return;
1943
+ const executableMissing = `'${executableFile}' does not exist
1944
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1945
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1946
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1947
+ throw new Error(executableMissing);
1948
+ }
1949
+ /**
1950
+ * Execute a sub-command executable.
1951
+ *
1952
+ * @private
1953
+ */
1954
+ _executeSubCommand(subcommand, args) {
1955
+ args = args.slice();
1956
+ let launchWithNode = false;
1957
+ const sourceExt = [
1958
+ ".js",
1959
+ ".ts",
1960
+ ".tsx",
1961
+ ".mjs",
1962
+ ".cjs"
1963
+ ];
1964
+ function findFile(baseDir, baseName) {
1965
+ const localBin = path.resolve(baseDir, baseName);
1966
+ if (fs.existsSync(localBin)) return localBin;
1967
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1968
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1969
+ if (foundExt) return `${localBin}${foundExt}`;
1970
+ }
1971
+ this._checkForMissingMandatoryOptions();
1972
+ this._checkForConflictingOptions();
1973
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1974
+ let executableDir = this._executableDir || "";
1975
+ if (this._scriptPath) {
1976
+ let resolvedScriptPath;
1977
+ try {
1978
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1979
+ } catch {
1980
+ resolvedScriptPath = this._scriptPath;
1981
+ }
1982
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1983
+ }
1984
+ if (executableDir) {
1985
+ let localFile = findFile(executableDir, executableFile);
1986
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1987
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1988
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1989
+ }
1990
+ executableFile = localFile || executableFile;
1991
+ }
1992
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1993
+ let proc;
1994
+ if (process$1.platform !== "win32") if (launchWithNode) {
1995
+ args.unshift(executableFile);
1996
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
1997
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
1998
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1999
+ else {
2000
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2001
+ args.unshift(executableFile);
2002
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2003
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
2004
+ }
2005
+ if (!proc.killed) [
2006
+ "SIGUSR1",
2007
+ "SIGUSR2",
2008
+ "SIGTERM",
2009
+ "SIGINT",
2010
+ "SIGHUP"
2011
+ ].forEach((signal) => {
2012
+ process$1.on(signal, () => {
2013
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2014
+ });
2015
+ });
2016
+ const exitCallback = this._exitCallback;
2017
+ proc.on("close", (code) => {
2018
+ code = code ?? 1;
2019
+ if (!exitCallback) process$1.exit(code);
2020
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2021
+ });
2022
+ proc.on("error", (err) => {
2023
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2024
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2025
+ if (!exitCallback) process$1.exit(1);
2026
+ else {
2027
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2028
+ wrappedError.nestedError = err;
2029
+ exitCallback(wrappedError);
2030
+ }
2031
+ });
2032
+ this.runningCommand = proc;
2033
+ }
2034
+ /**
2035
+ * @private
2036
+ */
2037
+ _dispatchSubcommand(commandName, operands, unknown) {
2038
+ const subCommand = this._findCommand(commandName);
2039
+ if (!subCommand) this.help({ error: true });
2040
+ subCommand._prepareForParse();
2041
+ let promiseChain;
2042
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2043
+ promiseChain = this._chainOrCall(promiseChain, () => {
2044
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2045
+ else return subCommand._parseCommand(operands, unknown);
2046
+ });
2047
+ return promiseChain;
2048
+ }
2049
+ /**
2050
+ * Invoke help directly if possible, or dispatch if necessary.
2051
+ * e.g. help foo
2052
+ *
2053
+ * @private
2054
+ */
2055
+ _dispatchHelpCommand(subcommandName) {
2056
+ if (!subcommandName) this.help();
2057
+ const subCommand = this._findCommand(subcommandName);
2058
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2059
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2060
+ }
2061
+ /**
2062
+ * Check this.args against expected this.registeredArguments.
2063
+ *
2064
+ * @private
2065
+ */
2066
+ _checkNumberOfArguments() {
2067
+ this.registeredArguments.forEach((arg, i) => {
2068
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2069
+ });
2070
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2071
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2072
+ }
2073
+ /**
2074
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2075
+ *
2076
+ * @private
2077
+ */
2078
+ _processArguments() {
2079
+ const myParseArg = (argument, value, previous) => {
2080
+ let parsedValue = value;
2081
+ if (value !== null && argument.parseArg) {
2082
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2083
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2084
+ }
2085
+ return parsedValue;
2086
+ };
2087
+ this._checkNumberOfArguments();
2088
+ const processedArgs = [];
2089
+ this.registeredArguments.forEach((declaredArg, index) => {
2090
+ let value = declaredArg.defaultValue;
2091
+ if (declaredArg.variadic) {
2092
+ if (index < this.args.length) {
2093
+ value = this.args.slice(index);
2094
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2095
+ return myParseArg(declaredArg, v, processed);
2096
+ }, declaredArg.defaultValue);
2097
+ } else if (value === void 0) value = [];
2098
+ } else if (index < this.args.length) {
2099
+ value = this.args[index];
2100
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2101
+ }
2102
+ processedArgs[index] = value;
2103
+ });
2104
+ this.processedArgs = processedArgs;
2105
+ }
2106
+ /**
2107
+ * Once we have a promise we chain, but call synchronously until then.
2108
+ *
2109
+ * @param {(Promise|undefined)} promise
2110
+ * @param {Function} fn
2111
+ * @return {(Promise|undefined)}
2112
+ * @private
2113
+ */
2114
+ _chainOrCall(promise, fn) {
2115
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2116
+ return fn();
2117
+ }
2118
+ /**
2119
+ *
2120
+ * @param {(Promise|undefined)} promise
2121
+ * @param {string} event
2122
+ * @return {(Promise|undefined)}
2123
+ * @private
2124
+ */
2125
+ _chainOrCallHooks(promise, event) {
2126
+ let result = promise;
2127
+ const hooks = [];
2128
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2129
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2130
+ hooks.push({
2131
+ hookedCommand,
2132
+ callback
2133
+ });
2134
+ });
2135
+ });
2136
+ if (event === "postAction") hooks.reverse();
2137
+ hooks.forEach((hookDetail) => {
2138
+ result = this._chainOrCall(result, () => {
2139
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2140
+ });
2141
+ });
2142
+ return result;
2143
+ }
2144
+ /**
2145
+ *
2146
+ * @param {(Promise|undefined)} promise
2147
+ * @param {Command} subCommand
2148
+ * @param {string} event
2149
+ * @return {(Promise|undefined)}
2150
+ * @private
2151
+ */
2152
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2153
+ let result = promise;
2154
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2155
+ result = this._chainOrCall(result, () => {
2156
+ return hook(this, subCommand);
2157
+ });
2158
+ });
2159
+ return result;
2160
+ }
2161
+ /**
2162
+ * Process arguments in context of this command.
2163
+ * Returns action result, in case it is a promise.
2164
+ *
2165
+ * @private
2166
+ */
2167
+ _parseCommand(operands, unknown) {
2168
+ const parsed = this.parseOptions(unknown);
2169
+ this._parseOptionsEnv();
2170
+ this._parseOptionsImplied();
2171
+ operands = operands.concat(parsed.operands);
2172
+ unknown = parsed.unknown;
2173
+ this.args = operands.concat(unknown);
2174
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2175
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2176
+ if (this._defaultCommandName) {
2177
+ this._outputHelpIfRequested(unknown);
2178
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2179
+ }
2180
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2181
+ this._outputHelpIfRequested(parsed.unknown);
2182
+ this._checkForMissingMandatoryOptions();
2183
+ this._checkForConflictingOptions();
2184
+ const checkForUnknownOptions = () => {
2185
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2186
+ };
2187
+ const commandEvent = `command:${this.name()}`;
2188
+ if (this._actionHandler) {
2189
+ checkForUnknownOptions();
2190
+ this._processArguments();
2191
+ let promiseChain;
2192
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2193
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2194
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2195
+ this.parent.emit(commandEvent, operands, unknown);
2196
+ });
2197
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2198
+ return promiseChain;
2199
+ }
2200
+ if (this.parent?.listenerCount(commandEvent)) {
2201
+ checkForUnknownOptions();
2202
+ this._processArguments();
2203
+ this.parent.emit(commandEvent, operands, unknown);
2204
+ } else if (operands.length) {
2205
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2206
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2207
+ else if (this.commands.length) this.unknownCommand();
2208
+ else {
2209
+ checkForUnknownOptions();
2210
+ this._processArguments();
2211
+ }
2212
+ } else if (this.commands.length) {
2213
+ checkForUnknownOptions();
2214
+ this.help({ error: true });
2215
+ } else {
2216
+ checkForUnknownOptions();
2217
+ this._processArguments();
2218
+ }
2219
+ }
2220
+ /**
2221
+ * Find matching command.
2222
+ *
2223
+ * @private
2224
+ * @return {Command | undefined}
2225
+ */
2226
+ _findCommand(name) {
2227
+ if (!name) return void 0;
2228
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2229
+ }
2230
+ /**
2231
+ * Return an option matching `arg` if any.
2232
+ *
2233
+ * @param {string} arg
2234
+ * @return {Option}
2235
+ * @package
2236
+ */
2237
+ _findOption(arg) {
2238
+ return this.options.find((option) => option.is(arg));
2239
+ }
2240
+ /**
2241
+ * Display an error message if a mandatory option does not have a value.
2242
+ * Called after checking for help flags in leaf subcommand.
2243
+ *
2244
+ * @private
2245
+ */
2246
+ _checkForMissingMandatoryOptions() {
2247
+ this._getCommandAndAncestors().forEach((cmd) => {
2248
+ cmd.options.forEach((anOption) => {
2249
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2250
+ });
2251
+ });
2252
+ }
2253
+ /**
2254
+ * Display an error message if conflicting options are used together in this.
2255
+ *
2256
+ * @private
2257
+ */
2258
+ _checkForConflictingLocalOptions() {
2259
+ const definedNonDefaultOptions = this.options.filter((option) => {
2260
+ const optionKey = option.attributeName();
2261
+ if (this.getOptionValue(optionKey) === void 0) return false;
2262
+ return this.getOptionValueSource(optionKey) !== "default";
2263
+ });
2264
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2265
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2266
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2267
+ });
2268
+ }
2269
+ /**
2270
+ * Display an error message if conflicting options are used together.
2271
+ * Called after checking for help flags in leaf subcommand.
2272
+ *
2273
+ * @private
2274
+ */
2275
+ _checkForConflictingOptions() {
2276
+ this._getCommandAndAncestors().forEach((cmd) => {
2277
+ cmd._checkForConflictingLocalOptions();
2278
+ });
2279
+ }
2280
+ /**
2281
+ * Parse options from `argv` removing known options,
2282
+ * and return argv split into operands and unknown arguments.
2283
+ *
2284
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2285
+ *
2286
+ * Examples:
2287
+ *
2288
+ * argv => operands, unknown
2289
+ * --known kkk op => [op], []
2290
+ * op --known kkk => [op], []
2291
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2292
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2293
+ *
2294
+ * @param {string[]} args
2295
+ * @return {{operands: string[], unknown: string[]}}
2296
+ */
2297
+ parseOptions(args) {
2298
+ const operands = [];
2299
+ const unknown = [];
2300
+ let dest = operands;
2301
+ function maybeOption(arg) {
2302
+ return arg.length > 1 && arg[0] === "-";
2303
+ }
2304
+ const negativeNumberArg = (arg) => {
2305
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2306
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2307
+ };
2308
+ let activeVariadicOption = null;
2309
+ let activeGroup = null;
2310
+ let i = 0;
2311
+ while (i < args.length || activeGroup) {
2312
+ const arg = activeGroup ?? args[i++];
2313
+ activeGroup = null;
2314
+ if (arg === "--") {
2315
+ if (dest === unknown) dest.push(arg);
2316
+ dest.push(...args.slice(i));
2317
+ break;
2318
+ }
2319
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2320
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2321
+ continue;
2322
+ }
2323
+ activeVariadicOption = null;
2324
+ if (maybeOption(arg)) {
2325
+ const option = this._findOption(arg);
2326
+ if (option) {
2327
+ if (option.required) {
2328
+ const value = args[i++];
2329
+ if (value === void 0) this.optionMissingArgument(option);
2330
+ this.emit(`option:${option.name()}`, value);
2331
+ } else if (option.optional) {
2332
+ let value = null;
2333
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2334
+ this.emit(`option:${option.name()}`, value);
2335
+ } else this.emit(`option:${option.name()}`);
2336
+ activeVariadicOption = option.variadic ? option : null;
2337
+ continue;
2338
+ }
2339
+ }
2340
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2341
+ const option = this._findOption(`-${arg[1]}`);
2342
+ if (option) {
2343
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2344
+ else {
2345
+ this.emit(`option:${option.name()}`);
2346
+ activeGroup = `-${arg.slice(2)}`;
2347
+ }
2348
+ continue;
2349
+ }
2350
+ }
2351
+ if (/^--[^=]+=/.test(arg)) {
2352
+ const index = arg.indexOf("=");
2353
+ const option = this._findOption(arg.slice(0, index));
2354
+ if (option && (option.required || option.optional)) {
2355
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2356
+ continue;
2357
+ }
2358
+ }
2359
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2360
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2361
+ if (this._findCommand(arg)) {
2362
+ operands.push(arg);
2363
+ unknown.push(...args.slice(i));
2364
+ break;
2365
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2366
+ operands.push(arg, ...args.slice(i));
2367
+ break;
2368
+ } else if (this._defaultCommandName) {
2369
+ unknown.push(arg, ...args.slice(i));
2370
+ break;
2371
+ }
2372
+ }
2373
+ if (this._passThroughOptions) {
2374
+ dest.push(arg, ...args.slice(i));
2375
+ break;
2376
+ }
2377
+ dest.push(arg);
2378
+ }
2379
+ return {
2380
+ operands,
2381
+ unknown
2382
+ };
2383
+ }
2384
+ /**
2385
+ * Return an object containing local option values as key-value pairs.
2386
+ *
2387
+ * @return {object}
2388
+ */
2389
+ opts() {
2390
+ if (this._storeOptionsAsProperties) {
2391
+ const result = {};
2392
+ const len = this.options.length;
2393
+ for (let i = 0; i < len; i++) {
2394
+ const key = this.options[i].attributeName();
2395
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2396
+ }
2397
+ return result;
2398
+ }
2399
+ return this._optionValues;
2400
+ }
2401
+ /**
2402
+ * Return an object containing merged local and global option values as key-value pairs.
2403
+ *
2404
+ * @return {object}
2405
+ */
2406
+ optsWithGlobals() {
2407
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2408
+ }
2409
+ /**
2410
+ * Display error message and exit (or call exitOverride).
2411
+ *
2412
+ * @param {string} message
2413
+ * @param {object} [errorOptions]
2414
+ * @param {string} [errorOptions.code] - an id string representing the error
2415
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2416
+ */
2417
+ error(message, errorOptions) {
2418
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2419
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2420
+ else if (this._showHelpAfterError) {
2421
+ this._outputConfiguration.writeErr("\n");
2422
+ this.outputHelp({ error: true });
2423
+ }
2424
+ const config = errorOptions || {};
2425
+ const exitCode = config.exitCode || 1;
2426
+ const code = config.code || "commander.error";
2427
+ this._exit(exitCode, code, message);
2428
+ }
2429
+ /**
2430
+ * Apply any option related environment variables, if option does
2431
+ * not have a value from cli or client code.
2432
+ *
2433
+ * @private
2434
+ */
2435
+ _parseOptionsEnv() {
2436
+ this.options.forEach((option) => {
2437
+ if (option.envVar && option.envVar in process$1.env) {
2438
+ const optionKey = option.attributeName();
2439
+ if (this.getOptionValue(optionKey) === void 0 || [
2440
+ "default",
2441
+ "config",
2442
+ "env"
2443
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2444
+ else this.emit(`optionEnv:${option.name()}`);
2445
+ }
2446
+ });
2447
+ }
2448
+ /**
2449
+ * Apply any implied option values, if option is undefined or default value.
2450
+ *
2451
+ * @private
2452
+ */
2453
+ _parseOptionsImplied() {
2454
+ const dualHelper = new DualOptions(this.options);
2455
+ const hasCustomOptionValue = (optionKey) => {
2456
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2457
+ };
2458
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2459
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2460
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2461
+ });
2462
+ });
2463
+ }
2464
+ /**
2465
+ * Argument `name` is missing.
2466
+ *
2467
+ * @param {string} name
2468
+ * @private
2469
+ */
2470
+ missingArgument(name) {
2471
+ const message = `error: missing required argument '${name}'`;
2472
+ this.error(message, { code: "commander.missingArgument" });
2473
+ }
2474
+ /**
2475
+ * `Option` is missing an argument.
2476
+ *
2477
+ * @param {Option} option
2478
+ * @private
2479
+ */
2480
+ optionMissingArgument(option) {
2481
+ const message = `error: option '${option.flags}' argument missing`;
2482
+ this.error(message, { code: "commander.optionMissingArgument" });
2483
+ }
2484
+ /**
2485
+ * `Option` does not have a value, and is a mandatory option.
2486
+ *
2487
+ * @param {Option} option
2488
+ * @private
2489
+ */
2490
+ missingMandatoryOptionValue(option) {
2491
+ const message = `error: required option '${option.flags}' not specified`;
2492
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2493
+ }
2494
+ /**
2495
+ * `Option` conflicts with another option.
2496
+ *
2497
+ * @param {Option} option
2498
+ * @param {Option} conflictingOption
2499
+ * @private
2500
+ */
2501
+ _conflictingOption(option, conflictingOption) {
2502
+ const findBestOptionFromValue = (option) => {
2503
+ const optionKey = option.attributeName();
2504
+ const optionValue = this.getOptionValue(optionKey);
2505
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2506
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2507
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2508
+ return positiveOption || option;
2509
+ };
2510
+ const getErrorMessage = (option) => {
2511
+ const bestOption = findBestOptionFromValue(option);
2512
+ const optionKey = bestOption.attributeName();
2513
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2514
+ return `option '${bestOption.flags}'`;
2515
+ };
2516
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2517
+ this.error(message, { code: "commander.conflictingOption" });
2518
+ }
2519
+ /**
2520
+ * Unknown option `flag`.
2521
+ *
2522
+ * @param {string} flag
2523
+ * @private
2524
+ */
2525
+ unknownOption(flag) {
2526
+ if (this._allowUnknownOption) return;
2527
+ let suggestion = "";
2528
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2529
+ let candidateFlags = [];
2530
+ let command = this;
2531
+ do {
2532
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2533
+ candidateFlags = candidateFlags.concat(moreFlags);
2534
+ command = command.parent;
2535
+ } while (command && !command._enablePositionalOptions);
2536
+ suggestion = suggestSimilar(flag, candidateFlags);
2537
+ }
2538
+ const message = `error: unknown option '${flag}'${suggestion}`;
2539
+ this.error(message, { code: "commander.unknownOption" });
2540
+ }
2541
+ /**
2542
+ * Excess arguments, more than expected.
2543
+ *
2544
+ * @param {string[]} receivedArgs
2545
+ * @private
2546
+ */
2547
+ _excessArguments(receivedArgs) {
2548
+ if (this._allowExcessArguments) return;
2549
+ const expected = this.registeredArguments.length;
2550
+ const s = expected === 1 ? "" : "s";
2551
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2552
+ this.error(message, { code: "commander.excessArguments" });
2553
+ }
2554
+ /**
2555
+ * Unknown command.
2556
+ *
2557
+ * @private
2558
+ */
2559
+ unknownCommand() {
2560
+ const unknownName = this.args[0];
2561
+ let suggestion = "";
2562
+ if (this._showSuggestionAfterError) {
2563
+ const candidateNames = [];
2564
+ this.createHelp().visibleCommands(this).forEach((command) => {
2565
+ candidateNames.push(command.name());
2566
+ if (command.alias()) candidateNames.push(command.alias());
2567
+ });
2568
+ suggestion = suggestSimilar(unknownName, candidateNames);
2569
+ }
2570
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2571
+ this.error(message, { code: "commander.unknownCommand" });
2572
+ }
2573
+ /**
2574
+ * Get or set the program version.
2575
+ *
2576
+ * This method auto-registers the "-V, --version" option which will print the version number.
2577
+ *
2578
+ * You can optionally supply the flags and description to override the defaults.
2579
+ *
2580
+ * @param {string} [str]
2581
+ * @param {string} [flags]
2582
+ * @param {string} [description]
2583
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2584
+ */
2585
+ version(str, flags, description) {
2586
+ if (str === void 0) return this._version;
2587
+ this._version = str;
2588
+ flags = flags || "-V, --version";
2589
+ description = description || "output the version number";
2590
+ const versionOption = this.createOption(flags, description);
2591
+ this._versionOptionName = versionOption.attributeName();
2592
+ this._registerOption(versionOption);
2593
+ this.on("option:" + versionOption.name(), () => {
2594
+ this._outputConfiguration.writeOut(`${str}\n`);
2595
+ this._exit(0, "commander.version", str);
2596
+ });
2597
+ return this;
2598
+ }
2599
+ /**
2600
+ * Set the description.
2601
+ *
2602
+ * @param {string} [str]
2603
+ * @param {object} [argsDescription]
2604
+ * @return {(string|Command)}
2605
+ */
2606
+ description(str, argsDescription) {
2607
+ if (str === void 0 && argsDescription === void 0) return this._description;
2608
+ this._description = str;
2609
+ if (argsDescription) this._argsDescription = argsDescription;
2610
+ return this;
2611
+ }
2612
+ /**
2613
+ * Set the summary. Used when listed as subcommand of parent.
2614
+ *
2615
+ * @param {string} [str]
2616
+ * @return {(string|Command)}
2617
+ */
2618
+ summary(str) {
2619
+ if (str === void 0) return this._summary;
2620
+ this._summary = str;
2621
+ return this;
2622
+ }
2623
+ /**
2624
+ * Set an alias for the command.
2625
+ *
2626
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2627
+ *
2628
+ * @param {string} [alias]
2629
+ * @return {(string|Command)}
2630
+ */
2631
+ alias(alias) {
2632
+ if (alias === void 0) return this._aliases[0];
2633
+ /** @type {Command} */
2634
+ let command = this;
2635
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2636
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2637
+ const matchingCommand = this.parent?._findCommand(alias);
2638
+ if (matchingCommand) {
2639
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2640
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2641
+ }
2642
+ command._aliases.push(alias);
2643
+ return this;
2644
+ }
2645
+ /**
2646
+ * Set aliases for the command.
2647
+ *
2648
+ * Only the first alias is shown in the auto-generated help.
2649
+ *
2650
+ * @param {string[]} [aliases]
2651
+ * @return {(string[]|Command)}
2652
+ */
2653
+ aliases(aliases) {
2654
+ if (aliases === void 0) return this._aliases;
2655
+ aliases.forEach((alias) => this.alias(alias));
2656
+ return this;
2657
+ }
2658
+ /**
2659
+ * Set / get the command usage `str`.
2660
+ *
2661
+ * @param {string} [str]
2662
+ * @return {(string|Command)}
2663
+ */
2664
+ usage(str) {
2665
+ if (str === void 0) {
2666
+ if (this._usage) return this._usage;
2667
+ const args = this.registeredArguments.map((arg) => {
2668
+ return humanReadableArgName(arg);
2669
+ });
2670
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2671
+ }
2672
+ this._usage = str;
2673
+ return this;
2674
+ }
2675
+ /**
2676
+ * Get or set the name of the command.
2677
+ *
2678
+ * @param {string} [str]
2679
+ * @return {(string|Command)}
2680
+ */
2681
+ name(str) {
2682
+ if (str === void 0) return this._name;
2683
+ this._name = str;
2684
+ return this;
2685
+ }
2686
+ /**
2687
+ * Set/get the help group heading for this subcommand in parent command's help.
2688
+ *
2689
+ * @param {string} [heading]
2690
+ * @return {Command | string}
2691
+ */
2692
+ helpGroup(heading) {
2693
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2694
+ this._helpGroupHeading = heading;
2695
+ return this;
2696
+ }
2697
+ /**
2698
+ * Set/get the default help group heading for subcommands added to this command.
2699
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2700
+ *
2701
+ * @example
2702
+ * program.commandsGroup('Development Commands:);
2703
+ * program.command('watch')...
2704
+ * program.command('lint')...
2705
+ * ...
2706
+ *
2707
+ * @param {string} [heading]
2708
+ * @returns {Command | string}
2709
+ */
2710
+ commandsGroup(heading) {
2711
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2712
+ this._defaultCommandGroup = heading;
2713
+ return this;
2714
+ }
2715
+ /**
2716
+ * Set/get the default help group heading for options added to this command.
2717
+ * (This does not override a group set directly on the option using .helpGroup().)
2718
+ *
2719
+ * @example
2720
+ * program
2721
+ * .optionsGroup('Development Options:')
2722
+ * .option('-d, --debug', 'output extra debugging')
2723
+ * .option('-p, --profile', 'output profiling information')
2724
+ *
2725
+ * @param {string} [heading]
2726
+ * @returns {Command | string}
2727
+ */
2728
+ optionsGroup(heading) {
2729
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2730
+ this._defaultOptionGroup = heading;
2731
+ return this;
2732
+ }
2733
+ /**
2734
+ * @param {Option} option
2735
+ * @private
2736
+ */
2737
+ _initOptionGroup(option) {
2738
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2739
+ }
2740
+ /**
2741
+ * @param {Command} cmd
2742
+ * @private
2743
+ */
2744
+ _initCommandGroup(cmd) {
2745
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2746
+ }
2747
+ /**
2748
+ * Set the name of the command from script filename, such as process.argv[1],
2749
+ * or require.main.filename, or __filename.
2750
+ *
2751
+ * (Used internally and public although not documented in README.)
2752
+ *
2753
+ * @example
2754
+ * program.nameFromFilename(require.main.filename);
2755
+ *
2756
+ * @param {string} filename
2757
+ * @return {Command}
2758
+ */
2759
+ nameFromFilename(filename) {
2760
+ this._name = path.basename(filename, path.extname(filename));
2761
+ return this;
2762
+ }
2763
+ /**
2764
+ * Get or set the directory for searching for executable subcommands of this command.
2765
+ *
2766
+ * @example
2767
+ * program.executableDir(__dirname);
2768
+ * // or
2769
+ * program.executableDir('subcommands');
2770
+ *
2771
+ * @param {string} [path]
2772
+ * @return {(string|null|Command)}
2773
+ */
2774
+ executableDir(path) {
2775
+ if (path === void 0) return this._executableDir;
2776
+ this._executableDir = path;
2777
+ return this;
2778
+ }
2779
+ /**
2780
+ * Return program help documentation.
2781
+ *
2782
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2783
+ * @return {string}
2784
+ */
2785
+ helpInformation(contextOptions) {
2786
+ const helper = this.createHelp();
2787
+ const context = this._getOutputContext(contextOptions);
2788
+ helper.prepareContext({
2789
+ error: context.error,
2790
+ helpWidth: context.helpWidth,
2791
+ outputHasColors: context.hasColors
2792
+ });
2793
+ const text = helper.formatHelp(this, helper);
2794
+ if (context.hasColors) return text;
2795
+ return this._outputConfiguration.stripColor(text);
2796
+ }
2797
+ /**
2798
+ * @typedef HelpContext
2799
+ * @type {object}
2800
+ * @property {boolean} error
2801
+ * @property {number} helpWidth
2802
+ * @property {boolean} hasColors
2803
+ * @property {function} write - includes stripColor if needed
2804
+ *
2805
+ * @returns {HelpContext}
2806
+ * @private
2807
+ */
2808
+ _getOutputContext(contextOptions) {
2809
+ contextOptions = contextOptions || {};
2810
+ const error = !!contextOptions.error;
2811
+ let baseWrite;
2812
+ let hasColors;
2813
+ let helpWidth;
2814
+ if (error) {
2815
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2816
+ hasColors = this._outputConfiguration.getErrHasColors();
2817
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2818
+ } else {
2819
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2820
+ hasColors = this._outputConfiguration.getOutHasColors();
2821
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2822
+ }
2823
+ const write = (str) => {
2824
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2825
+ return baseWrite(str);
2826
+ };
2827
+ return {
2828
+ error,
2829
+ write,
2830
+ hasColors,
2831
+ helpWidth
2832
+ };
2833
+ }
2834
+ /**
2835
+ * Output help information for this command.
2836
+ *
2837
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2838
+ *
2839
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2840
+ */
2841
+ outputHelp(contextOptions) {
2842
+ let deprecatedCallback;
2843
+ if (typeof contextOptions === "function") {
2844
+ deprecatedCallback = contextOptions;
2845
+ contextOptions = void 0;
2846
+ }
2847
+ const outputContext = this._getOutputContext(contextOptions);
2848
+ /** @type {HelpTextEventContext} */
2849
+ const eventContext = {
2850
+ error: outputContext.error,
2851
+ write: outputContext.write,
2852
+ command: this
2853
+ };
2854
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2855
+ this.emit("beforeHelp", eventContext);
2856
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2857
+ if (deprecatedCallback) {
2858
+ helpInformation = deprecatedCallback(helpInformation);
2859
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2860
+ }
2861
+ outputContext.write(helpInformation);
2862
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2863
+ this.emit("afterHelp", eventContext);
2864
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2865
+ }
2866
+ /**
2867
+ * You can pass in flags and a description to customise the built-in help option.
2868
+ * Pass in false to disable the built-in help option.
2869
+ *
2870
+ * @example
2871
+ * program.helpOption('-?, --help' 'show help'); // customise
2872
+ * program.helpOption(false); // disable
2873
+ *
2874
+ * @param {(string | boolean)} flags
2875
+ * @param {string} [description]
2876
+ * @return {Command} `this` command for chaining
2877
+ */
2878
+ helpOption(flags, description) {
2879
+ if (typeof flags === "boolean") {
2880
+ if (flags) {
2881
+ if (this._helpOption === null) this._helpOption = void 0;
2882
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2883
+ } else this._helpOption = null;
2884
+ return this;
2885
+ }
2886
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2887
+ if (flags || description) this._initOptionGroup(this._helpOption);
2888
+ return this;
2889
+ }
2890
+ /**
2891
+ * Lazy create help option.
2892
+ * Returns null if has been disabled with .helpOption(false).
2893
+ *
2894
+ * @returns {(Option | null)} the help option
2895
+ * @package
2896
+ */
2897
+ _getHelpOption() {
2898
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2899
+ return this._helpOption;
2900
+ }
2901
+ /**
2902
+ * Supply your own option to use for the built-in help option.
2903
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2904
+ *
2905
+ * @param {Option} option
2906
+ * @return {Command} `this` command for chaining
2907
+ */
2908
+ addHelpOption(option) {
2909
+ this._helpOption = option;
2910
+ this._initOptionGroup(option);
2911
+ return this;
2912
+ }
2913
+ /**
2914
+ * Output help information and exit.
2915
+ *
2916
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2917
+ *
2918
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2919
+ */
2920
+ help(contextOptions) {
2921
+ this.outputHelp(contextOptions);
2922
+ let exitCode = Number(process$1.exitCode ?? 0);
2923
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2924
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2925
+ }
2926
+ /**
2927
+ * // Do a little typing to coordinate emit and listener for the help text events.
2928
+ * @typedef HelpTextEventContext
2929
+ * @type {object}
2930
+ * @property {boolean} error
2931
+ * @property {Command} command
2932
+ * @property {function} write
2933
+ */
2934
+ /**
2935
+ * Add additional text to be displayed with the built-in help.
2936
+ *
2937
+ * Position is 'before' or 'after' to affect just this command,
2938
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2939
+ *
2940
+ * @param {string} position - before or after built-in help
2941
+ * @param {(string | Function)} text - string to add, or a function returning a string
2942
+ * @return {Command} `this` command for chaining
2943
+ */
2944
+ addHelpText(position, text) {
2945
+ const allowedValues = [
2946
+ "beforeAll",
2947
+ "before",
2948
+ "after",
2949
+ "afterAll"
2950
+ ];
2951
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2952
+ Expecting one of '${allowedValues.join("', '")}'`);
2953
+ const helpEvent = `${position}Help`;
2954
+ this.on(helpEvent, (context) => {
2955
+ let helpStr;
2956
+ if (typeof text === "function") helpStr = text({
2957
+ error: context.error,
2958
+ command: context.command
2959
+ });
2960
+ else helpStr = text;
2961
+ if (helpStr) context.write(`${helpStr}\n`);
2962
+ });
2963
+ return this;
2964
+ }
2965
+ /**
2966
+ * Output help information if help flags specified
2967
+ *
2968
+ * @param {Array} args - array of options to search for help flags
2969
+ * @private
2970
+ */
2971
+ _outputHelpIfRequested(args) {
2972
+ const helpOption = this._getHelpOption();
2973
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2974
+ this.outputHelp();
2975
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2976
+ }
2977
+ }
2978
+ };
2979
+ /**
2980
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2981
+ *
2982
+ * @param {string[]} args - array of arguments from node.execArgv
2983
+ * @returns {string[]}
2984
+ * @private
2985
+ */
2986
+ function incrementNodeInspectorPort(args) {
2987
+ return args.map((arg) => {
2988
+ if (!arg.startsWith("--inspect")) return arg;
2989
+ let debugOption;
2990
+ let debugHost = "127.0.0.1";
2991
+ let debugPort = "9229";
2992
+ let match;
2993
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
2994
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2995
+ debugOption = match[1];
2996
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
2997
+ else debugHost = match[3];
2998
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2999
+ debugOption = match[1];
3000
+ debugHost = match[3];
3001
+ debugPort = match[4];
3002
+ }
3003
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3004
+ return arg;
3005
+ });
3006
+ }
3007
+ /**
3008
+ * @returns {boolean | undefined}
3009
+ * @package
3010
+ */
3011
+ function useColor() {
3012
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
3013
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
3014
+ }
3015
+ exports.Command = Command;
3016
+ exports.useColor = useColor;
3017
+ }));
3018
+ const { program: program$1, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = (/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
3019
+ const { Argument } = require_argument();
3020
+ const { Command } = require_command();
3021
+ const { CommanderError, InvalidArgumentError } = require_error();
3022
+ const { Help } = require_help();
3023
+ const { Option } = require_option();
3024
+ exports.program = new Command();
3025
+ exports.createCommand = (name) => new Command(name);
3026
+ exports.createOption = (flags, description) => new Option(flags, description);
3027
+ exports.createArgument = (name, description) => new Argument(name, description);
3028
+ /**
3029
+ * Expose classes
3030
+ */
3031
+ exports.Command = Command;
3032
+ exports.Option = Option;
3033
+ exports.Argument = Argument;
3034
+ exports.Help = Help;
3035
+ exports.CommanderError = CommanderError;
3036
+ exports.InvalidArgumentError = InvalidArgumentError;
3037
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3038
+ })))(), 1)).default;
3039
+ //#endregion
3040
+ //#region cli/index.ts
3041
+ /**
3042
+ * gdl-instagram — CLI entry point.
3043
+ *
3044
+ * Usage:
3045
+ * gdl-instagram <url> [options] ← auto-detect from URL
3046
+ * gdl-instagram tag <hashtag> [options]
3047
+ * gdl-instagram saved [options]
3048
+ *
3049
+ * Every option is self-documented via ``--help``.
3050
+ */
3051
+ function addSharedOptions(cmd) {
3052
+ return cmd.option("--sessionid <cookie>", "Instagram sessionid cookie value (from browser)", process.env.INSTAGRAM_SESSIONID).option("--cookies <string>", "Full Cookie header string from browser (DevTools → Network → Request Headers → Cookie)", process.env.INSTAGRAM_COOKIES).option("-o, --output <dir>", "Output directory", "./data").option("--videos <mode>", "Download videos: true, false, or merged (yt-dlp)", "true").option("--previews <types>", "Download only previews: video,audio (comma-separated)").option("--audio", "Download standalone audio tracks", false).option("--max-posts <n>", "Maximum number of posts to download", Number.parseInt).option("--cursor <cursor>", "Resume from pagination cursor (see output of previous run)").option("--order-posts <order>", "Post ordering: asc, desc, id, id_asc, id_desc").option("--order-files <order>", "File ordering: r, d (reverse), or empty for natural order").option("--static-videos", "Download static video cover images instead of actual videos", false).option("--no-static-videos", "Do not force static video covers (download real videos)").option("--api <backend>", "API backend: rest (default) or graphql", "rest").option("-v, --verbose", "Verbose debug output", false).option("--include <list>", "For user: comma-separated sub-extractors (posts,reels,tagged,stories,highlights,info,avatar)", "posts").option("--split", "For stories: split each frame into a separate post", false).option("-i, --info", "Print structured post info to terminal (no download)", false);
3053
+ }
3054
+ /** Build config from parsed options */
3055
+ function buildConfig(opts) {
3056
+ const config = new ConfigManager();
3057
+ const ig = {};
3058
+ if (opts.videos) ig.videos = opts.videos;
3059
+ if (opts.previews) ig.previews = opts.previews.split(",");
3060
+ if (opts.audio) ig.audio = true;
3061
+ if (opts.maxPosts) ig["max-posts"] = opts.maxPosts;
3062
+ if (opts.cursor) ig.cursor = opts.cursor;
3063
+ if (opts.orderPosts) ig["order-posts"] = opts.orderPosts;
3064
+ if (opts.orderFiles) ig["order-files"] = opts.orderFiles;
3065
+ if (opts.staticVideos) ig["static-videos"] = true;
3066
+ if (opts.api) ig.api = opts.api;
3067
+ if (opts.include) ig.include = opts.include;
3068
+ if (opts.split) ig.split = true;
3069
+ if (Object.keys(ig).length > 0) config.set("extractor.instagram", ig);
3070
+ return config;
3071
+ }
3072
+ /** Auto-detect the right extractor for a URL */
3073
+ function resolveExtractor(url) {
3074
+ for (const Cls of [
3075
+ InstagramPostExtractor,
3076
+ InstagramStoriesExtractor,
3077
+ InstagramHighlightsExtractor,
3078
+ InstagramTagExtractor,
3079
+ InstagramSavedExtractor,
3080
+ InstagramUserExtractor
3081
+ ]) if (Cls.pattern.test(url)) return Cls;
3082
+ throw new Error(`No extractor matched URL: ${url}. Supported: /p/, /reel/, /{user}/, /stories/, /highlights/, /explore/tags/, /saved/`);
3083
+ }
3084
+ /** Run an extractor */
3085
+ async function runExtractor(url, extrClass, opts) {
3086
+ const config = buildConfig(opts);
3087
+ const log = createLogger(opts.verbose ?? false);
3088
+ let http;
3089
+ let webCsrf;
3090
+ if (opts.cookies) {
3091
+ http = createHttpClient(void 0, opts.cookies, log);
3092
+ webCsrf = extractCsrfFromCookies(opts.cookies);
3093
+ } else if (opts.sessionid) http = createHttpClient(opts.sessionid, void 0, log);
3094
+ else {
3095
+ const wc = await createWebClient(log);
3096
+ http = wc.http;
3097
+ webCsrf = wc.csrfToken;
3098
+ }
3099
+ const storage = createStorage();
3100
+ const match = extrClass.pattern.exec(url);
3101
+ if (!match) {
3102
+ console.error(`URL did not match expected pattern: ${url}`);
3103
+ process.exit(1);
3104
+ }
3105
+ const extractor = new extrClass({
3106
+ url,
3107
+ match,
3108
+ config,
3109
+ http,
3110
+ storage,
3111
+ log,
3112
+ sessionId: opts.sessionid,
3113
+ csrfToken: webCsrf
3114
+ });
3115
+ if (opts.info) {
3116
+ const job = new PrintJob(extractor);
3117
+ const start = Date.now();
3118
+ try {
3119
+ const status = await job.run();
3120
+ const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
3121
+ if (status !== 0) log.warn(`Finished with status ${status} in ${elapsed}s`);
3122
+ } catch (err) {
3123
+ log.error(String(err));
3124
+ process.exit(1);
3125
+ }
3126
+ return;
3127
+ }
3128
+ const job = new DownloadJob(extractor);
3129
+ job.basePath = opts.output ?? "./data";
3130
+ const start = Date.now();
3131
+ try {
3132
+ const status = await job.run();
3133
+ const elapsed = ((Date.now() - start) / 1e3).toFixed(1);
3134
+ if (status === 0) log.info(`Done in ${elapsed}s`);
3135
+ else log.warn(`Finished with status ${status} in ${elapsed}s`);
3136
+ } catch (err) {
3137
+ log.error(String(err));
3138
+ process.exit(1);
3139
+ }
3140
+ }
3141
+ /** Program */
3142
+ const program = new Command();
3143
+ program.name("gdl-instagram").description("Download images and videos from Instagram.\n\nUses gallery-dl's extraction pipeline — supports posts, reels,\nstories, highlights, tagged posts, saved collections, and more.\n\nRequires a sessionid cookie exported from your browser.\nSet via --sessionid or INSTAGRAM_SESSIONID environment variable.").version("0.1.0");
3144
+ addSharedOptions(program.command("dl", { isDefault: true }).argument("[url]", "Instagram URL to download (auto-detects type)").description("Download media from an Instagram URL (auto-detects post/user/stories/…)\n\nExamples:\n gdl-instagram https://www.instagram.com/p/CxAbCdEfGh/\n gdl-instagram https://www.instagram.com/username/ --include=posts,reels\n gdl-instagram https://www.instagram.com/stories/username/").action(async (url, opts) => {
3145
+ if (!url) {
3146
+ program.help();
3147
+ return;
3148
+ }
3149
+ await runExtractor(url, resolveExtractor(url), opts);
3150
+ }));
3151
+ addSharedOptions(program.command("tag <hashtag>").description("Download posts from an Instagram hashtag\n\nExamples:\n gdl-instagram tag cats\n gdl-instagram tag https://www.instagram.com/explore/tags/cats/").action(async (hashtag, opts) => {
3152
+ await runExtractor(hashtag.startsWith("http") ? hashtag : `https://www.instagram.com/explore/tags/${hashtag}/`, InstagramTagExtractor, opts);
3153
+ }));
3154
+ addSharedOptions(program.command("saved").description("Download your saved (bookmarked) posts\n\nRequires authentication via --sessionid.\n\nExamples:\n gdl-instagram saved --sessionid=abc123").action(async (opts) => {
3155
+ await runExtractor("https://www.instagram.com/me/saved/", InstagramSavedExtractor, opts);
3156
+ }));
3157
+ /** parse */
3158
+ program.parse();
3159
+ //#endregion
3160
+ export {};