@magda/org-tree 2.3.3 → 3.0.0-alpha.1

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,4495 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined")
12
+ return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/commander/lib/error.js
36
+ var require_error = __commonJS({
37
+ "../../node_modules/commander/lib/error.js"(exports) {
38
+ var CommanderError2 = class extends Error {
39
+ /**
40
+ * Constructs the CommanderError class
41
+ * @param {number} exitCode suggested exit code which could be used with process.exit
42
+ * @param {string} code an id string representing the error
43
+ * @param {string} message human-readable description of the error
44
+ * @constructor
45
+ */
46
+ constructor(exitCode, code, message) {
47
+ super(message);
48
+ Error.captureStackTrace(this, this.constructor);
49
+ this.name = this.constructor.name;
50
+ this.code = code;
51
+ this.exitCode = exitCode;
52
+ this.nestedError = void 0;
53
+ }
54
+ };
55
+ var InvalidArgumentError2 = class extends CommanderError2 {
56
+ /**
57
+ * Constructs the InvalidArgumentError class
58
+ * @param {string} [message] explanation of why argument is invalid
59
+ * @constructor
60
+ */
61
+ constructor(message) {
62
+ super(1, "commander.invalidArgument", message);
63
+ Error.captureStackTrace(this, this.constructor);
64
+ this.name = this.constructor.name;
65
+ }
66
+ };
67
+ exports.CommanderError = CommanderError2;
68
+ exports.InvalidArgumentError = InvalidArgumentError2;
69
+ }
70
+ });
71
+
72
+ // ../../node_modules/commander/lib/argument.js
73
+ var require_argument = __commonJS({
74
+ "../../node_modules/commander/lib/argument.js"(exports) {
75
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
76
+ var Argument2 = class {
77
+ /**
78
+ * Initialize a new command argument with the given name and description.
79
+ * The default is that the argument is required, and you can explicitly
80
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
81
+ *
82
+ * @param {string} name
83
+ * @param {string} [description]
84
+ */
85
+ constructor(name, description) {
86
+ this.description = description || "";
87
+ this.variadic = false;
88
+ this.parseArg = void 0;
89
+ this.defaultValue = void 0;
90
+ this.defaultValueDescription = void 0;
91
+ this.argChoices = void 0;
92
+ switch (name[0]) {
93
+ case "<":
94
+ this.required = true;
95
+ this._name = name.slice(1, -1);
96
+ break;
97
+ case "[":
98
+ this.required = false;
99
+ this._name = name.slice(1, -1);
100
+ break;
101
+ default:
102
+ this.required = true;
103
+ this._name = name;
104
+ break;
105
+ }
106
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
107
+ this.variadic = true;
108
+ this._name = this._name.slice(0, -3);
109
+ }
110
+ }
111
+ /**
112
+ * Return argument name.
113
+ *
114
+ * @return {string}
115
+ */
116
+ name() {
117
+ return this._name;
118
+ }
119
+ /**
120
+ * @api private
121
+ */
122
+ _concatValue(value, previous) {
123
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
124
+ return [value];
125
+ }
126
+ return previous.concat(value);
127
+ }
128
+ /**
129
+ * Set the default value, and optionally supply the description to be displayed in the help.
130
+ *
131
+ * @param {*} value
132
+ * @param {string} [description]
133
+ * @return {Argument}
134
+ */
135
+ default(value, description) {
136
+ this.defaultValue = value;
137
+ this.defaultValueDescription = description;
138
+ return this;
139
+ }
140
+ /**
141
+ * Set the custom handler for processing CLI command arguments into argument values.
142
+ *
143
+ * @param {Function} [fn]
144
+ * @return {Argument}
145
+ */
146
+ argParser(fn) {
147
+ this.parseArg = fn;
148
+ return this;
149
+ }
150
+ /**
151
+ * Only allow argument value to be one of choices.
152
+ *
153
+ * @param {string[]} values
154
+ * @return {Argument}
155
+ */
156
+ choices(values) {
157
+ this.argChoices = values.slice();
158
+ this.parseArg = (arg, previous) => {
159
+ if (!this.argChoices.includes(arg)) {
160
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
161
+ }
162
+ if (this.variadic) {
163
+ return this._concatValue(arg, previous);
164
+ }
165
+ return arg;
166
+ };
167
+ return this;
168
+ }
169
+ /**
170
+ * Make argument required.
171
+ */
172
+ argRequired() {
173
+ this.required = true;
174
+ return this;
175
+ }
176
+ /**
177
+ * Make argument optional.
178
+ */
179
+ argOptional() {
180
+ this.required = false;
181
+ return this;
182
+ }
183
+ };
184
+ function humanReadableArgName(arg) {
185
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
186
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
187
+ }
188
+ exports.Argument = Argument2;
189
+ exports.humanReadableArgName = humanReadableArgName;
190
+ }
191
+ });
192
+
193
+ // ../../node_modules/commander/lib/help.js
194
+ var require_help = __commonJS({
195
+ "../../node_modules/commander/lib/help.js"(exports) {
196
+ var { humanReadableArgName } = require_argument();
197
+ var Help2 = class {
198
+ constructor() {
199
+ this.helpWidth = void 0;
200
+ this.sortSubcommands = false;
201
+ this.sortOptions = false;
202
+ this.showGlobalOptions = false;
203
+ }
204
+ /**
205
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
206
+ *
207
+ * @param {Command} cmd
208
+ * @returns {Command[]}
209
+ */
210
+ visibleCommands(cmd) {
211
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
212
+ if (cmd._hasImplicitHelpCommand()) {
213
+ const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
214
+ const helpCommand = cmd.createCommand(helpName).helpOption(false);
215
+ helpCommand.description(cmd._helpCommandDescription);
216
+ if (helpArgs)
217
+ helpCommand.arguments(helpArgs);
218
+ visibleCommands.push(helpCommand);
219
+ }
220
+ if (this.sortSubcommands) {
221
+ visibleCommands.sort((a, b) => {
222
+ return a.name().localeCompare(b.name());
223
+ });
224
+ }
225
+ return visibleCommands;
226
+ }
227
+ /**
228
+ * Compare options for sort.
229
+ *
230
+ * @param {Option} a
231
+ * @param {Option} b
232
+ * @returns number
233
+ */
234
+ compareOptions(a, b) {
235
+ const getSortKey = (option) => {
236
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
237
+ };
238
+ return getSortKey(a).localeCompare(getSortKey(b));
239
+ }
240
+ /**
241
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
242
+ *
243
+ * @param {Command} cmd
244
+ * @returns {Option[]}
245
+ */
246
+ visibleOptions(cmd) {
247
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
248
+ const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
249
+ const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
250
+ if (showShortHelpFlag || showLongHelpFlag) {
251
+ let helpOption;
252
+ if (!showShortHelpFlag) {
253
+ helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
254
+ } else if (!showLongHelpFlag) {
255
+ helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
256
+ } else {
257
+ helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
258
+ }
259
+ visibleOptions.push(helpOption);
260
+ }
261
+ if (this.sortOptions) {
262
+ visibleOptions.sort(this.compareOptions);
263
+ }
264
+ return visibleOptions;
265
+ }
266
+ /**
267
+ * Get an array of the visible global options. (Not including help.)
268
+ *
269
+ * @param {Command} cmd
270
+ * @returns {Option[]}
271
+ */
272
+ visibleGlobalOptions(cmd) {
273
+ if (!this.showGlobalOptions)
274
+ return [];
275
+ const globalOptions = [];
276
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
277
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
278
+ globalOptions.push(...visibleOptions);
279
+ }
280
+ if (this.sortOptions) {
281
+ globalOptions.sort(this.compareOptions);
282
+ }
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) {
293
+ cmd.registeredArguments.forEach((argument) => {
294
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
295
+ });
296
+ }
297
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
298
+ return cmd.registeredArguments;
299
+ }
300
+ return [];
301
+ }
302
+ /**
303
+ * Get the command term to show in the list of subcommands.
304
+ *
305
+ * @param {Command} cmd
306
+ * @returns {string}
307
+ */
308
+ subcommandTerm(cmd) {
309
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
310
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
311
+ (args ? " " + args : "");
312
+ }
313
+ /**
314
+ * Get the option term to show in the list of options.
315
+ *
316
+ * @param {Option} option
317
+ * @returns {string}
318
+ */
319
+ optionTerm(option) {
320
+ return option.flags;
321
+ }
322
+ /**
323
+ * Get the argument term to show in the list of arguments.
324
+ *
325
+ * @param {Argument} argument
326
+ * @returns {string}
327
+ */
328
+ argumentTerm(argument) {
329
+ return argument.name();
330
+ }
331
+ /**
332
+ * Get the longest command term length.
333
+ *
334
+ * @param {Command} cmd
335
+ * @param {Help} helper
336
+ * @returns {number}
337
+ */
338
+ longestSubcommandTermLength(cmd, helper) {
339
+ return helper.visibleCommands(cmd).reduce((max, command) => {
340
+ return Math.max(max, helper.subcommandTerm(command).length);
341
+ }, 0);
342
+ }
343
+ /**
344
+ * Get the longest option term length.
345
+ *
346
+ * @param {Command} cmd
347
+ * @param {Help} helper
348
+ * @returns {number}
349
+ */
350
+ longestOptionTermLength(cmd, helper) {
351
+ return helper.visibleOptions(cmd).reduce((max, option) => {
352
+ return Math.max(max, helper.optionTerm(option).length);
353
+ }, 0);
354
+ }
355
+ /**
356
+ * Get the longest global option term length.
357
+ *
358
+ * @param {Command} cmd
359
+ * @param {Help} helper
360
+ * @returns {number}
361
+ */
362
+ longestGlobalOptionTermLength(cmd, helper) {
363
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
364
+ return Math.max(max, helper.optionTerm(option).length);
365
+ }, 0);
366
+ }
367
+ /**
368
+ * Get the longest argument term length.
369
+ *
370
+ * @param {Command} cmd
371
+ * @param {Help} helper
372
+ * @returns {number}
373
+ */
374
+ longestArgumentTermLength(cmd, helper) {
375
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
376
+ return Math.max(max, helper.argumentTerm(argument).length);
377
+ }, 0);
378
+ }
379
+ /**
380
+ * Get the command usage to be displayed at the top of the built-in help.
381
+ *
382
+ * @param {Command} cmd
383
+ * @returns {string}
384
+ */
385
+ commandUsage(cmd) {
386
+ let cmdName = cmd._name;
387
+ if (cmd._aliases[0]) {
388
+ cmdName = cmdName + "|" + cmd._aliases[0];
389
+ }
390
+ let ancestorCmdNames = "";
391
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
392
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
393
+ }
394
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
395
+ }
396
+ /**
397
+ * Get the description for the command.
398
+ *
399
+ * @param {Command} cmd
400
+ * @returns {string}
401
+ */
402
+ commandDescription(cmd) {
403
+ return cmd.description();
404
+ }
405
+ /**
406
+ * Get the subcommand summary to show in the list of subcommands.
407
+ * (Fallback to description for backwards compatibility.)
408
+ *
409
+ * @param {Command} cmd
410
+ * @returns {string}
411
+ */
412
+ subcommandDescription(cmd) {
413
+ return cmd.summary() || cmd.description();
414
+ }
415
+ /**
416
+ * Get the option description to show in the list of options.
417
+ *
418
+ * @param {Option} option
419
+ * @return {string}
420
+ */
421
+ optionDescription(option) {
422
+ const extraInfo = [];
423
+ if (option.argChoices) {
424
+ extraInfo.push(
425
+ // use stringify to match the display of the default value
426
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
427
+ );
428
+ }
429
+ if (option.defaultValue !== void 0) {
430
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
431
+ if (showDefault) {
432
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
433
+ }
434
+ }
435
+ if (option.presetArg !== void 0 && option.optional) {
436
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
437
+ }
438
+ if (option.envVar !== void 0) {
439
+ extraInfo.push(`env: ${option.envVar}`);
440
+ }
441
+ if (extraInfo.length > 0) {
442
+ return `${option.description} (${extraInfo.join(", ")})`;
443
+ }
444
+ return option.description;
445
+ }
446
+ /**
447
+ * Get the argument description to show in the list of arguments.
448
+ *
449
+ * @param {Argument} argument
450
+ * @return {string}
451
+ */
452
+ argumentDescription(argument) {
453
+ const extraInfo = [];
454
+ if (argument.argChoices) {
455
+ extraInfo.push(
456
+ // use stringify to match the display of the default value
457
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
458
+ );
459
+ }
460
+ if (argument.defaultValue !== void 0) {
461
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
462
+ }
463
+ if (extraInfo.length > 0) {
464
+ const extraDescripton = `(${extraInfo.join(", ")})`;
465
+ if (argument.description) {
466
+ return `${argument.description} ${extraDescripton}`;
467
+ }
468
+ return extraDescripton;
469
+ }
470
+ return argument.description;
471
+ }
472
+ /**
473
+ * Generate the built-in help text.
474
+ *
475
+ * @param {Command} cmd
476
+ * @param {Help} helper
477
+ * @returns {string}
478
+ */
479
+ formatHelp(cmd, helper) {
480
+ const termWidth = helper.padWidth(cmd, helper);
481
+ const helpWidth = helper.helpWidth || 80;
482
+ const itemIndentWidth = 2;
483
+ const itemSeparatorWidth = 2;
484
+ function formatItem(term, description) {
485
+ if (description) {
486
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
487
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
488
+ }
489
+ return term;
490
+ }
491
+ function formatList(textArray) {
492
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
493
+ }
494
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
495
+ const commandDescription = helper.commandDescription(cmd);
496
+ if (commandDescription.length > 0) {
497
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
498
+ }
499
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
500
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
501
+ });
502
+ if (argumentList.length > 0) {
503
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
504
+ }
505
+ const optionList = helper.visibleOptions(cmd).map((option) => {
506
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
507
+ });
508
+ if (optionList.length > 0) {
509
+ output = output.concat(["Options:", formatList(optionList), ""]);
510
+ }
511
+ if (this.showGlobalOptions) {
512
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
513
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
514
+ });
515
+ if (globalOptionList.length > 0) {
516
+ output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
517
+ }
518
+ }
519
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
520
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
521
+ });
522
+ if (commandList.length > 0) {
523
+ output = output.concat(["Commands:", formatList(commandList), ""]);
524
+ }
525
+ return output.join("\n");
526
+ }
527
+ /**
528
+ * Calculate the pad width from the maximum term length.
529
+ *
530
+ * @param {Command} cmd
531
+ * @param {Help} helper
532
+ * @returns {number}
533
+ */
534
+ padWidth(cmd, helper) {
535
+ return Math.max(
536
+ helper.longestOptionTermLength(cmd, helper),
537
+ helper.longestGlobalOptionTermLength(cmd, helper),
538
+ helper.longestSubcommandTermLength(cmd, helper),
539
+ helper.longestArgumentTermLength(cmd, helper)
540
+ );
541
+ }
542
+ /**
543
+ * Wrap the given string to width characters per line, with lines after the first indented.
544
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
545
+ *
546
+ * @param {string} str
547
+ * @param {number} width
548
+ * @param {number} indent
549
+ * @param {number} [minColumnWidth=40]
550
+ * @return {string}
551
+ *
552
+ */
553
+ wrap(str, width, indent, minColumnWidth = 40) {
554
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
555
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
556
+ if (str.match(manualIndent))
557
+ return str;
558
+ const columnWidth = width - indent;
559
+ if (columnWidth < minColumnWidth)
560
+ return str;
561
+ const leadingStr = str.slice(0, indent);
562
+ const columnText = str.slice(indent).replace("\r\n", "\n");
563
+ const indentString = " ".repeat(indent);
564
+ const zeroWidthSpace = "\u200B";
565
+ const breaks = `\\s${zeroWidthSpace}`;
566
+ const regex = new RegExp(`
567
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
568
+ const lines = columnText.match(regex) || [];
569
+ return leadingStr + lines.map((line, i) => {
570
+ if (line === "\n")
571
+ return "";
572
+ return (i > 0 ? indentString : "") + line.trimEnd();
573
+ }).join("\n");
574
+ }
575
+ };
576
+ exports.Help = Help2;
577
+ }
578
+ });
579
+
580
+ // ../../node_modules/commander/lib/option.js
581
+ var require_option = __commonJS({
582
+ "../../node_modules/commander/lib/option.js"(exports) {
583
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
584
+ var Option2 = class {
585
+ /**
586
+ * Initialize a new `Option` with the given `flags` and `description`.
587
+ *
588
+ * @param {string} flags
589
+ * @param {string} [description]
590
+ */
591
+ constructor(flags, description) {
592
+ this.flags = flags;
593
+ this.description = description || "";
594
+ this.required = flags.includes("<");
595
+ this.optional = flags.includes("[");
596
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
597
+ this.mandatory = false;
598
+ const optionFlags = splitOptionFlags(flags);
599
+ this.short = optionFlags.shortFlag;
600
+ this.long = optionFlags.longFlag;
601
+ this.negate = false;
602
+ if (this.long) {
603
+ this.negate = this.long.startsWith("--no-");
604
+ }
605
+ this.defaultValue = void 0;
606
+ this.defaultValueDescription = void 0;
607
+ this.presetArg = void 0;
608
+ this.envVar = void 0;
609
+ this.parseArg = void 0;
610
+ this.hidden = false;
611
+ this.argChoices = void 0;
612
+ this.conflictsWith = [];
613
+ this.implied = void 0;
614
+ }
615
+ /**
616
+ * Set the default value, and optionally supply the description to be displayed in the help.
617
+ *
618
+ * @param {*} value
619
+ * @param {string} [description]
620
+ * @return {Option}
621
+ */
622
+ default(value, description) {
623
+ this.defaultValue = value;
624
+ this.defaultValueDescription = description;
625
+ return this;
626
+ }
627
+ /**
628
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
629
+ * The custom processing (parseArg) is called.
630
+ *
631
+ * @example
632
+ * new Option('--color').default('GREYSCALE').preset('RGB');
633
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
634
+ *
635
+ * @param {*} arg
636
+ * @return {Option}
637
+ */
638
+ preset(arg) {
639
+ this.presetArg = arg;
640
+ return this;
641
+ }
642
+ /**
643
+ * Add option name(s) that conflict with this option.
644
+ * An error will be displayed if conflicting options are found during parsing.
645
+ *
646
+ * @example
647
+ * new Option('--rgb').conflicts('cmyk');
648
+ * new Option('--js').conflicts(['ts', 'jsx']);
649
+ *
650
+ * @param {string | string[]} names
651
+ * @return {Option}
652
+ */
653
+ conflicts(names) {
654
+ this.conflictsWith = this.conflictsWith.concat(names);
655
+ return this;
656
+ }
657
+ /**
658
+ * Specify implied option values for when this option is set and the implied options are not.
659
+ *
660
+ * The custom processing (parseArg) is not called on the implied values.
661
+ *
662
+ * @example
663
+ * program
664
+ * .addOption(new Option('--log', 'write logging information to file'))
665
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
666
+ *
667
+ * @param {Object} impliedOptionValues
668
+ * @return {Option}
669
+ */
670
+ implies(impliedOptionValues) {
671
+ let newImplied = impliedOptionValues;
672
+ if (typeof impliedOptionValues === "string") {
673
+ newImplied = { [impliedOptionValues]: true };
674
+ }
675
+ this.implied = Object.assign(this.implied || {}, newImplied);
676
+ return this;
677
+ }
678
+ /**
679
+ * Set environment variable to check for option value.
680
+ *
681
+ * An environment variable is only used if when processed the current option value is
682
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
683
+ *
684
+ * @param {string} name
685
+ * @return {Option}
686
+ */
687
+ env(name) {
688
+ this.envVar = name;
689
+ return this;
690
+ }
691
+ /**
692
+ * Set the custom handler for processing CLI option arguments into option values.
693
+ *
694
+ * @param {Function} [fn]
695
+ * @return {Option}
696
+ */
697
+ argParser(fn) {
698
+ this.parseArg = fn;
699
+ return this;
700
+ }
701
+ /**
702
+ * Whether the option is mandatory and must have a value after parsing.
703
+ *
704
+ * @param {boolean} [mandatory=true]
705
+ * @return {Option}
706
+ */
707
+ makeOptionMandatory(mandatory = true) {
708
+ this.mandatory = !!mandatory;
709
+ return this;
710
+ }
711
+ /**
712
+ * Hide option in help.
713
+ *
714
+ * @param {boolean} [hide=true]
715
+ * @return {Option}
716
+ */
717
+ hideHelp(hide = true) {
718
+ this.hidden = !!hide;
719
+ return this;
720
+ }
721
+ /**
722
+ * @api private
723
+ */
724
+ _concatValue(value, previous) {
725
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
726
+ return [value];
727
+ }
728
+ return previous.concat(value);
729
+ }
730
+ /**
731
+ * Only allow option value to be one of choices.
732
+ *
733
+ * @param {string[]} values
734
+ * @return {Option}
735
+ */
736
+ choices(values) {
737
+ this.argChoices = values.slice();
738
+ this.parseArg = (arg, previous) => {
739
+ if (!this.argChoices.includes(arg)) {
740
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
741
+ }
742
+ if (this.variadic) {
743
+ return this._concatValue(arg, previous);
744
+ }
745
+ return arg;
746
+ };
747
+ return this;
748
+ }
749
+ /**
750
+ * Return option name.
751
+ *
752
+ * @return {string}
753
+ */
754
+ name() {
755
+ if (this.long) {
756
+ return this.long.replace(/^--/, "");
757
+ }
758
+ return this.short.replace(/^-/, "");
759
+ }
760
+ /**
761
+ * Return option name, in a camelcase format that can be used
762
+ * as a object attribute key.
763
+ *
764
+ * @return {string}
765
+ * @api private
766
+ */
767
+ attributeName() {
768
+ return camelcase(this.name().replace(/^no-/, ""));
769
+ }
770
+ /**
771
+ * Check if `arg` matches the short or long flag.
772
+ *
773
+ * @param {string} arg
774
+ * @return {boolean}
775
+ * @api private
776
+ */
777
+ is(arg) {
778
+ return this.short === arg || this.long === arg;
779
+ }
780
+ /**
781
+ * Return whether a boolean option.
782
+ *
783
+ * Options are one of boolean, negated, required argument, or optional argument.
784
+ *
785
+ * @return {boolean}
786
+ * @api private
787
+ */
788
+ isBoolean() {
789
+ return !this.required && !this.optional && !this.negate;
790
+ }
791
+ };
792
+ var DualOptions = class {
793
+ /**
794
+ * @param {Option[]} options
795
+ */
796
+ constructor(options) {
797
+ this.positiveOptions = /* @__PURE__ */ new Map();
798
+ this.negativeOptions = /* @__PURE__ */ new Map();
799
+ this.dualOptions = /* @__PURE__ */ new Set();
800
+ options.forEach((option) => {
801
+ if (option.negate) {
802
+ this.negativeOptions.set(option.attributeName(), option);
803
+ } else {
804
+ this.positiveOptions.set(option.attributeName(), option);
805
+ }
806
+ });
807
+ this.negativeOptions.forEach((value, key) => {
808
+ if (this.positiveOptions.has(key)) {
809
+ this.dualOptions.add(key);
810
+ }
811
+ });
812
+ }
813
+ /**
814
+ * Did the value come from the option, and not from possible matching dual option?
815
+ *
816
+ * @param {*} value
817
+ * @param {Option} option
818
+ * @returns {boolean}
819
+ */
820
+ valueFromOption(value, option) {
821
+ const optionKey = option.attributeName();
822
+ if (!this.dualOptions.has(optionKey))
823
+ return true;
824
+ const preset = this.negativeOptions.get(optionKey).presetArg;
825
+ const negativeValue = preset !== void 0 ? preset : false;
826
+ return option.negate === (negativeValue === value);
827
+ }
828
+ };
829
+ function camelcase(str) {
830
+ return str.split("-").reduce((str2, word) => {
831
+ return str2 + word[0].toUpperCase() + word.slice(1);
832
+ });
833
+ }
834
+ function splitOptionFlags(flags) {
835
+ let shortFlag;
836
+ let longFlag;
837
+ const flagParts = flags.split(/[ |,]+/);
838
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
839
+ shortFlag = flagParts.shift();
840
+ longFlag = flagParts.shift();
841
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
842
+ shortFlag = longFlag;
843
+ longFlag = void 0;
844
+ }
845
+ return { shortFlag, longFlag };
846
+ }
847
+ exports.Option = Option2;
848
+ exports.splitOptionFlags = splitOptionFlags;
849
+ exports.DualOptions = DualOptions;
850
+ }
851
+ });
852
+
853
+ // ../../node_modules/commander/lib/suggestSimilar.js
854
+ var require_suggestSimilar = __commonJS({
855
+ "../../node_modules/commander/lib/suggestSimilar.js"(exports) {
856
+ var maxDistance = 3;
857
+ function editDistance(a, b) {
858
+ if (Math.abs(a.length - b.length) > maxDistance)
859
+ return Math.max(a.length, b.length);
860
+ const d = [];
861
+ for (let i = 0; i <= a.length; i++) {
862
+ d[i] = [i];
863
+ }
864
+ for (let j = 0; j <= b.length; j++) {
865
+ d[0][j] = j;
866
+ }
867
+ for (let j = 1; j <= b.length; j++) {
868
+ for (let i = 1; i <= a.length; i++) {
869
+ let cost = 1;
870
+ if (a[i - 1] === b[j - 1]) {
871
+ cost = 0;
872
+ } else {
873
+ cost = 1;
874
+ }
875
+ d[i][j] = Math.min(
876
+ d[i - 1][j] + 1,
877
+ // deletion
878
+ d[i][j - 1] + 1,
879
+ // insertion
880
+ d[i - 1][j - 1] + cost
881
+ // substitution
882
+ );
883
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
884
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
885
+ }
886
+ }
887
+ }
888
+ return d[a.length][b.length];
889
+ }
890
+ function suggestSimilar(word, candidates) {
891
+ if (!candidates || candidates.length === 0)
892
+ return "";
893
+ candidates = Array.from(new Set(candidates));
894
+ const searchingOptions = word.startsWith("--");
895
+ if (searchingOptions) {
896
+ word = word.slice(2);
897
+ candidates = candidates.map((candidate) => candidate.slice(2));
898
+ }
899
+ let similar = [];
900
+ let bestDistance = maxDistance;
901
+ const minSimilarity = 0.4;
902
+ candidates.forEach((candidate) => {
903
+ if (candidate.length <= 1)
904
+ return;
905
+ const distance = editDistance(word, candidate);
906
+ const length = Math.max(word.length, candidate.length);
907
+ const similarity = (length - distance) / length;
908
+ if (similarity > minSimilarity) {
909
+ if (distance < bestDistance) {
910
+ bestDistance = distance;
911
+ similar = [candidate];
912
+ } else if (distance === bestDistance) {
913
+ similar.push(candidate);
914
+ }
915
+ }
916
+ });
917
+ similar.sort((a, b) => a.localeCompare(b));
918
+ if (searchingOptions) {
919
+ similar = similar.map((candidate) => `--${candidate}`);
920
+ }
921
+ if (similar.length > 1) {
922
+ return `
923
+ (Did you mean one of ${similar.join(", ")}?)`;
924
+ }
925
+ if (similar.length === 1) {
926
+ return `
927
+ (Did you mean ${similar[0]}?)`;
928
+ }
929
+ return "";
930
+ }
931
+ exports.suggestSimilar = suggestSimilar;
932
+ }
933
+ });
934
+
935
+ // ../../node_modules/commander/lib/command.js
936
+ var require_command = __commonJS({
937
+ "../../node_modules/commander/lib/command.js"(exports) {
938
+ var EventEmitter = __require("events").EventEmitter;
939
+ var childProcess = __require("child_process");
940
+ var path = __require("path");
941
+ var fs = __require("fs");
942
+ var process2 = __require("process");
943
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
944
+ var { CommanderError: CommanderError2 } = require_error();
945
+ var { Help: Help2 } = require_help();
946
+ var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
947
+ var { suggestSimilar } = require_suggestSimilar();
948
+ var Command2 = class _Command extends EventEmitter {
949
+ /**
950
+ * Initialize a new `Command`.
951
+ *
952
+ * @param {string} [name]
953
+ */
954
+ constructor(name) {
955
+ super();
956
+ this.commands = [];
957
+ this.options = [];
958
+ this.parent = null;
959
+ this._allowUnknownOption = false;
960
+ this._allowExcessArguments = true;
961
+ this.registeredArguments = [];
962
+ this._args = this.registeredArguments;
963
+ this.args = [];
964
+ this.rawArgs = [];
965
+ this.processedArgs = [];
966
+ this._scriptPath = null;
967
+ this._name = name || "";
968
+ this._optionValues = {};
969
+ this._optionValueSources = {};
970
+ this._storeOptionsAsProperties = false;
971
+ this._actionHandler = null;
972
+ this._executableHandler = false;
973
+ this._executableFile = null;
974
+ this._executableDir = null;
975
+ this._defaultCommandName = null;
976
+ this._exitCallback = null;
977
+ this._aliases = [];
978
+ this._combineFlagAndOptionalValue = true;
979
+ this._description = "";
980
+ this._summary = "";
981
+ this._argsDescription = void 0;
982
+ this._enablePositionalOptions = false;
983
+ this._passThroughOptions = false;
984
+ this._lifeCycleHooks = {};
985
+ this._showHelpAfterError = false;
986
+ this._showSuggestionAfterError = true;
987
+ this._outputConfiguration = {
988
+ writeOut: (str) => process2.stdout.write(str),
989
+ writeErr: (str) => process2.stderr.write(str),
990
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
991
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
992
+ outputError: (str, write) => write(str)
993
+ };
994
+ this._hidden = false;
995
+ this._hasHelpOption = true;
996
+ this._helpFlags = "-h, --help";
997
+ this._helpDescription = "display help for command";
998
+ this._helpShortFlag = "-h";
999
+ this._helpLongFlag = "--help";
1000
+ this._addImplicitHelpCommand = void 0;
1001
+ this._helpCommandName = "help";
1002
+ this._helpCommandnameAndArgs = "help [command]";
1003
+ this._helpCommandDescription = "display help for command";
1004
+ this._helpConfiguration = {};
1005
+ }
1006
+ /**
1007
+ * Copy settings that are useful to have in common across root command and subcommands.
1008
+ *
1009
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1010
+ *
1011
+ * @param {Command} sourceCommand
1012
+ * @return {Command} `this` command for chaining
1013
+ */
1014
+ copyInheritedSettings(sourceCommand) {
1015
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1016
+ this._hasHelpOption = sourceCommand._hasHelpOption;
1017
+ this._helpFlags = sourceCommand._helpFlags;
1018
+ this._helpDescription = sourceCommand._helpDescription;
1019
+ this._helpShortFlag = sourceCommand._helpShortFlag;
1020
+ this._helpLongFlag = sourceCommand._helpLongFlag;
1021
+ this._helpCommandName = sourceCommand._helpCommandName;
1022
+ this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1023
+ this._helpCommandDescription = sourceCommand._helpCommandDescription;
1024
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1025
+ this._exitCallback = sourceCommand._exitCallback;
1026
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1027
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1028
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1029
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1030
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1031
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1032
+ return this;
1033
+ }
1034
+ /**
1035
+ * @returns {Command[]}
1036
+ * @api private
1037
+ */
1038
+ _getCommandAndAncestors() {
1039
+ const result = [];
1040
+ for (let command = this; command; command = command.parent) {
1041
+ result.push(command);
1042
+ }
1043
+ return result;
1044
+ }
1045
+ /**
1046
+ * Define a command.
1047
+ *
1048
+ * There are two styles of command: pay attention to where to put the description.
1049
+ *
1050
+ * @example
1051
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1052
+ * program
1053
+ * .command('clone <source> [destination]')
1054
+ * .description('clone a repository into a newly created directory')
1055
+ * .action((source, destination) => {
1056
+ * console.log('clone command called');
1057
+ * });
1058
+ *
1059
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1060
+ * program
1061
+ * .command('start <service>', 'start named service')
1062
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1063
+ *
1064
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1065
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1066
+ * @param {Object} [execOpts] - configuration options (for executable)
1067
+ * @return {Command} returns new command for action handler, or `this` for executable command
1068
+ */
1069
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1070
+ let desc = actionOptsOrExecDesc;
1071
+ let opts = execOpts;
1072
+ if (typeof desc === "object" && desc !== null) {
1073
+ opts = desc;
1074
+ desc = null;
1075
+ }
1076
+ opts = opts || {};
1077
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1078
+ const cmd = this.createCommand(name);
1079
+ if (desc) {
1080
+ cmd.description(desc);
1081
+ cmd._executableHandler = true;
1082
+ }
1083
+ if (opts.isDefault)
1084
+ this._defaultCommandName = cmd._name;
1085
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1086
+ cmd._executableFile = opts.executableFile || null;
1087
+ if (args)
1088
+ cmd.arguments(args);
1089
+ this.commands.push(cmd);
1090
+ cmd.parent = this;
1091
+ cmd.copyInheritedSettings(this);
1092
+ if (desc)
1093
+ return this;
1094
+ return cmd;
1095
+ }
1096
+ /**
1097
+ * Factory routine to create a new unattached command.
1098
+ *
1099
+ * See .command() for creating an attached subcommand, which uses this routine to
1100
+ * create the command. You can override createCommand to customise subcommands.
1101
+ *
1102
+ * @param {string} [name]
1103
+ * @return {Command} new command
1104
+ */
1105
+ createCommand(name) {
1106
+ return new _Command(name);
1107
+ }
1108
+ /**
1109
+ * You can customise the help with a subclass of Help by overriding createHelp,
1110
+ * or by overriding Help properties using configureHelp().
1111
+ *
1112
+ * @return {Help}
1113
+ */
1114
+ createHelp() {
1115
+ return Object.assign(new Help2(), this.configureHelp());
1116
+ }
1117
+ /**
1118
+ * You can customise the help by overriding Help properties using configureHelp(),
1119
+ * or with a subclass of Help by overriding createHelp().
1120
+ *
1121
+ * @param {Object} [configuration] - configuration options
1122
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1123
+ */
1124
+ configureHelp(configuration) {
1125
+ if (configuration === void 0)
1126
+ return this._helpConfiguration;
1127
+ this._helpConfiguration = configuration;
1128
+ return this;
1129
+ }
1130
+ /**
1131
+ * The default output goes to stdout and stderr. You can customise this for special
1132
+ * applications. You can also customise the display of errors by overriding outputError.
1133
+ *
1134
+ * The configuration properties are all functions:
1135
+ *
1136
+ * // functions to change where being written, stdout and stderr
1137
+ * writeOut(str)
1138
+ * writeErr(str)
1139
+ * // matching functions to specify width for wrapping help
1140
+ * getOutHelpWidth()
1141
+ * getErrHelpWidth()
1142
+ * // functions based on what is being written out
1143
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1144
+ *
1145
+ * @param {Object} [configuration] - configuration options
1146
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1147
+ */
1148
+ configureOutput(configuration) {
1149
+ if (configuration === void 0)
1150
+ return this._outputConfiguration;
1151
+ Object.assign(this._outputConfiguration, configuration);
1152
+ return this;
1153
+ }
1154
+ /**
1155
+ * Display the help or a custom message after an error occurs.
1156
+ *
1157
+ * @param {boolean|string} [displayHelp]
1158
+ * @return {Command} `this` command for chaining
1159
+ */
1160
+ showHelpAfterError(displayHelp = true) {
1161
+ if (typeof displayHelp !== "string")
1162
+ displayHelp = !!displayHelp;
1163
+ this._showHelpAfterError = displayHelp;
1164
+ return this;
1165
+ }
1166
+ /**
1167
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1168
+ *
1169
+ * @param {boolean} [displaySuggestion]
1170
+ * @return {Command} `this` command for chaining
1171
+ */
1172
+ showSuggestionAfterError(displaySuggestion = true) {
1173
+ this._showSuggestionAfterError = !!displaySuggestion;
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Add a prepared subcommand.
1178
+ *
1179
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1180
+ *
1181
+ * @param {Command} cmd - new subcommand
1182
+ * @param {Object} [opts] - configuration options
1183
+ * @return {Command} `this` command for chaining
1184
+ */
1185
+ addCommand(cmd, opts) {
1186
+ if (!cmd._name) {
1187
+ throw new Error(`Command passed to .addCommand() must have a name
1188
+ - specify the name in Command constructor or using .name()`);
1189
+ }
1190
+ opts = opts || {};
1191
+ if (opts.isDefault)
1192
+ this._defaultCommandName = cmd._name;
1193
+ if (opts.noHelp || opts.hidden)
1194
+ cmd._hidden = true;
1195
+ this.commands.push(cmd);
1196
+ cmd.parent = this;
1197
+ return this;
1198
+ }
1199
+ /**
1200
+ * Factory routine to create a new unattached argument.
1201
+ *
1202
+ * See .argument() for creating an attached argument, which uses this routine to
1203
+ * create the argument. You can override createArgument to return a custom argument.
1204
+ *
1205
+ * @param {string} name
1206
+ * @param {string} [description]
1207
+ * @return {Argument} new argument
1208
+ */
1209
+ createArgument(name, description) {
1210
+ return new Argument2(name, description);
1211
+ }
1212
+ /**
1213
+ * Define argument syntax for command.
1214
+ *
1215
+ * The default is that the argument is required, and you can explicitly
1216
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1217
+ *
1218
+ * @example
1219
+ * program.argument('<input-file>');
1220
+ * program.argument('[output-file]');
1221
+ *
1222
+ * @param {string} name
1223
+ * @param {string} [description]
1224
+ * @param {Function|*} [fn] - custom argument processing function
1225
+ * @param {*} [defaultValue]
1226
+ * @return {Command} `this` command for chaining
1227
+ */
1228
+ argument(name, description, fn, defaultValue) {
1229
+ const argument = this.createArgument(name, description);
1230
+ if (typeof fn === "function") {
1231
+ argument.default(defaultValue).argParser(fn);
1232
+ } else {
1233
+ argument.default(fn);
1234
+ }
1235
+ this.addArgument(argument);
1236
+ return this;
1237
+ }
1238
+ /**
1239
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1240
+ *
1241
+ * See also .argument().
1242
+ *
1243
+ * @example
1244
+ * program.arguments('<cmd> [env]');
1245
+ *
1246
+ * @param {string} names
1247
+ * @return {Command} `this` command for chaining
1248
+ */
1249
+ arguments(names) {
1250
+ names.trim().split(/ +/).forEach((detail) => {
1251
+ this.argument(detail);
1252
+ });
1253
+ return this;
1254
+ }
1255
+ /**
1256
+ * Define argument syntax for command, adding a prepared argument.
1257
+ *
1258
+ * @param {Argument} argument
1259
+ * @return {Command} `this` command for chaining
1260
+ */
1261
+ addArgument(argument) {
1262
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1263
+ if (previousArgument && previousArgument.variadic) {
1264
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1265
+ }
1266
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1267
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1268
+ }
1269
+ this.registeredArguments.push(argument);
1270
+ return this;
1271
+ }
1272
+ /**
1273
+ * Override default decision whether to add implicit help command.
1274
+ *
1275
+ * addHelpCommand() // force on
1276
+ * addHelpCommand(false); // force off
1277
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1278
+ *
1279
+ * @return {Command} `this` command for chaining
1280
+ */
1281
+ addHelpCommand(enableOrNameAndArgs, description) {
1282
+ if (enableOrNameAndArgs === false) {
1283
+ this._addImplicitHelpCommand = false;
1284
+ } else {
1285
+ this._addImplicitHelpCommand = true;
1286
+ if (typeof enableOrNameAndArgs === "string") {
1287
+ this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1288
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
1289
+ }
1290
+ this._helpCommandDescription = description || this._helpCommandDescription;
1291
+ }
1292
+ return this;
1293
+ }
1294
+ /**
1295
+ * @return {boolean}
1296
+ * @api private
1297
+ */
1298
+ _hasImplicitHelpCommand() {
1299
+ if (this._addImplicitHelpCommand === void 0) {
1300
+ return this.commands.length && !this._actionHandler && !this._findCommand("help");
1301
+ }
1302
+ return this._addImplicitHelpCommand;
1303
+ }
1304
+ /**
1305
+ * Add hook for life cycle event.
1306
+ *
1307
+ * @param {string} event
1308
+ * @param {Function} listener
1309
+ * @return {Command} `this` command for chaining
1310
+ */
1311
+ hook(event, listener) {
1312
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1313
+ if (!allowedValues.includes(event)) {
1314
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1315
+ Expecting one of '${allowedValues.join("', '")}'`);
1316
+ }
1317
+ if (this._lifeCycleHooks[event]) {
1318
+ this._lifeCycleHooks[event].push(listener);
1319
+ } else {
1320
+ this._lifeCycleHooks[event] = [listener];
1321
+ }
1322
+ return this;
1323
+ }
1324
+ /**
1325
+ * Register callback to use as replacement for calling process.exit.
1326
+ *
1327
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1328
+ * @return {Command} `this` command for chaining
1329
+ */
1330
+ exitOverride(fn) {
1331
+ if (fn) {
1332
+ this._exitCallback = fn;
1333
+ } else {
1334
+ this._exitCallback = (err) => {
1335
+ if (err.code !== "commander.executeSubCommandAsync") {
1336
+ throw err;
1337
+ } else {
1338
+ }
1339
+ };
1340
+ }
1341
+ return this;
1342
+ }
1343
+ /**
1344
+ * Call process.exit, and _exitCallback if defined.
1345
+ *
1346
+ * @param {number} exitCode exit code for using with process.exit
1347
+ * @param {string} code an id string representing the error
1348
+ * @param {string} message human-readable description of the error
1349
+ * @return never
1350
+ * @api private
1351
+ */
1352
+ _exit(exitCode, code, message) {
1353
+ if (this._exitCallback) {
1354
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1355
+ }
1356
+ process2.exit(exitCode);
1357
+ }
1358
+ /**
1359
+ * Register callback `fn` for the command.
1360
+ *
1361
+ * @example
1362
+ * program
1363
+ * .command('serve')
1364
+ * .description('start service')
1365
+ * .action(function() {
1366
+ * // do work here
1367
+ * });
1368
+ *
1369
+ * @param {Function} fn
1370
+ * @return {Command} `this` command for chaining
1371
+ */
1372
+ action(fn) {
1373
+ const listener = (args) => {
1374
+ const expectedArgsCount = this.registeredArguments.length;
1375
+ const actionArgs = args.slice(0, expectedArgsCount);
1376
+ if (this._storeOptionsAsProperties) {
1377
+ actionArgs[expectedArgsCount] = this;
1378
+ } else {
1379
+ actionArgs[expectedArgsCount] = this.opts();
1380
+ }
1381
+ actionArgs.push(this);
1382
+ return fn.apply(this, actionArgs);
1383
+ };
1384
+ this._actionHandler = listener;
1385
+ return this;
1386
+ }
1387
+ /**
1388
+ * Factory routine to create a new unattached option.
1389
+ *
1390
+ * See .option() for creating an attached option, which uses this routine to
1391
+ * create the option. You can override createOption to return a custom option.
1392
+ *
1393
+ * @param {string} flags
1394
+ * @param {string} [description]
1395
+ * @return {Option} new option
1396
+ */
1397
+ createOption(flags, description) {
1398
+ return new Option2(flags, description);
1399
+ }
1400
+ /**
1401
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1402
+ *
1403
+ * @param {Option | Argument} target
1404
+ * @param {string} value
1405
+ * @param {*} previous
1406
+ * @param {string} invalidArgumentMessage
1407
+ * @api private
1408
+ */
1409
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1410
+ try {
1411
+ return target.parseArg(value, previous);
1412
+ } catch (err) {
1413
+ if (err.code === "commander.invalidArgument") {
1414
+ const message = `${invalidArgumentMessage} ${err.message}`;
1415
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1416
+ }
1417
+ throw err;
1418
+ }
1419
+ }
1420
+ /**
1421
+ * Add an option.
1422
+ *
1423
+ * @param {Option} option
1424
+ * @return {Command} `this` command for chaining
1425
+ */
1426
+ addOption(option) {
1427
+ const oname = option.name();
1428
+ const name = option.attributeName();
1429
+ if (option.negate) {
1430
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1431
+ if (!this._findOption(positiveLongFlag)) {
1432
+ this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1433
+ }
1434
+ } else if (option.defaultValue !== void 0) {
1435
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1436
+ }
1437
+ this.options.push(option);
1438
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1439
+ if (val == null && option.presetArg !== void 0) {
1440
+ val = option.presetArg;
1441
+ }
1442
+ const oldValue = this.getOptionValue(name);
1443
+ if (val !== null && option.parseArg) {
1444
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1445
+ } else if (val !== null && option.variadic) {
1446
+ val = option._concatValue(val, oldValue);
1447
+ }
1448
+ if (val == null) {
1449
+ if (option.negate) {
1450
+ val = false;
1451
+ } else if (option.isBoolean() || option.optional) {
1452
+ val = true;
1453
+ } else {
1454
+ val = "";
1455
+ }
1456
+ }
1457
+ this.setOptionValueWithSource(name, val, valueSource);
1458
+ };
1459
+ this.on("option:" + oname, (val) => {
1460
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1461
+ handleOptionValue(val, invalidValueMessage, "cli");
1462
+ });
1463
+ if (option.envVar) {
1464
+ this.on("optionEnv:" + oname, (val) => {
1465
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1466
+ handleOptionValue(val, invalidValueMessage, "env");
1467
+ });
1468
+ }
1469
+ return this;
1470
+ }
1471
+ /**
1472
+ * Internal implementation shared by .option() and .requiredOption()
1473
+ *
1474
+ * @api private
1475
+ */
1476
+ _optionEx(config, flags, description, fn, defaultValue) {
1477
+ if (typeof flags === "object" && flags instanceof Option2) {
1478
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1479
+ }
1480
+ const option = this.createOption(flags, description);
1481
+ option.makeOptionMandatory(!!config.mandatory);
1482
+ if (typeof fn === "function") {
1483
+ option.default(defaultValue).argParser(fn);
1484
+ } else if (fn instanceof RegExp) {
1485
+ const regex = fn;
1486
+ fn = (val, def) => {
1487
+ const m = regex.exec(val);
1488
+ return m ? m[0] : def;
1489
+ };
1490
+ option.default(defaultValue).argParser(fn);
1491
+ } else {
1492
+ option.default(fn);
1493
+ }
1494
+ return this.addOption(option);
1495
+ }
1496
+ /**
1497
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1498
+ *
1499
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1500
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1501
+ *
1502
+ * See the README for more details, and see also addOption() and requiredOption().
1503
+ *
1504
+ * @example
1505
+ * program
1506
+ * .option('-p, --pepper', 'add pepper')
1507
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1508
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1509
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1510
+ *
1511
+ * @param {string} flags
1512
+ * @param {string} [description]
1513
+ * @param {Function|*} [parseArg] - custom option processing function or default value
1514
+ * @param {*} [defaultValue]
1515
+ * @return {Command} `this` command for chaining
1516
+ */
1517
+ option(flags, description, parseArg, defaultValue) {
1518
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1519
+ }
1520
+ /**
1521
+ * Add a required option which must have a value after parsing. This usually means
1522
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1523
+ *
1524
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1525
+ *
1526
+ * @param {string} flags
1527
+ * @param {string} [description]
1528
+ * @param {Function|*} [parseArg] - custom option processing function or default value
1529
+ * @param {*} [defaultValue]
1530
+ * @return {Command} `this` command for chaining
1531
+ */
1532
+ requiredOption(flags, description, parseArg, defaultValue) {
1533
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1534
+ }
1535
+ /**
1536
+ * Alter parsing of short flags with optional values.
1537
+ *
1538
+ * @example
1539
+ * // for `.option('-f,--flag [value]'):
1540
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1541
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1542
+ *
1543
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1544
+ */
1545
+ combineFlagAndOptionalValue(combine = true) {
1546
+ this._combineFlagAndOptionalValue = !!combine;
1547
+ return this;
1548
+ }
1549
+ /**
1550
+ * Allow unknown options on the command line.
1551
+ *
1552
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1553
+ * for unknown options.
1554
+ */
1555
+ allowUnknownOption(allowUnknown = true) {
1556
+ this._allowUnknownOption = !!allowUnknown;
1557
+ return this;
1558
+ }
1559
+ /**
1560
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1561
+ *
1562
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1563
+ * for excess arguments.
1564
+ */
1565
+ allowExcessArguments(allowExcess = true) {
1566
+ this._allowExcessArguments = !!allowExcess;
1567
+ return this;
1568
+ }
1569
+ /**
1570
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1571
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1572
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1573
+ *
1574
+ * @param {Boolean} [positional=true]
1575
+ */
1576
+ enablePositionalOptions(positional = true) {
1577
+ this._enablePositionalOptions = !!positional;
1578
+ return this;
1579
+ }
1580
+ /**
1581
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1582
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1583
+ * positional options to have been enabled on the program (parent commands).
1584
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1585
+ *
1586
+ * @param {Boolean} [passThrough=true]
1587
+ * for unknown options.
1588
+ */
1589
+ passThroughOptions(passThrough = true) {
1590
+ this._passThroughOptions = !!passThrough;
1591
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1592
+ throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1593
+ }
1594
+ return this;
1595
+ }
1596
+ /**
1597
+ * Whether to store option values as properties on command object,
1598
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1599
+ *
1600
+ * @param {boolean} [storeAsProperties=true]
1601
+ * @return {Command} `this` command for chaining
1602
+ */
1603
+ storeOptionsAsProperties(storeAsProperties = true) {
1604
+ if (this.options.length) {
1605
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1606
+ }
1607
+ this._storeOptionsAsProperties = !!storeAsProperties;
1608
+ return this;
1609
+ }
1610
+ /**
1611
+ * Retrieve option value.
1612
+ *
1613
+ * @param {string} key
1614
+ * @return {Object} value
1615
+ */
1616
+ getOptionValue(key) {
1617
+ if (this._storeOptionsAsProperties) {
1618
+ return this[key];
1619
+ }
1620
+ return this._optionValues[key];
1621
+ }
1622
+ /**
1623
+ * Store option value.
1624
+ *
1625
+ * @param {string} key
1626
+ * @param {Object} value
1627
+ * @return {Command} `this` command for chaining
1628
+ */
1629
+ setOptionValue(key, value) {
1630
+ return this.setOptionValueWithSource(key, value, void 0);
1631
+ }
1632
+ /**
1633
+ * Store option value and where the value came from.
1634
+ *
1635
+ * @param {string} key
1636
+ * @param {Object} value
1637
+ * @param {string} source - expected values are default/config/env/cli/implied
1638
+ * @return {Command} `this` command for chaining
1639
+ */
1640
+ setOptionValueWithSource(key, value, source) {
1641
+ if (this._storeOptionsAsProperties) {
1642
+ this[key] = value;
1643
+ } else {
1644
+ this._optionValues[key] = value;
1645
+ }
1646
+ this._optionValueSources[key] = source;
1647
+ return this;
1648
+ }
1649
+ /**
1650
+ * Get source of option value.
1651
+ * Expected values are default | config | env | cli | implied
1652
+ *
1653
+ * @param {string} key
1654
+ * @return {string}
1655
+ */
1656
+ getOptionValueSource(key) {
1657
+ return this._optionValueSources[key];
1658
+ }
1659
+ /**
1660
+ * Get source of option value. See also .optsWithGlobals().
1661
+ * Expected values are default | config | env | cli | implied
1662
+ *
1663
+ * @param {string} key
1664
+ * @return {string}
1665
+ */
1666
+ getOptionValueSourceWithGlobals(key) {
1667
+ let source;
1668
+ this._getCommandAndAncestors().forEach((cmd) => {
1669
+ if (cmd.getOptionValueSource(key) !== void 0) {
1670
+ source = cmd.getOptionValueSource(key);
1671
+ }
1672
+ });
1673
+ return source;
1674
+ }
1675
+ /**
1676
+ * Get user arguments from implied or explicit arguments.
1677
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1678
+ *
1679
+ * @api private
1680
+ */
1681
+ _prepareUserArgs(argv, parseOptions) {
1682
+ if (argv !== void 0 && !Array.isArray(argv)) {
1683
+ throw new Error("first parameter to parse must be array or undefined");
1684
+ }
1685
+ parseOptions = parseOptions || {};
1686
+ if (argv === void 0) {
1687
+ argv = process2.argv;
1688
+ if (process2.versions && process2.versions.electron) {
1689
+ parseOptions.from = "electron";
1690
+ }
1691
+ }
1692
+ this.rawArgs = argv.slice();
1693
+ let userArgs;
1694
+ switch (parseOptions.from) {
1695
+ case void 0:
1696
+ case "node":
1697
+ this._scriptPath = argv[1];
1698
+ userArgs = argv.slice(2);
1699
+ break;
1700
+ case "electron":
1701
+ if (process2.defaultApp) {
1702
+ this._scriptPath = argv[1];
1703
+ userArgs = argv.slice(2);
1704
+ } else {
1705
+ userArgs = argv.slice(1);
1706
+ }
1707
+ break;
1708
+ case "user":
1709
+ userArgs = argv.slice(0);
1710
+ break;
1711
+ default:
1712
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1713
+ }
1714
+ if (!this._name && this._scriptPath)
1715
+ this.nameFromFilename(this._scriptPath);
1716
+ this._name = this._name || "program";
1717
+ return userArgs;
1718
+ }
1719
+ /**
1720
+ * Parse `argv`, setting options and invoking commands when defined.
1721
+ *
1722
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1723
+ * and the script being run in argv[1], with user parameters after that.
1724
+ *
1725
+ * @example
1726
+ * program.parse(process.argv);
1727
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1728
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1729
+ *
1730
+ * @param {string[]} [argv] - optional, defaults to process.argv
1731
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1732
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1733
+ * @return {Command} `this` command for chaining
1734
+ */
1735
+ parse(argv, parseOptions) {
1736
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1737
+ this._parseCommand([], userArgs);
1738
+ return this;
1739
+ }
1740
+ /**
1741
+ * Parse `argv`, setting options and invoking commands when defined.
1742
+ *
1743
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1744
+ *
1745
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1746
+ * and the script being run in argv[1], with user parameters after that.
1747
+ *
1748
+ * @example
1749
+ * await program.parseAsync(process.argv);
1750
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1751
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1752
+ *
1753
+ * @param {string[]} [argv]
1754
+ * @param {Object} [parseOptions]
1755
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1756
+ * @return {Promise}
1757
+ */
1758
+ async parseAsync(argv, parseOptions) {
1759
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1760
+ await this._parseCommand([], userArgs);
1761
+ return this;
1762
+ }
1763
+ /**
1764
+ * Execute a sub-command executable.
1765
+ *
1766
+ * @api private
1767
+ */
1768
+ _executeSubCommand(subcommand, args) {
1769
+ args = args.slice();
1770
+ let launchWithNode = false;
1771
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1772
+ function findFile(baseDir, baseName) {
1773
+ const localBin = path.resolve(baseDir, baseName);
1774
+ if (fs.existsSync(localBin))
1775
+ return localBin;
1776
+ if (sourceExt.includes(path.extname(baseName)))
1777
+ return void 0;
1778
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1779
+ if (foundExt)
1780
+ return `${localBin}${foundExt}`;
1781
+ return void 0;
1782
+ }
1783
+ this._checkForMissingMandatoryOptions();
1784
+ this._checkForConflictingOptions();
1785
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1786
+ let executableDir = this._executableDir || "";
1787
+ if (this._scriptPath) {
1788
+ let resolvedScriptPath;
1789
+ try {
1790
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1791
+ } catch (err) {
1792
+ resolvedScriptPath = this._scriptPath;
1793
+ }
1794
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1795
+ }
1796
+ if (executableDir) {
1797
+ let localFile = findFile(executableDir, executableFile);
1798
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1799
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1800
+ if (legacyName !== this._name) {
1801
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1802
+ }
1803
+ }
1804
+ executableFile = localFile || executableFile;
1805
+ }
1806
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1807
+ let proc;
1808
+ if (process2.platform !== "win32") {
1809
+ if (launchWithNode) {
1810
+ args.unshift(executableFile);
1811
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1812
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1813
+ } else {
1814
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1815
+ }
1816
+ } else {
1817
+ args.unshift(executableFile);
1818
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1819
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1820
+ }
1821
+ if (!proc.killed) {
1822
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1823
+ signals.forEach((signal) => {
1824
+ process2.on(signal, () => {
1825
+ if (proc.killed === false && proc.exitCode === null) {
1826
+ proc.kill(signal);
1827
+ }
1828
+ });
1829
+ });
1830
+ }
1831
+ const exitCallback = this._exitCallback;
1832
+ if (!exitCallback) {
1833
+ proc.on("close", process2.exit.bind(process2));
1834
+ } else {
1835
+ proc.on("close", () => {
1836
+ exitCallback(new CommanderError2(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1837
+ });
1838
+ }
1839
+ proc.on("error", (err) => {
1840
+ if (err.code === "ENOENT") {
1841
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1842
+ const executableMissing = `'${executableFile}' does not exist
1843
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1844
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1845
+ - ${executableDirMessage}`;
1846
+ throw new Error(executableMissing);
1847
+ } else if (err.code === "EACCES") {
1848
+ throw new Error(`'${executableFile}' not executable`);
1849
+ }
1850
+ if (!exitCallback) {
1851
+ process2.exit(1);
1852
+ } else {
1853
+ const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
1854
+ wrappedError.nestedError = err;
1855
+ exitCallback(wrappedError);
1856
+ }
1857
+ });
1858
+ this.runningCommand = proc;
1859
+ }
1860
+ /**
1861
+ * @api private
1862
+ */
1863
+ _dispatchSubcommand(commandName, operands, unknown) {
1864
+ const subCommand = this._findCommand(commandName);
1865
+ if (!subCommand)
1866
+ this.help({ error: true });
1867
+ let promiseChain;
1868
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1869
+ promiseChain = this._chainOrCall(promiseChain, () => {
1870
+ if (subCommand._executableHandler) {
1871
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1872
+ } else {
1873
+ return subCommand._parseCommand(operands, unknown);
1874
+ }
1875
+ });
1876
+ return promiseChain;
1877
+ }
1878
+ /**
1879
+ * Invoke help directly if possible, or dispatch if necessary.
1880
+ * e.g. help foo
1881
+ *
1882
+ * @api private
1883
+ */
1884
+ _dispatchHelpCommand(subcommandName) {
1885
+ if (!subcommandName) {
1886
+ this.help();
1887
+ }
1888
+ const subCommand = this._findCommand(subcommandName);
1889
+ if (subCommand && !subCommand._executableHandler) {
1890
+ subCommand.help();
1891
+ }
1892
+ return this._dispatchSubcommand(subcommandName, [], [
1893
+ this._helpLongFlag || this._helpShortFlag
1894
+ ]);
1895
+ }
1896
+ /**
1897
+ * Check this.args against expected this.registeredArguments.
1898
+ *
1899
+ * @api private
1900
+ */
1901
+ _checkNumberOfArguments() {
1902
+ this.registeredArguments.forEach((arg, i) => {
1903
+ if (arg.required && this.args[i] == null) {
1904
+ this.missingArgument(arg.name());
1905
+ }
1906
+ });
1907
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1908
+ return;
1909
+ }
1910
+ if (this.args.length > this.registeredArguments.length) {
1911
+ this._excessArguments(this.args);
1912
+ }
1913
+ }
1914
+ /**
1915
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1916
+ *
1917
+ * @api private
1918
+ */
1919
+ _processArguments() {
1920
+ const myParseArg = (argument, value, previous) => {
1921
+ let parsedValue = value;
1922
+ if (value !== null && argument.parseArg) {
1923
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1924
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1925
+ }
1926
+ return parsedValue;
1927
+ };
1928
+ this._checkNumberOfArguments();
1929
+ const processedArgs = [];
1930
+ this.registeredArguments.forEach((declaredArg, index) => {
1931
+ let value = declaredArg.defaultValue;
1932
+ if (declaredArg.variadic) {
1933
+ if (index < this.args.length) {
1934
+ value = this.args.slice(index);
1935
+ if (declaredArg.parseArg) {
1936
+ value = value.reduce((processed, v) => {
1937
+ return myParseArg(declaredArg, v, processed);
1938
+ }, declaredArg.defaultValue);
1939
+ }
1940
+ } else if (value === void 0) {
1941
+ value = [];
1942
+ }
1943
+ } else if (index < this.args.length) {
1944
+ value = this.args[index];
1945
+ if (declaredArg.parseArg) {
1946
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1947
+ }
1948
+ }
1949
+ processedArgs[index] = value;
1950
+ });
1951
+ this.processedArgs = processedArgs;
1952
+ }
1953
+ /**
1954
+ * Once we have a promise we chain, but call synchronously until then.
1955
+ *
1956
+ * @param {Promise|undefined} promise
1957
+ * @param {Function} fn
1958
+ * @return {Promise|undefined}
1959
+ * @api private
1960
+ */
1961
+ _chainOrCall(promise, fn) {
1962
+ if (promise && promise.then && typeof promise.then === "function") {
1963
+ return promise.then(() => fn());
1964
+ }
1965
+ return fn();
1966
+ }
1967
+ /**
1968
+ *
1969
+ * @param {Promise|undefined} promise
1970
+ * @param {string} event
1971
+ * @return {Promise|undefined}
1972
+ * @api private
1973
+ */
1974
+ _chainOrCallHooks(promise, event) {
1975
+ let result = promise;
1976
+ const hooks = [];
1977
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1978
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1979
+ hooks.push({ hookedCommand, callback });
1980
+ });
1981
+ });
1982
+ if (event === "postAction") {
1983
+ hooks.reverse();
1984
+ }
1985
+ hooks.forEach((hookDetail) => {
1986
+ result = this._chainOrCall(result, () => {
1987
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1988
+ });
1989
+ });
1990
+ return result;
1991
+ }
1992
+ /**
1993
+ *
1994
+ * @param {Promise|undefined} promise
1995
+ * @param {Command} subCommand
1996
+ * @param {string} event
1997
+ * @return {Promise|undefined}
1998
+ * @api private
1999
+ */
2000
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2001
+ let result = promise;
2002
+ if (this._lifeCycleHooks[event] !== void 0) {
2003
+ this._lifeCycleHooks[event].forEach((hook) => {
2004
+ result = this._chainOrCall(result, () => {
2005
+ return hook(this, subCommand);
2006
+ });
2007
+ });
2008
+ }
2009
+ return result;
2010
+ }
2011
+ /**
2012
+ * Process arguments in context of this command.
2013
+ * Returns action result, in case it is a promise.
2014
+ *
2015
+ * @api private
2016
+ */
2017
+ _parseCommand(operands, unknown) {
2018
+ const parsed = this.parseOptions(unknown);
2019
+ this._parseOptionsEnv();
2020
+ this._parseOptionsImplied();
2021
+ operands = operands.concat(parsed.operands);
2022
+ unknown = parsed.unknown;
2023
+ this.args = operands.concat(unknown);
2024
+ if (operands && this._findCommand(operands[0])) {
2025
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2026
+ }
2027
+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2028
+ return this._dispatchHelpCommand(operands[1]);
2029
+ }
2030
+ if (this._defaultCommandName) {
2031
+ outputHelpIfRequested(this, unknown);
2032
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2033
+ }
2034
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2035
+ this.help({ error: true });
2036
+ }
2037
+ outputHelpIfRequested(this, parsed.unknown);
2038
+ this._checkForMissingMandatoryOptions();
2039
+ this._checkForConflictingOptions();
2040
+ const checkForUnknownOptions = () => {
2041
+ if (parsed.unknown.length > 0) {
2042
+ this.unknownOption(parsed.unknown[0]);
2043
+ }
2044
+ };
2045
+ const commandEvent = `command:${this.name()}`;
2046
+ if (this._actionHandler) {
2047
+ checkForUnknownOptions();
2048
+ this._processArguments();
2049
+ let promiseChain;
2050
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2051
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2052
+ if (this.parent) {
2053
+ promiseChain = this._chainOrCall(promiseChain, () => {
2054
+ this.parent.emit(commandEvent, operands, unknown);
2055
+ });
2056
+ }
2057
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2058
+ return promiseChain;
2059
+ }
2060
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2061
+ checkForUnknownOptions();
2062
+ this._processArguments();
2063
+ this.parent.emit(commandEvent, operands, unknown);
2064
+ } else if (operands.length) {
2065
+ if (this._findCommand("*")) {
2066
+ return this._dispatchSubcommand("*", operands, unknown);
2067
+ }
2068
+ if (this.listenerCount("command:*")) {
2069
+ this.emit("command:*", operands, unknown);
2070
+ } else if (this.commands.length) {
2071
+ this.unknownCommand();
2072
+ } else {
2073
+ checkForUnknownOptions();
2074
+ this._processArguments();
2075
+ }
2076
+ } else if (this.commands.length) {
2077
+ checkForUnknownOptions();
2078
+ this.help({ error: true });
2079
+ } else {
2080
+ checkForUnknownOptions();
2081
+ this._processArguments();
2082
+ }
2083
+ }
2084
+ /**
2085
+ * Find matching command.
2086
+ *
2087
+ * @api private
2088
+ */
2089
+ _findCommand(name) {
2090
+ if (!name)
2091
+ return void 0;
2092
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2093
+ }
2094
+ /**
2095
+ * Return an option matching `arg` if any.
2096
+ *
2097
+ * @param {string} arg
2098
+ * @return {Option}
2099
+ * @api private
2100
+ */
2101
+ _findOption(arg) {
2102
+ return this.options.find((option) => option.is(arg));
2103
+ }
2104
+ /**
2105
+ * Display an error message if a mandatory option does not have a value.
2106
+ * Called after checking for help flags in leaf subcommand.
2107
+ *
2108
+ * @api private
2109
+ */
2110
+ _checkForMissingMandatoryOptions() {
2111
+ this._getCommandAndAncestors().forEach((cmd) => {
2112
+ cmd.options.forEach((anOption) => {
2113
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2114
+ cmd.missingMandatoryOptionValue(anOption);
2115
+ }
2116
+ });
2117
+ });
2118
+ }
2119
+ /**
2120
+ * Display an error message if conflicting options are used together in this.
2121
+ *
2122
+ * @api private
2123
+ */
2124
+ _checkForConflictingLocalOptions() {
2125
+ const definedNonDefaultOptions = this.options.filter(
2126
+ (option) => {
2127
+ const optionKey = option.attributeName();
2128
+ if (this.getOptionValue(optionKey) === void 0) {
2129
+ return false;
2130
+ }
2131
+ return this.getOptionValueSource(optionKey) !== "default";
2132
+ }
2133
+ );
2134
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2135
+ (option) => option.conflictsWith.length > 0
2136
+ );
2137
+ optionsWithConflicting.forEach((option) => {
2138
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2139
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2140
+ );
2141
+ if (conflictingAndDefined) {
2142
+ this._conflictingOption(option, conflictingAndDefined);
2143
+ }
2144
+ });
2145
+ }
2146
+ /**
2147
+ * Display an error message if conflicting options are used together.
2148
+ * Called after checking for help flags in leaf subcommand.
2149
+ *
2150
+ * @api private
2151
+ */
2152
+ _checkForConflictingOptions() {
2153
+ this._getCommandAndAncestors().forEach((cmd) => {
2154
+ cmd._checkForConflictingLocalOptions();
2155
+ });
2156
+ }
2157
+ /**
2158
+ * Parse options from `argv` removing known options,
2159
+ * and return argv split into operands and unknown arguments.
2160
+ *
2161
+ * Examples:
2162
+ *
2163
+ * argv => operands, unknown
2164
+ * --known kkk op => [op], []
2165
+ * op --known kkk => [op], []
2166
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2167
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2168
+ *
2169
+ * @param {String[]} argv
2170
+ * @return {{operands: String[], unknown: String[]}}
2171
+ */
2172
+ parseOptions(argv) {
2173
+ const operands = [];
2174
+ const unknown = [];
2175
+ let dest = operands;
2176
+ const args = argv.slice();
2177
+ function maybeOption(arg) {
2178
+ return arg.length > 1 && arg[0] === "-";
2179
+ }
2180
+ let activeVariadicOption = null;
2181
+ while (args.length) {
2182
+ const arg = args.shift();
2183
+ if (arg === "--") {
2184
+ if (dest === unknown)
2185
+ dest.push(arg);
2186
+ dest.push(...args);
2187
+ break;
2188
+ }
2189
+ if (activeVariadicOption && !maybeOption(arg)) {
2190
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2191
+ continue;
2192
+ }
2193
+ activeVariadicOption = null;
2194
+ if (maybeOption(arg)) {
2195
+ const option = this._findOption(arg);
2196
+ if (option) {
2197
+ if (option.required) {
2198
+ const value = args.shift();
2199
+ if (value === void 0)
2200
+ this.optionMissingArgument(option);
2201
+ this.emit(`option:${option.name()}`, value);
2202
+ } else if (option.optional) {
2203
+ let value = null;
2204
+ if (args.length > 0 && !maybeOption(args[0])) {
2205
+ value = args.shift();
2206
+ }
2207
+ this.emit(`option:${option.name()}`, value);
2208
+ } else {
2209
+ this.emit(`option:${option.name()}`);
2210
+ }
2211
+ activeVariadicOption = option.variadic ? option : null;
2212
+ continue;
2213
+ }
2214
+ }
2215
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2216
+ const option = this._findOption(`-${arg[1]}`);
2217
+ if (option) {
2218
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2219
+ this.emit(`option:${option.name()}`, arg.slice(2));
2220
+ } else {
2221
+ this.emit(`option:${option.name()}`);
2222
+ args.unshift(`-${arg.slice(2)}`);
2223
+ }
2224
+ continue;
2225
+ }
2226
+ }
2227
+ if (/^--[^=]+=/.test(arg)) {
2228
+ const index = arg.indexOf("=");
2229
+ const option = this._findOption(arg.slice(0, index));
2230
+ if (option && (option.required || option.optional)) {
2231
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2232
+ continue;
2233
+ }
2234
+ }
2235
+ if (maybeOption(arg)) {
2236
+ dest = unknown;
2237
+ }
2238
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2239
+ if (this._findCommand(arg)) {
2240
+ operands.push(arg);
2241
+ if (args.length > 0)
2242
+ unknown.push(...args);
2243
+ break;
2244
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2245
+ operands.push(arg);
2246
+ if (args.length > 0)
2247
+ operands.push(...args);
2248
+ break;
2249
+ } else if (this._defaultCommandName) {
2250
+ unknown.push(arg);
2251
+ if (args.length > 0)
2252
+ unknown.push(...args);
2253
+ break;
2254
+ }
2255
+ }
2256
+ if (this._passThroughOptions) {
2257
+ dest.push(arg);
2258
+ if (args.length > 0)
2259
+ dest.push(...args);
2260
+ break;
2261
+ }
2262
+ dest.push(arg);
2263
+ }
2264
+ return { operands, unknown };
2265
+ }
2266
+ /**
2267
+ * Return an object containing local option values as key-value pairs.
2268
+ *
2269
+ * @return {Object}
2270
+ */
2271
+ opts() {
2272
+ if (this._storeOptionsAsProperties) {
2273
+ const result = {};
2274
+ const len = this.options.length;
2275
+ for (let i = 0; i < len; i++) {
2276
+ const key = this.options[i].attributeName();
2277
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2278
+ }
2279
+ return result;
2280
+ }
2281
+ return this._optionValues;
2282
+ }
2283
+ /**
2284
+ * Return an object containing merged local and global option values as key-value pairs.
2285
+ *
2286
+ * @return {Object}
2287
+ */
2288
+ optsWithGlobals() {
2289
+ return this._getCommandAndAncestors().reduce(
2290
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2291
+ {}
2292
+ );
2293
+ }
2294
+ /**
2295
+ * Display error message and exit (or call exitOverride).
2296
+ *
2297
+ * @param {string} message
2298
+ * @param {Object} [errorOptions]
2299
+ * @param {string} [errorOptions.code] - an id string representing the error
2300
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2301
+ */
2302
+ error(message, errorOptions) {
2303
+ this._outputConfiguration.outputError(`${message}
2304
+ `, this._outputConfiguration.writeErr);
2305
+ if (typeof this._showHelpAfterError === "string") {
2306
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2307
+ `);
2308
+ } else if (this._showHelpAfterError) {
2309
+ this._outputConfiguration.writeErr("\n");
2310
+ this.outputHelp({ error: true });
2311
+ }
2312
+ const config = errorOptions || {};
2313
+ const exitCode = config.exitCode || 1;
2314
+ const code = config.code || "commander.error";
2315
+ this._exit(exitCode, code, message);
2316
+ }
2317
+ /**
2318
+ * Apply any option related environment variables, if option does
2319
+ * not have a value from cli or client code.
2320
+ *
2321
+ * @api private
2322
+ */
2323
+ _parseOptionsEnv() {
2324
+ this.options.forEach((option) => {
2325
+ if (option.envVar && option.envVar in process2.env) {
2326
+ const optionKey = option.attributeName();
2327
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2328
+ if (option.required || option.optional) {
2329
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2330
+ } else {
2331
+ this.emit(`optionEnv:${option.name()}`);
2332
+ }
2333
+ }
2334
+ }
2335
+ });
2336
+ }
2337
+ /**
2338
+ * Apply any implied option values, if option is undefined or default value.
2339
+ *
2340
+ * @api private
2341
+ */
2342
+ _parseOptionsImplied() {
2343
+ const dualHelper = new DualOptions(this.options);
2344
+ const hasCustomOptionValue = (optionKey) => {
2345
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2346
+ };
2347
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2348
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2349
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2350
+ });
2351
+ });
2352
+ }
2353
+ /**
2354
+ * Argument `name` is missing.
2355
+ *
2356
+ * @param {string} name
2357
+ * @api private
2358
+ */
2359
+ missingArgument(name) {
2360
+ const message = `error: missing required argument '${name}'`;
2361
+ this.error(message, { code: "commander.missingArgument" });
2362
+ }
2363
+ /**
2364
+ * `Option` is missing an argument.
2365
+ *
2366
+ * @param {Option} option
2367
+ * @api private
2368
+ */
2369
+ optionMissingArgument(option) {
2370
+ const message = `error: option '${option.flags}' argument missing`;
2371
+ this.error(message, { code: "commander.optionMissingArgument" });
2372
+ }
2373
+ /**
2374
+ * `Option` does not have a value, and is a mandatory option.
2375
+ *
2376
+ * @param {Option} option
2377
+ * @api private
2378
+ */
2379
+ missingMandatoryOptionValue(option) {
2380
+ const message = `error: required option '${option.flags}' not specified`;
2381
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2382
+ }
2383
+ /**
2384
+ * `Option` conflicts with another option.
2385
+ *
2386
+ * @param {Option} option
2387
+ * @param {Option} conflictingOption
2388
+ * @api private
2389
+ */
2390
+ _conflictingOption(option, conflictingOption) {
2391
+ const findBestOptionFromValue = (option2) => {
2392
+ const optionKey = option2.attributeName();
2393
+ const optionValue = this.getOptionValue(optionKey);
2394
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2395
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2396
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2397
+ return negativeOption;
2398
+ }
2399
+ return positiveOption || option2;
2400
+ };
2401
+ const getErrorMessage = (option2) => {
2402
+ const bestOption = findBestOptionFromValue(option2);
2403
+ const optionKey = bestOption.attributeName();
2404
+ const source = this.getOptionValueSource(optionKey);
2405
+ if (source === "env") {
2406
+ return `environment variable '${bestOption.envVar}'`;
2407
+ }
2408
+ return `option '${bestOption.flags}'`;
2409
+ };
2410
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2411
+ this.error(message, { code: "commander.conflictingOption" });
2412
+ }
2413
+ /**
2414
+ * Unknown option `flag`.
2415
+ *
2416
+ * @param {string} flag
2417
+ * @api private
2418
+ */
2419
+ unknownOption(flag) {
2420
+ if (this._allowUnknownOption)
2421
+ return;
2422
+ let suggestion = "";
2423
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2424
+ let candidateFlags = [];
2425
+ let command = this;
2426
+ do {
2427
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2428
+ candidateFlags = candidateFlags.concat(moreFlags);
2429
+ command = command.parent;
2430
+ } while (command && !command._enablePositionalOptions);
2431
+ suggestion = suggestSimilar(flag, candidateFlags);
2432
+ }
2433
+ const message = `error: unknown option '${flag}'${suggestion}`;
2434
+ this.error(message, { code: "commander.unknownOption" });
2435
+ }
2436
+ /**
2437
+ * Excess arguments, more than expected.
2438
+ *
2439
+ * @param {string[]} receivedArgs
2440
+ * @api private
2441
+ */
2442
+ _excessArguments(receivedArgs) {
2443
+ if (this._allowExcessArguments)
2444
+ return;
2445
+ const expected = this.registeredArguments.length;
2446
+ const s = expected === 1 ? "" : "s";
2447
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2448
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2449
+ this.error(message, { code: "commander.excessArguments" });
2450
+ }
2451
+ /**
2452
+ * Unknown command.
2453
+ *
2454
+ * @api private
2455
+ */
2456
+ unknownCommand() {
2457
+ const unknownName = this.args[0];
2458
+ let suggestion = "";
2459
+ if (this._showSuggestionAfterError) {
2460
+ const candidateNames = [];
2461
+ this.createHelp().visibleCommands(this).forEach((command) => {
2462
+ candidateNames.push(command.name());
2463
+ if (command.alias())
2464
+ candidateNames.push(command.alias());
2465
+ });
2466
+ suggestion = suggestSimilar(unknownName, candidateNames);
2467
+ }
2468
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2469
+ this.error(message, { code: "commander.unknownCommand" });
2470
+ }
2471
+ /**
2472
+ * Get or set the program version.
2473
+ *
2474
+ * This method auto-registers the "-V, --version" option which will print the version number.
2475
+ *
2476
+ * You can optionally supply the flags and description to override the defaults.
2477
+ *
2478
+ * @param {string} [str]
2479
+ * @param {string} [flags]
2480
+ * @param {string} [description]
2481
+ * @return {this | string | undefined} `this` command for chaining, or version string if no arguments
2482
+ */
2483
+ version(str, flags, description) {
2484
+ if (str === void 0)
2485
+ return this._version;
2486
+ this._version = str;
2487
+ flags = flags || "-V, --version";
2488
+ description = description || "output the version number";
2489
+ const versionOption = this.createOption(flags, description);
2490
+ this._versionOptionName = versionOption.attributeName();
2491
+ this.options.push(versionOption);
2492
+ this.on("option:" + versionOption.name(), () => {
2493
+ this._outputConfiguration.writeOut(`${str}
2494
+ `);
2495
+ this._exit(0, "commander.version", str);
2496
+ });
2497
+ return this;
2498
+ }
2499
+ /**
2500
+ * Set the description.
2501
+ *
2502
+ * @param {string} [str]
2503
+ * @param {Object} [argsDescription]
2504
+ * @return {string|Command}
2505
+ */
2506
+ description(str, argsDescription) {
2507
+ if (str === void 0 && argsDescription === void 0)
2508
+ return this._description;
2509
+ this._description = str;
2510
+ if (argsDescription) {
2511
+ this._argsDescription = argsDescription;
2512
+ }
2513
+ return this;
2514
+ }
2515
+ /**
2516
+ * Set the summary. Used when listed as subcommand of parent.
2517
+ *
2518
+ * @param {string} [str]
2519
+ * @return {string|Command}
2520
+ */
2521
+ summary(str) {
2522
+ if (str === void 0)
2523
+ return this._summary;
2524
+ this._summary = str;
2525
+ return this;
2526
+ }
2527
+ /**
2528
+ * Set an alias for the command.
2529
+ *
2530
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2531
+ *
2532
+ * @param {string} [alias]
2533
+ * @return {string|Command}
2534
+ */
2535
+ alias(alias) {
2536
+ if (alias === void 0)
2537
+ return this._aliases[0];
2538
+ let command = this;
2539
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2540
+ command = this.commands[this.commands.length - 1];
2541
+ }
2542
+ if (alias === command._name)
2543
+ throw new Error("Command alias can't be the same as its name");
2544
+ command._aliases.push(alias);
2545
+ return this;
2546
+ }
2547
+ /**
2548
+ * Set aliases for the command.
2549
+ *
2550
+ * Only the first alias is shown in the auto-generated help.
2551
+ *
2552
+ * @param {string[]} [aliases]
2553
+ * @return {string[]|Command}
2554
+ */
2555
+ aliases(aliases) {
2556
+ if (aliases === void 0)
2557
+ return this._aliases;
2558
+ aliases.forEach((alias) => this.alias(alias));
2559
+ return this;
2560
+ }
2561
+ /**
2562
+ * Set / get the command usage `str`.
2563
+ *
2564
+ * @param {string} [str]
2565
+ * @return {String|Command}
2566
+ */
2567
+ usage(str) {
2568
+ if (str === void 0) {
2569
+ if (this._usage)
2570
+ return this._usage;
2571
+ const args = this.registeredArguments.map((arg) => {
2572
+ return humanReadableArgName(arg);
2573
+ });
2574
+ return [].concat(
2575
+ this.options.length || this._hasHelpOption ? "[options]" : [],
2576
+ this.commands.length ? "[command]" : [],
2577
+ this.registeredArguments.length ? args : []
2578
+ ).join(" ");
2579
+ }
2580
+ this._usage = str;
2581
+ return this;
2582
+ }
2583
+ /**
2584
+ * Get or set the name of the command.
2585
+ *
2586
+ * @param {string} [str]
2587
+ * @return {string|Command}
2588
+ */
2589
+ name(str) {
2590
+ if (str === void 0)
2591
+ return this._name;
2592
+ this._name = str;
2593
+ return this;
2594
+ }
2595
+ /**
2596
+ * Set the name of the command from script filename, such as process.argv[1],
2597
+ * or require.main.filename, or __filename.
2598
+ *
2599
+ * (Used internally and public although not documented in README.)
2600
+ *
2601
+ * @example
2602
+ * program.nameFromFilename(require.main.filename);
2603
+ *
2604
+ * @param {string} filename
2605
+ * @return {Command}
2606
+ */
2607
+ nameFromFilename(filename) {
2608
+ this._name = path.basename(filename, path.extname(filename));
2609
+ return this;
2610
+ }
2611
+ /**
2612
+ * Get or set the directory for searching for executable subcommands of this command.
2613
+ *
2614
+ * @example
2615
+ * program.executableDir(__dirname);
2616
+ * // or
2617
+ * program.executableDir('subcommands');
2618
+ *
2619
+ * @param {string} [path]
2620
+ * @return {string|null|Command}
2621
+ */
2622
+ executableDir(path2) {
2623
+ if (path2 === void 0)
2624
+ return this._executableDir;
2625
+ this._executableDir = path2;
2626
+ return this;
2627
+ }
2628
+ /**
2629
+ * Return program help documentation.
2630
+ *
2631
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2632
+ * @return {string}
2633
+ */
2634
+ helpInformation(contextOptions) {
2635
+ const helper = this.createHelp();
2636
+ if (helper.helpWidth === void 0) {
2637
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2638
+ }
2639
+ return helper.formatHelp(this, helper);
2640
+ }
2641
+ /**
2642
+ * @api private
2643
+ */
2644
+ _getHelpContext(contextOptions) {
2645
+ contextOptions = contextOptions || {};
2646
+ const context = { error: !!contextOptions.error };
2647
+ let write;
2648
+ if (context.error) {
2649
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2650
+ } else {
2651
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2652
+ }
2653
+ context.write = contextOptions.write || write;
2654
+ context.command = this;
2655
+ return context;
2656
+ }
2657
+ /**
2658
+ * Output help information for this command.
2659
+ *
2660
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2661
+ *
2662
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2663
+ */
2664
+ outputHelp(contextOptions) {
2665
+ let deprecatedCallback;
2666
+ if (typeof contextOptions === "function") {
2667
+ deprecatedCallback = contextOptions;
2668
+ contextOptions = void 0;
2669
+ }
2670
+ const context = this._getHelpContext(contextOptions);
2671
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2672
+ this.emit("beforeHelp", context);
2673
+ let helpInformation = this.helpInformation(context);
2674
+ if (deprecatedCallback) {
2675
+ helpInformation = deprecatedCallback(helpInformation);
2676
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2677
+ throw new Error("outputHelp callback must return a string or a Buffer");
2678
+ }
2679
+ }
2680
+ context.write(helpInformation);
2681
+ if (this._helpLongFlag) {
2682
+ this.emit(this._helpLongFlag);
2683
+ }
2684
+ this.emit("afterHelp", context);
2685
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
2686
+ }
2687
+ /**
2688
+ * You can pass in flags and a description to override the help
2689
+ * flags and help description for your command. Pass in false to
2690
+ * disable the built-in help option.
2691
+ *
2692
+ * @param {string | boolean} [flags]
2693
+ * @param {string} [description]
2694
+ * @return {Command} `this` command for chaining
2695
+ */
2696
+ helpOption(flags, description) {
2697
+ if (typeof flags === "boolean") {
2698
+ this._hasHelpOption = flags;
2699
+ return this;
2700
+ }
2701
+ this._helpFlags = flags || this._helpFlags;
2702
+ this._helpDescription = description || this._helpDescription;
2703
+ const helpFlags = splitOptionFlags(this._helpFlags);
2704
+ this._helpShortFlag = helpFlags.shortFlag;
2705
+ this._helpLongFlag = helpFlags.longFlag;
2706
+ return this;
2707
+ }
2708
+ /**
2709
+ * Output help information and exit.
2710
+ *
2711
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2712
+ *
2713
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2714
+ */
2715
+ help(contextOptions) {
2716
+ this.outputHelp(contextOptions);
2717
+ let exitCode = process2.exitCode || 0;
2718
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2719
+ exitCode = 1;
2720
+ }
2721
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2722
+ }
2723
+ /**
2724
+ * Add additional text to be displayed with the built-in help.
2725
+ *
2726
+ * Position is 'before' or 'after' to affect just this command,
2727
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2728
+ *
2729
+ * @param {string} position - before or after built-in help
2730
+ * @param {string | Function} text - string to add, or a function returning a string
2731
+ * @return {Command} `this` command for chaining
2732
+ */
2733
+ addHelpText(position, text) {
2734
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2735
+ if (!allowedValues.includes(position)) {
2736
+ throw new Error(`Unexpected value for position to addHelpText.
2737
+ Expecting one of '${allowedValues.join("', '")}'`);
2738
+ }
2739
+ const helpEvent = `${position}Help`;
2740
+ this.on(helpEvent, (context) => {
2741
+ let helpStr;
2742
+ if (typeof text === "function") {
2743
+ helpStr = text({ error: context.error, command: context.command });
2744
+ } else {
2745
+ helpStr = text;
2746
+ }
2747
+ if (helpStr) {
2748
+ context.write(`${helpStr}
2749
+ `);
2750
+ }
2751
+ });
2752
+ return this;
2753
+ }
2754
+ };
2755
+ function outputHelpIfRequested(cmd, args) {
2756
+ const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2757
+ if (helpOption) {
2758
+ cmd.outputHelp();
2759
+ cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2760
+ }
2761
+ }
2762
+ function incrementNodeInspectorPort(args) {
2763
+ return args.map((arg) => {
2764
+ if (!arg.startsWith("--inspect")) {
2765
+ return arg;
2766
+ }
2767
+ let debugOption;
2768
+ let debugHost = "127.0.0.1";
2769
+ let debugPort = "9229";
2770
+ let match;
2771
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2772
+ debugOption = match[1];
2773
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2774
+ debugOption = match[1];
2775
+ if (/^\d+$/.test(match[3])) {
2776
+ debugPort = match[3];
2777
+ } else {
2778
+ debugHost = match[3];
2779
+ }
2780
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2781
+ debugOption = match[1];
2782
+ debugHost = match[3];
2783
+ debugPort = match[4];
2784
+ }
2785
+ if (debugOption && debugPort !== "0") {
2786
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2787
+ }
2788
+ return arg;
2789
+ });
2790
+ }
2791
+ exports.Command = Command2;
2792
+ }
2793
+ });
2794
+
2795
+ // ../../node_modules/commander/index.js
2796
+ var require_commander = __commonJS({
2797
+ "../../node_modules/commander/index.js"(exports, module) {
2798
+ var { Argument: Argument2 } = require_argument();
2799
+ var { Command: Command2 } = require_command();
2800
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2801
+ var { Help: Help2 } = require_help();
2802
+ var { Option: Option2 } = require_option();
2803
+ exports = module.exports = new Command2();
2804
+ exports.program = exports;
2805
+ exports.Command = Command2;
2806
+ exports.Option = Option2;
2807
+ exports.Argument = Argument2;
2808
+ exports.Help = Help2;
2809
+ exports.CommanderError = CommanderError2;
2810
+ exports.InvalidArgumentError = InvalidArgumentError2;
2811
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
2812
+ }
2813
+ });
2814
+
2815
+ // ../../node_modules/escape-string-regexp/index.js
2816
+ var require_escape_string_regexp = __commonJS({
2817
+ "../../node_modules/escape-string-regexp/index.js"(exports, module) {
2818
+ "use strict";
2819
+ var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
2820
+ module.exports = function(str) {
2821
+ if (typeof str !== "string") {
2822
+ throw new TypeError("Expected a string");
2823
+ }
2824
+ return str.replace(matchOperatorsRe, "\\$&");
2825
+ };
2826
+ }
2827
+ });
2828
+
2829
+ // ../../node_modules/color-convert/node_modules/color-name/index.js
2830
+ var require_color_name = __commonJS({
2831
+ "../../node_modules/color-convert/node_modules/color-name/index.js"(exports, module) {
2832
+ "use strict";
2833
+ module.exports = {
2834
+ "aliceblue": [240, 248, 255],
2835
+ "antiquewhite": [250, 235, 215],
2836
+ "aqua": [0, 255, 255],
2837
+ "aquamarine": [127, 255, 212],
2838
+ "azure": [240, 255, 255],
2839
+ "beige": [245, 245, 220],
2840
+ "bisque": [255, 228, 196],
2841
+ "black": [0, 0, 0],
2842
+ "blanchedalmond": [255, 235, 205],
2843
+ "blue": [0, 0, 255],
2844
+ "blueviolet": [138, 43, 226],
2845
+ "brown": [165, 42, 42],
2846
+ "burlywood": [222, 184, 135],
2847
+ "cadetblue": [95, 158, 160],
2848
+ "chartreuse": [127, 255, 0],
2849
+ "chocolate": [210, 105, 30],
2850
+ "coral": [255, 127, 80],
2851
+ "cornflowerblue": [100, 149, 237],
2852
+ "cornsilk": [255, 248, 220],
2853
+ "crimson": [220, 20, 60],
2854
+ "cyan": [0, 255, 255],
2855
+ "darkblue": [0, 0, 139],
2856
+ "darkcyan": [0, 139, 139],
2857
+ "darkgoldenrod": [184, 134, 11],
2858
+ "darkgray": [169, 169, 169],
2859
+ "darkgreen": [0, 100, 0],
2860
+ "darkgrey": [169, 169, 169],
2861
+ "darkkhaki": [189, 183, 107],
2862
+ "darkmagenta": [139, 0, 139],
2863
+ "darkolivegreen": [85, 107, 47],
2864
+ "darkorange": [255, 140, 0],
2865
+ "darkorchid": [153, 50, 204],
2866
+ "darkred": [139, 0, 0],
2867
+ "darksalmon": [233, 150, 122],
2868
+ "darkseagreen": [143, 188, 143],
2869
+ "darkslateblue": [72, 61, 139],
2870
+ "darkslategray": [47, 79, 79],
2871
+ "darkslategrey": [47, 79, 79],
2872
+ "darkturquoise": [0, 206, 209],
2873
+ "darkviolet": [148, 0, 211],
2874
+ "deeppink": [255, 20, 147],
2875
+ "deepskyblue": [0, 191, 255],
2876
+ "dimgray": [105, 105, 105],
2877
+ "dimgrey": [105, 105, 105],
2878
+ "dodgerblue": [30, 144, 255],
2879
+ "firebrick": [178, 34, 34],
2880
+ "floralwhite": [255, 250, 240],
2881
+ "forestgreen": [34, 139, 34],
2882
+ "fuchsia": [255, 0, 255],
2883
+ "gainsboro": [220, 220, 220],
2884
+ "ghostwhite": [248, 248, 255],
2885
+ "gold": [255, 215, 0],
2886
+ "goldenrod": [218, 165, 32],
2887
+ "gray": [128, 128, 128],
2888
+ "green": [0, 128, 0],
2889
+ "greenyellow": [173, 255, 47],
2890
+ "grey": [128, 128, 128],
2891
+ "honeydew": [240, 255, 240],
2892
+ "hotpink": [255, 105, 180],
2893
+ "indianred": [205, 92, 92],
2894
+ "indigo": [75, 0, 130],
2895
+ "ivory": [255, 255, 240],
2896
+ "khaki": [240, 230, 140],
2897
+ "lavender": [230, 230, 250],
2898
+ "lavenderblush": [255, 240, 245],
2899
+ "lawngreen": [124, 252, 0],
2900
+ "lemonchiffon": [255, 250, 205],
2901
+ "lightblue": [173, 216, 230],
2902
+ "lightcoral": [240, 128, 128],
2903
+ "lightcyan": [224, 255, 255],
2904
+ "lightgoldenrodyellow": [250, 250, 210],
2905
+ "lightgray": [211, 211, 211],
2906
+ "lightgreen": [144, 238, 144],
2907
+ "lightgrey": [211, 211, 211],
2908
+ "lightpink": [255, 182, 193],
2909
+ "lightsalmon": [255, 160, 122],
2910
+ "lightseagreen": [32, 178, 170],
2911
+ "lightskyblue": [135, 206, 250],
2912
+ "lightslategray": [119, 136, 153],
2913
+ "lightslategrey": [119, 136, 153],
2914
+ "lightsteelblue": [176, 196, 222],
2915
+ "lightyellow": [255, 255, 224],
2916
+ "lime": [0, 255, 0],
2917
+ "limegreen": [50, 205, 50],
2918
+ "linen": [250, 240, 230],
2919
+ "magenta": [255, 0, 255],
2920
+ "maroon": [128, 0, 0],
2921
+ "mediumaquamarine": [102, 205, 170],
2922
+ "mediumblue": [0, 0, 205],
2923
+ "mediumorchid": [186, 85, 211],
2924
+ "mediumpurple": [147, 112, 219],
2925
+ "mediumseagreen": [60, 179, 113],
2926
+ "mediumslateblue": [123, 104, 238],
2927
+ "mediumspringgreen": [0, 250, 154],
2928
+ "mediumturquoise": [72, 209, 204],
2929
+ "mediumvioletred": [199, 21, 133],
2930
+ "midnightblue": [25, 25, 112],
2931
+ "mintcream": [245, 255, 250],
2932
+ "mistyrose": [255, 228, 225],
2933
+ "moccasin": [255, 228, 181],
2934
+ "navajowhite": [255, 222, 173],
2935
+ "navy": [0, 0, 128],
2936
+ "oldlace": [253, 245, 230],
2937
+ "olive": [128, 128, 0],
2938
+ "olivedrab": [107, 142, 35],
2939
+ "orange": [255, 165, 0],
2940
+ "orangered": [255, 69, 0],
2941
+ "orchid": [218, 112, 214],
2942
+ "palegoldenrod": [238, 232, 170],
2943
+ "palegreen": [152, 251, 152],
2944
+ "paleturquoise": [175, 238, 238],
2945
+ "palevioletred": [219, 112, 147],
2946
+ "papayawhip": [255, 239, 213],
2947
+ "peachpuff": [255, 218, 185],
2948
+ "peru": [205, 133, 63],
2949
+ "pink": [255, 192, 203],
2950
+ "plum": [221, 160, 221],
2951
+ "powderblue": [176, 224, 230],
2952
+ "purple": [128, 0, 128],
2953
+ "rebeccapurple": [102, 51, 153],
2954
+ "red": [255, 0, 0],
2955
+ "rosybrown": [188, 143, 143],
2956
+ "royalblue": [65, 105, 225],
2957
+ "saddlebrown": [139, 69, 19],
2958
+ "salmon": [250, 128, 114],
2959
+ "sandybrown": [244, 164, 96],
2960
+ "seagreen": [46, 139, 87],
2961
+ "seashell": [255, 245, 238],
2962
+ "sienna": [160, 82, 45],
2963
+ "silver": [192, 192, 192],
2964
+ "skyblue": [135, 206, 235],
2965
+ "slateblue": [106, 90, 205],
2966
+ "slategray": [112, 128, 144],
2967
+ "slategrey": [112, 128, 144],
2968
+ "snow": [255, 250, 250],
2969
+ "springgreen": [0, 255, 127],
2970
+ "steelblue": [70, 130, 180],
2971
+ "tan": [210, 180, 140],
2972
+ "teal": [0, 128, 128],
2973
+ "thistle": [216, 191, 216],
2974
+ "tomato": [255, 99, 71],
2975
+ "turquoise": [64, 224, 208],
2976
+ "violet": [238, 130, 238],
2977
+ "wheat": [245, 222, 179],
2978
+ "white": [255, 255, 255],
2979
+ "whitesmoke": [245, 245, 245],
2980
+ "yellow": [255, 255, 0],
2981
+ "yellowgreen": [154, 205, 50]
2982
+ };
2983
+ }
2984
+ });
2985
+
2986
+ // ../../node_modules/color-convert/conversions.js
2987
+ var require_conversions = __commonJS({
2988
+ "../../node_modules/color-convert/conversions.js"(exports, module) {
2989
+ var cssKeywords = require_color_name();
2990
+ var reverseKeywords = {};
2991
+ for (key in cssKeywords) {
2992
+ if (cssKeywords.hasOwnProperty(key)) {
2993
+ reverseKeywords[cssKeywords[key]] = key;
2994
+ }
2995
+ }
2996
+ var key;
2997
+ var convert = module.exports = {
2998
+ rgb: { channels: 3, labels: "rgb" },
2999
+ hsl: { channels: 3, labels: "hsl" },
3000
+ hsv: { channels: 3, labels: "hsv" },
3001
+ hwb: { channels: 3, labels: "hwb" },
3002
+ cmyk: { channels: 4, labels: "cmyk" },
3003
+ xyz: { channels: 3, labels: "xyz" },
3004
+ lab: { channels: 3, labels: "lab" },
3005
+ lch: { channels: 3, labels: "lch" },
3006
+ hex: { channels: 1, labels: ["hex"] },
3007
+ keyword: { channels: 1, labels: ["keyword"] },
3008
+ ansi16: { channels: 1, labels: ["ansi16"] },
3009
+ ansi256: { channels: 1, labels: ["ansi256"] },
3010
+ hcg: { channels: 3, labels: ["h", "c", "g"] },
3011
+ apple: { channels: 3, labels: ["r16", "g16", "b16"] },
3012
+ gray: { channels: 1, labels: ["gray"] }
3013
+ };
3014
+ for (model in convert) {
3015
+ if (convert.hasOwnProperty(model)) {
3016
+ if (!("channels" in convert[model])) {
3017
+ throw new Error("missing channels property: " + model);
3018
+ }
3019
+ if (!("labels" in convert[model])) {
3020
+ throw new Error("missing channel labels property: " + model);
3021
+ }
3022
+ if (convert[model].labels.length !== convert[model].channels) {
3023
+ throw new Error("channel and label counts mismatch: " + model);
3024
+ }
3025
+ channels = convert[model].channels;
3026
+ labels = convert[model].labels;
3027
+ delete convert[model].channels;
3028
+ delete convert[model].labels;
3029
+ Object.defineProperty(convert[model], "channels", { value: channels });
3030
+ Object.defineProperty(convert[model], "labels", { value: labels });
3031
+ }
3032
+ }
3033
+ var channels;
3034
+ var labels;
3035
+ var model;
3036
+ convert.rgb.hsl = function(rgb) {
3037
+ var r = rgb[0] / 255;
3038
+ var g = rgb[1] / 255;
3039
+ var b = rgb[2] / 255;
3040
+ var min = Math.min(r, g, b);
3041
+ var max = Math.max(r, g, b);
3042
+ var delta = max - min;
3043
+ var h;
3044
+ var s;
3045
+ var l;
3046
+ if (max === min) {
3047
+ h = 0;
3048
+ } else if (r === max) {
3049
+ h = (g - b) / delta;
3050
+ } else if (g === max) {
3051
+ h = 2 + (b - r) / delta;
3052
+ } else if (b === max) {
3053
+ h = 4 + (r - g) / delta;
3054
+ }
3055
+ h = Math.min(h * 60, 360);
3056
+ if (h < 0) {
3057
+ h += 360;
3058
+ }
3059
+ l = (min + max) / 2;
3060
+ if (max === min) {
3061
+ s = 0;
3062
+ } else if (l <= 0.5) {
3063
+ s = delta / (max + min);
3064
+ } else {
3065
+ s = delta / (2 - max - min);
3066
+ }
3067
+ return [h, s * 100, l * 100];
3068
+ };
3069
+ convert.rgb.hsv = function(rgb) {
3070
+ var rdif;
3071
+ var gdif;
3072
+ var bdif;
3073
+ var h;
3074
+ var s;
3075
+ var r = rgb[0] / 255;
3076
+ var g = rgb[1] / 255;
3077
+ var b = rgb[2] / 255;
3078
+ var v = Math.max(r, g, b);
3079
+ var diff = v - Math.min(r, g, b);
3080
+ var diffc = function(c) {
3081
+ return (v - c) / 6 / diff + 1 / 2;
3082
+ };
3083
+ if (diff === 0) {
3084
+ h = s = 0;
3085
+ } else {
3086
+ s = diff / v;
3087
+ rdif = diffc(r);
3088
+ gdif = diffc(g);
3089
+ bdif = diffc(b);
3090
+ if (r === v) {
3091
+ h = bdif - gdif;
3092
+ } else if (g === v) {
3093
+ h = 1 / 3 + rdif - bdif;
3094
+ } else if (b === v) {
3095
+ h = 2 / 3 + gdif - rdif;
3096
+ }
3097
+ if (h < 0) {
3098
+ h += 1;
3099
+ } else if (h > 1) {
3100
+ h -= 1;
3101
+ }
3102
+ }
3103
+ return [
3104
+ h * 360,
3105
+ s * 100,
3106
+ v * 100
3107
+ ];
3108
+ };
3109
+ convert.rgb.hwb = function(rgb) {
3110
+ var r = rgb[0];
3111
+ var g = rgb[1];
3112
+ var b = rgb[2];
3113
+ var h = convert.rgb.hsl(rgb)[0];
3114
+ var w = 1 / 255 * Math.min(r, Math.min(g, b));
3115
+ b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
3116
+ return [h, w * 100, b * 100];
3117
+ };
3118
+ convert.rgb.cmyk = function(rgb) {
3119
+ var r = rgb[0] / 255;
3120
+ var g = rgb[1] / 255;
3121
+ var b = rgb[2] / 255;
3122
+ var c;
3123
+ var m;
3124
+ var y;
3125
+ var k;
3126
+ k = Math.min(1 - r, 1 - g, 1 - b);
3127
+ c = (1 - r - k) / (1 - k) || 0;
3128
+ m = (1 - g - k) / (1 - k) || 0;
3129
+ y = (1 - b - k) / (1 - k) || 0;
3130
+ return [c * 100, m * 100, y * 100, k * 100];
3131
+ };
3132
+ function comparativeDistance(x, y) {
3133
+ return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
3134
+ }
3135
+ convert.rgb.keyword = function(rgb) {
3136
+ var reversed = reverseKeywords[rgb];
3137
+ if (reversed) {
3138
+ return reversed;
3139
+ }
3140
+ var currentClosestDistance = Infinity;
3141
+ var currentClosestKeyword;
3142
+ for (var keyword in cssKeywords) {
3143
+ if (cssKeywords.hasOwnProperty(keyword)) {
3144
+ var value = cssKeywords[keyword];
3145
+ var distance = comparativeDistance(rgb, value);
3146
+ if (distance < currentClosestDistance) {
3147
+ currentClosestDistance = distance;
3148
+ currentClosestKeyword = keyword;
3149
+ }
3150
+ }
3151
+ }
3152
+ return currentClosestKeyword;
3153
+ };
3154
+ convert.keyword.rgb = function(keyword) {
3155
+ return cssKeywords[keyword];
3156
+ };
3157
+ convert.rgb.xyz = function(rgb) {
3158
+ var r = rgb[0] / 255;
3159
+ var g = rgb[1] / 255;
3160
+ var b = rgb[2] / 255;
3161
+ r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
3162
+ g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
3163
+ b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
3164
+ var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
3165
+ var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
3166
+ var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
3167
+ return [x * 100, y * 100, z * 100];
3168
+ };
3169
+ convert.rgb.lab = function(rgb) {
3170
+ var xyz = convert.rgb.xyz(rgb);
3171
+ var x = xyz[0];
3172
+ var y = xyz[1];
3173
+ var z = xyz[2];
3174
+ var l;
3175
+ var a;
3176
+ var b;
3177
+ x /= 95.047;
3178
+ y /= 100;
3179
+ z /= 108.883;
3180
+ x = x > 8856e-6 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
3181
+ y = y > 8856e-6 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
3182
+ z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
3183
+ l = 116 * y - 16;
3184
+ a = 500 * (x - y);
3185
+ b = 200 * (y - z);
3186
+ return [l, a, b];
3187
+ };
3188
+ convert.hsl.rgb = function(hsl) {
3189
+ var h = hsl[0] / 360;
3190
+ var s = hsl[1] / 100;
3191
+ var l = hsl[2] / 100;
3192
+ var t1;
3193
+ var t2;
3194
+ var t3;
3195
+ var rgb;
3196
+ var val;
3197
+ if (s === 0) {
3198
+ val = l * 255;
3199
+ return [val, val, val];
3200
+ }
3201
+ if (l < 0.5) {
3202
+ t2 = l * (1 + s);
3203
+ } else {
3204
+ t2 = l + s - l * s;
3205
+ }
3206
+ t1 = 2 * l - t2;
3207
+ rgb = [0, 0, 0];
3208
+ for (var i = 0; i < 3; i++) {
3209
+ t3 = h + 1 / 3 * -(i - 1);
3210
+ if (t3 < 0) {
3211
+ t3++;
3212
+ }
3213
+ if (t3 > 1) {
3214
+ t3--;
3215
+ }
3216
+ if (6 * t3 < 1) {
3217
+ val = t1 + (t2 - t1) * 6 * t3;
3218
+ } else if (2 * t3 < 1) {
3219
+ val = t2;
3220
+ } else if (3 * t3 < 2) {
3221
+ val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
3222
+ } else {
3223
+ val = t1;
3224
+ }
3225
+ rgb[i] = val * 255;
3226
+ }
3227
+ return rgb;
3228
+ };
3229
+ convert.hsl.hsv = function(hsl) {
3230
+ var h = hsl[0];
3231
+ var s = hsl[1] / 100;
3232
+ var l = hsl[2] / 100;
3233
+ var smin = s;
3234
+ var lmin = Math.max(l, 0.01);
3235
+ var sv;
3236
+ var v;
3237
+ l *= 2;
3238
+ s *= l <= 1 ? l : 2 - l;
3239
+ smin *= lmin <= 1 ? lmin : 2 - lmin;
3240
+ v = (l + s) / 2;
3241
+ sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
3242
+ return [h, sv * 100, v * 100];
3243
+ };
3244
+ convert.hsv.rgb = function(hsv) {
3245
+ var h = hsv[0] / 60;
3246
+ var s = hsv[1] / 100;
3247
+ var v = hsv[2] / 100;
3248
+ var hi = Math.floor(h) % 6;
3249
+ var f = h - Math.floor(h);
3250
+ var p = 255 * v * (1 - s);
3251
+ var q = 255 * v * (1 - s * f);
3252
+ var t = 255 * v * (1 - s * (1 - f));
3253
+ v *= 255;
3254
+ switch (hi) {
3255
+ case 0:
3256
+ return [v, t, p];
3257
+ case 1:
3258
+ return [q, v, p];
3259
+ case 2:
3260
+ return [p, v, t];
3261
+ case 3:
3262
+ return [p, q, v];
3263
+ case 4:
3264
+ return [t, p, v];
3265
+ case 5:
3266
+ return [v, p, q];
3267
+ }
3268
+ };
3269
+ convert.hsv.hsl = function(hsv) {
3270
+ var h = hsv[0];
3271
+ var s = hsv[1] / 100;
3272
+ var v = hsv[2] / 100;
3273
+ var vmin = Math.max(v, 0.01);
3274
+ var lmin;
3275
+ var sl;
3276
+ var l;
3277
+ l = (2 - s) * v;
3278
+ lmin = (2 - s) * vmin;
3279
+ sl = s * vmin;
3280
+ sl /= lmin <= 1 ? lmin : 2 - lmin;
3281
+ sl = sl || 0;
3282
+ l /= 2;
3283
+ return [h, sl * 100, l * 100];
3284
+ };
3285
+ convert.hwb.rgb = function(hwb) {
3286
+ var h = hwb[0] / 360;
3287
+ var wh = hwb[1] / 100;
3288
+ var bl = hwb[2] / 100;
3289
+ var ratio = wh + bl;
3290
+ var i;
3291
+ var v;
3292
+ var f;
3293
+ var n;
3294
+ if (ratio > 1) {
3295
+ wh /= ratio;
3296
+ bl /= ratio;
3297
+ }
3298
+ i = Math.floor(6 * h);
3299
+ v = 1 - bl;
3300
+ f = 6 * h - i;
3301
+ if ((i & 1) !== 0) {
3302
+ f = 1 - f;
3303
+ }
3304
+ n = wh + f * (v - wh);
3305
+ var r;
3306
+ var g;
3307
+ var b;
3308
+ switch (i) {
3309
+ default:
3310
+ case 6:
3311
+ case 0:
3312
+ r = v;
3313
+ g = n;
3314
+ b = wh;
3315
+ break;
3316
+ case 1:
3317
+ r = n;
3318
+ g = v;
3319
+ b = wh;
3320
+ break;
3321
+ case 2:
3322
+ r = wh;
3323
+ g = v;
3324
+ b = n;
3325
+ break;
3326
+ case 3:
3327
+ r = wh;
3328
+ g = n;
3329
+ b = v;
3330
+ break;
3331
+ case 4:
3332
+ r = n;
3333
+ g = wh;
3334
+ b = v;
3335
+ break;
3336
+ case 5:
3337
+ r = v;
3338
+ g = wh;
3339
+ b = n;
3340
+ break;
3341
+ }
3342
+ return [r * 255, g * 255, b * 255];
3343
+ };
3344
+ convert.cmyk.rgb = function(cmyk) {
3345
+ var c = cmyk[0] / 100;
3346
+ var m = cmyk[1] / 100;
3347
+ var y = cmyk[2] / 100;
3348
+ var k = cmyk[3] / 100;
3349
+ var r;
3350
+ var g;
3351
+ var b;
3352
+ r = 1 - Math.min(1, c * (1 - k) + k);
3353
+ g = 1 - Math.min(1, m * (1 - k) + k);
3354
+ b = 1 - Math.min(1, y * (1 - k) + k);
3355
+ return [r * 255, g * 255, b * 255];
3356
+ };
3357
+ convert.xyz.rgb = function(xyz) {
3358
+ var x = xyz[0] / 100;
3359
+ var y = xyz[1] / 100;
3360
+ var z = xyz[2] / 100;
3361
+ var r;
3362
+ var g;
3363
+ var b;
3364
+ r = x * 3.2406 + y * -1.5372 + z * -0.4986;
3365
+ g = x * -0.9689 + y * 1.8758 + z * 0.0415;
3366
+ b = x * 0.0557 + y * -0.204 + z * 1.057;
3367
+ r = r > 31308e-7 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : r * 12.92;
3368
+ g = g > 31308e-7 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : g * 12.92;
3369
+ b = b > 31308e-7 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : b * 12.92;
3370
+ r = Math.min(Math.max(0, r), 1);
3371
+ g = Math.min(Math.max(0, g), 1);
3372
+ b = Math.min(Math.max(0, b), 1);
3373
+ return [r * 255, g * 255, b * 255];
3374
+ };
3375
+ convert.xyz.lab = function(xyz) {
3376
+ var x = xyz[0];
3377
+ var y = xyz[1];
3378
+ var z = xyz[2];
3379
+ var l;
3380
+ var a;
3381
+ var b;
3382
+ x /= 95.047;
3383
+ y /= 100;
3384
+ z /= 108.883;
3385
+ x = x > 8856e-6 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
3386
+ y = y > 8856e-6 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
3387
+ z = z > 8856e-6 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
3388
+ l = 116 * y - 16;
3389
+ a = 500 * (x - y);
3390
+ b = 200 * (y - z);
3391
+ return [l, a, b];
3392
+ };
3393
+ convert.lab.xyz = function(lab) {
3394
+ var l = lab[0];
3395
+ var a = lab[1];
3396
+ var b = lab[2];
3397
+ var x;
3398
+ var y;
3399
+ var z;
3400
+ y = (l + 16) / 116;
3401
+ x = a / 500 + y;
3402
+ z = y - b / 200;
3403
+ var y2 = Math.pow(y, 3);
3404
+ var x2 = Math.pow(x, 3);
3405
+ var z2 = Math.pow(z, 3);
3406
+ y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787;
3407
+ x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787;
3408
+ z = z2 > 8856e-6 ? z2 : (z - 16 / 116) / 7.787;
3409
+ x *= 95.047;
3410
+ y *= 100;
3411
+ z *= 108.883;
3412
+ return [x, y, z];
3413
+ };
3414
+ convert.lab.lch = function(lab) {
3415
+ var l = lab[0];
3416
+ var a = lab[1];
3417
+ var b = lab[2];
3418
+ var hr;
3419
+ var h;
3420
+ var c;
3421
+ hr = Math.atan2(b, a);
3422
+ h = hr * 360 / 2 / Math.PI;
3423
+ if (h < 0) {
3424
+ h += 360;
3425
+ }
3426
+ c = Math.sqrt(a * a + b * b);
3427
+ return [l, c, h];
3428
+ };
3429
+ convert.lch.lab = function(lch) {
3430
+ var l = lch[0];
3431
+ var c = lch[1];
3432
+ var h = lch[2];
3433
+ var a;
3434
+ var b;
3435
+ var hr;
3436
+ hr = h / 360 * 2 * Math.PI;
3437
+ a = c * Math.cos(hr);
3438
+ b = c * Math.sin(hr);
3439
+ return [l, a, b];
3440
+ };
3441
+ convert.rgb.ansi16 = function(args) {
3442
+ var r = args[0];
3443
+ var g = args[1];
3444
+ var b = args[2];
3445
+ var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2];
3446
+ value = Math.round(value / 50);
3447
+ if (value === 0) {
3448
+ return 30;
3449
+ }
3450
+ var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
3451
+ if (value === 2) {
3452
+ ansi += 60;
3453
+ }
3454
+ return ansi;
3455
+ };
3456
+ convert.hsv.ansi16 = function(args) {
3457
+ return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
3458
+ };
3459
+ convert.rgb.ansi256 = function(args) {
3460
+ var r = args[0];
3461
+ var g = args[1];
3462
+ var b = args[2];
3463
+ if (r === g && g === b) {
3464
+ if (r < 8) {
3465
+ return 16;
3466
+ }
3467
+ if (r > 248) {
3468
+ return 231;
3469
+ }
3470
+ return Math.round((r - 8) / 247 * 24) + 232;
3471
+ }
3472
+ var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
3473
+ return ansi;
3474
+ };
3475
+ convert.ansi16.rgb = function(args) {
3476
+ var color = args % 10;
3477
+ if (color === 0 || color === 7) {
3478
+ if (args > 50) {
3479
+ color += 3.5;
3480
+ }
3481
+ color = color / 10.5 * 255;
3482
+ return [color, color, color];
3483
+ }
3484
+ var mult = (~~(args > 50) + 1) * 0.5;
3485
+ var r = (color & 1) * mult * 255;
3486
+ var g = (color >> 1 & 1) * mult * 255;
3487
+ var b = (color >> 2 & 1) * mult * 255;
3488
+ return [r, g, b];
3489
+ };
3490
+ convert.ansi256.rgb = function(args) {
3491
+ if (args >= 232) {
3492
+ var c = (args - 232) * 10 + 8;
3493
+ return [c, c, c];
3494
+ }
3495
+ args -= 16;
3496
+ var rem;
3497
+ var r = Math.floor(args / 36) / 5 * 255;
3498
+ var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
3499
+ var b = rem % 6 / 5 * 255;
3500
+ return [r, g, b];
3501
+ };
3502
+ convert.rgb.hex = function(args) {
3503
+ var integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
3504
+ var string = integer.toString(16).toUpperCase();
3505
+ return "000000".substring(string.length) + string;
3506
+ };
3507
+ convert.hex.rgb = function(args) {
3508
+ var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
3509
+ if (!match) {
3510
+ return [0, 0, 0];
3511
+ }
3512
+ var colorString = match[0];
3513
+ if (match[0].length === 3) {
3514
+ colorString = colorString.split("").map(function(char) {
3515
+ return char + char;
3516
+ }).join("");
3517
+ }
3518
+ var integer = parseInt(colorString, 16);
3519
+ var r = integer >> 16 & 255;
3520
+ var g = integer >> 8 & 255;
3521
+ var b = integer & 255;
3522
+ return [r, g, b];
3523
+ };
3524
+ convert.rgb.hcg = function(rgb) {
3525
+ var r = rgb[0] / 255;
3526
+ var g = rgb[1] / 255;
3527
+ var b = rgb[2] / 255;
3528
+ var max = Math.max(Math.max(r, g), b);
3529
+ var min = Math.min(Math.min(r, g), b);
3530
+ var chroma = max - min;
3531
+ var grayscale;
3532
+ var hue;
3533
+ if (chroma < 1) {
3534
+ grayscale = min / (1 - chroma);
3535
+ } else {
3536
+ grayscale = 0;
3537
+ }
3538
+ if (chroma <= 0) {
3539
+ hue = 0;
3540
+ } else if (max === r) {
3541
+ hue = (g - b) / chroma % 6;
3542
+ } else if (max === g) {
3543
+ hue = 2 + (b - r) / chroma;
3544
+ } else {
3545
+ hue = 4 + (r - g) / chroma + 4;
3546
+ }
3547
+ hue /= 6;
3548
+ hue %= 1;
3549
+ return [hue * 360, chroma * 100, grayscale * 100];
3550
+ };
3551
+ convert.hsl.hcg = function(hsl) {
3552
+ var s = hsl[1] / 100;
3553
+ var l = hsl[2] / 100;
3554
+ var c = 1;
3555
+ var f = 0;
3556
+ if (l < 0.5) {
3557
+ c = 2 * s * l;
3558
+ } else {
3559
+ c = 2 * s * (1 - l);
3560
+ }
3561
+ if (c < 1) {
3562
+ f = (l - 0.5 * c) / (1 - c);
3563
+ }
3564
+ return [hsl[0], c * 100, f * 100];
3565
+ };
3566
+ convert.hsv.hcg = function(hsv) {
3567
+ var s = hsv[1] / 100;
3568
+ var v = hsv[2] / 100;
3569
+ var c = s * v;
3570
+ var f = 0;
3571
+ if (c < 1) {
3572
+ f = (v - c) / (1 - c);
3573
+ }
3574
+ return [hsv[0], c * 100, f * 100];
3575
+ };
3576
+ convert.hcg.rgb = function(hcg) {
3577
+ var h = hcg[0] / 360;
3578
+ var c = hcg[1] / 100;
3579
+ var g = hcg[2] / 100;
3580
+ if (c === 0) {
3581
+ return [g * 255, g * 255, g * 255];
3582
+ }
3583
+ var pure = [0, 0, 0];
3584
+ var hi = h % 1 * 6;
3585
+ var v = hi % 1;
3586
+ var w = 1 - v;
3587
+ var mg = 0;
3588
+ switch (Math.floor(hi)) {
3589
+ case 0:
3590
+ pure[0] = 1;
3591
+ pure[1] = v;
3592
+ pure[2] = 0;
3593
+ break;
3594
+ case 1:
3595
+ pure[0] = w;
3596
+ pure[1] = 1;
3597
+ pure[2] = 0;
3598
+ break;
3599
+ case 2:
3600
+ pure[0] = 0;
3601
+ pure[1] = 1;
3602
+ pure[2] = v;
3603
+ break;
3604
+ case 3:
3605
+ pure[0] = 0;
3606
+ pure[1] = w;
3607
+ pure[2] = 1;
3608
+ break;
3609
+ case 4:
3610
+ pure[0] = v;
3611
+ pure[1] = 0;
3612
+ pure[2] = 1;
3613
+ break;
3614
+ default:
3615
+ pure[0] = 1;
3616
+ pure[1] = 0;
3617
+ pure[2] = w;
3618
+ }
3619
+ mg = (1 - c) * g;
3620
+ return [
3621
+ (c * pure[0] + mg) * 255,
3622
+ (c * pure[1] + mg) * 255,
3623
+ (c * pure[2] + mg) * 255
3624
+ ];
3625
+ };
3626
+ convert.hcg.hsv = function(hcg) {
3627
+ var c = hcg[1] / 100;
3628
+ var g = hcg[2] / 100;
3629
+ var v = c + g * (1 - c);
3630
+ var f = 0;
3631
+ if (v > 0) {
3632
+ f = c / v;
3633
+ }
3634
+ return [hcg[0], f * 100, v * 100];
3635
+ };
3636
+ convert.hcg.hsl = function(hcg) {
3637
+ var c = hcg[1] / 100;
3638
+ var g = hcg[2] / 100;
3639
+ var l = g * (1 - c) + 0.5 * c;
3640
+ var s = 0;
3641
+ if (l > 0 && l < 0.5) {
3642
+ s = c / (2 * l);
3643
+ } else if (l >= 0.5 && l < 1) {
3644
+ s = c / (2 * (1 - l));
3645
+ }
3646
+ return [hcg[0], s * 100, l * 100];
3647
+ };
3648
+ convert.hcg.hwb = function(hcg) {
3649
+ var c = hcg[1] / 100;
3650
+ var g = hcg[2] / 100;
3651
+ var v = c + g * (1 - c);
3652
+ return [hcg[0], (v - c) * 100, (1 - v) * 100];
3653
+ };
3654
+ convert.hwb.hcg = function(hwb) {
3655
+ var w = hwb[1] / 100;
3656
+ var b = hwb[2] / 100;
3657
+ var v = 1 - b;
3658
+ var c = v - w;
3659
+ var g = 0;
3660
+ if (c < 1) {
3661
+ g = (v - c) / (1 - c);
3662
+ }
3663
+ return [hwb[0], c * 100, g * 100];
3664
+ };
3665
+ convert.apple.rgb = function(apple) {
3666
+ return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
3667
+ };
3668
+ convert.rgb.apple = function(rgb) {
3669
+ return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
3670
+ };
3671
+ convert.gray.rgb = function(args) {
3672
+ return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
3673
+ };
3674
+ convert.gray.hsl = convert.gray.hsv = function(args) {
3675
+ return [0, 0, args[0]];
3676
+ };
3677
+ convert.gray.hwb = function(gray) {
3678
+ return [0, 100, gray[0]];
3679
+ };
3680
+ convert.gray.cmyk = function(gray) {
3681
+ return [0, 0, 0, gray[0]];
3682
+ };
3683
+ convert.gray.lab = function(gray) {
3684
+ return [gray[0], 0, 0];
3685
+ };
3686
+ convert.gray.hex = function(gray) {
3687
+ var val = Math.round(gray[0] / 100 * 255) & 255;
3688
+ var integer = (val << 16) + (val << 8) + val;
3689
+ var string = integer.toString(16).toUpperCase();
3690
+ return "000000".substring(string.length) + string;
3691
+ };
3692
+ convert.rgb.gray = function(rgb) {
3693
+ var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
3694
+ return [val / 255 * 100];
3695
+ };
3696
+ }
3697
+ });
3698
+
3699
+ // ../../node_modules/color-convert/route.js
3700
+ var require_route = __commonJS({
3701
+ "../../node_modules/color-convert/route.js"(exports, module) {
3702
+ var conversions = require_conversions();
3703
+ function buildGraph() {
3704
+ var graph = {};
3705
+ var models = Object.keys(conversions);
3706
+ for (var len = models.length, i = 0; i < len; i++) {
3707
+ graph[models[i]] = {
3708
+ // http://jsperf.com/1-vs-infinity
3709
+ // micro-opt, but this is simple.
3710
+ distance: -1,
3711
+ parent: null
3712
+ };
3713
+ }
3714
+ return graph;
3715
+ }
3716
+ function deriveBFS(fromModel) {
3717
+ var graph = buildGraph();
3718
+ var queue = [fromModel];
3719
+ graph[fromModel].distance = 0;
3720
+ while (queue.length) {
3721
+ var current = queue.pop();
3722
+ var adjacents = Object.keys(conversions[current]);
3723
+ for (var len = adjacents.length, i = 0; i < len; i++) {
3724
+ var adjacent = adjacents[i];
3725
+ var node = graph[adjacent];
3726
+ if (node.distance === -1) {
3727
+ node.distance = graph[current].distance + 1;
3728
+ node.parent = current;
3729
+ queue.unshift(adjacent);
3730
+ }
3731
+ }
3732
+ }
3733
+ return graph;
3734
+ }
3735
+ function link(from, to) {
3736
+ return function(args) {
3737
+ return to(from(args));
3738
+ };
3739
+ }
3740
+ function wrapConversion(toModel, graph) {
3741
+ var path = [graph[toModel].parent, toModel];
3742
+ var fn = conversions[graph[toModel].parent][toModel];
3743
+ var cur = graph[toModel].parent;
3744
+ while (graph[cur].parent) {
3745
+ path.unshift(graph[cur].parent);
3746
+ fn = link(conversions[graph[cur].parent][cur], fn);
3747
+ cur = graph[cur].parent;
3748
+ }
3749
+ fn.conversion = path;
3750
+ return fn;
3751
+ }
3752
+ module.exports = function(fromModel) {
3753
+ var graph = deriveBFS(fromModel);
3754
+ var conversion = {};
3755
+ var models = Object.keys(graph);
3756
+ for (var len = models.length, i = 0; i < len; i++) {
3757
+ var toModel = models[i];
3758
+ var node = graph[toModel];
3759
+ if (node.parent === null) {
3760
+ continue;
3761
+ }
3762
+ conversion[toModel] = wrapConversion(toModel, graph);
3763
+ }
3764
+ return conversion;
3765
+ };
3766
+ }
3767
+ });
3768
+
3769
+ // ../../node_modules/color-convert/index.js
3770
+ var require_color_convert = __commonJS({
3771
+ "../../node_modules/color-convert/index.js"(exports, module) {
3772
+ var conversions = require_conversions();
3773
+ var route = require_route();
3774
+ var convert = {};
3775
+ var models = Object.keys(conversions);
3776
+ function wrapRaw(fn) {
3777
+ var wrappedFn = function(args) {
3778
+ if (args === void 0 || args === null) {
3779
+ return args;
3780
+ }
3781
+ if (arguments.length > 1) {
3782
+ args = Array.prototype.slice.call(arguments);
3783
+ }
3784
+ return fn(args);
3785
+ };
3786
+ if ("conversion" in fn) {
3787
+ wrappedFn.conversion = fn.conversion;
3788
+ }
3789
+ return wrappedFn;
3790
+ }
3791
+ function wrapRounded(fn) {
3792
+ var wrappedFn = function(args) {
3793
+ if (args === void 0 || args === null) {
3794
+ return args;
3795
+ }
3796
+ if (arguments.length > 1) {
3797
+ args = Array.prototype.slice.call(arguments);
3798
+ }
3799
+ var result = fn(args);
3800
+ if (typeof result === "object") {
3801
+ for (var len = result.length, i = 0; i < len; i++) {
3802
+ result[i] = Math.round(result[i]);
3803
+ }
3804
+ }
3805
+ return result;
3806
+ };
3807
+ if ("conversion" in fn) {
3808
+ wrappedFn.conversion = fn.conversion;
3809
+ }
3810
+ return wrappedFn;
3811
+ }
3812
+ models.forEach(function(fromModel) {
3813
+ convert[fromModel] = {};
3814
+ Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels });
3815
+ Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels });
3816
+ var routes = route(fromModel);
3817
+ var routeModels = Object.keys(routes);
3818
+ routeModels.forEach(function(toModel) {
3819
+ var fn = routes[toModel];
3820
+ convert[fromModel][toModel] = wrapRounded(fn);
3821
+ convert[fromModel][toModel].raw = wrapRaw(fn);
3822
+ });
3823
+ });
3824
+ module.exports = convert;
3825
+ }
3826
+ });
3827
+
3828
+ // ../../node_modules/ansi-styles/index.js
3829
+ var require_ansi_styles = __commonJS({
3830
+ "../../node_modules/ansi-styles/index.js"(exports, module) {
3831
+ "use strict";
3832
+ var colorConvert = require_color_convert();
3833
+ var wrapAnsi16 = (fn, offset) => function() {
3834
+ const code = fn.apply(colorConvert, arguments);
3835
+ return `\x1B[${code + offset}m`;
3836
+ };
3837
+ var wrapAnsi256 = (fn, offset) => function() {
3838
+ const code = fn.apply(colorConvert, arguments);
3839
+ return `\x1B[${38 + offset};5;${code}m`;
3840
+ };
3841
+ var wrapAnsi16m = (fn, offset) => function() {
3842
+ const rgb = fn.apply(colorConvert, arguments);
3843
+ return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
3844
+ };
3845
+ function assembleStyles() {
3846
+ const codes = /* @__PURE__ */ new Map();
3847
+ const styles = {
3848
+ modifier: {
3849
+ reset: [0, 0],
3850
+ // 21 isn't widely supported and 22 does the same thing
3851
+ bold: [1, 22],
3852
+ dim: [2, 22],
3853
+ italic: [3, 23],
3854
+ underline: [4, 24],
3855
+ inverse: [7, 27],
3856
+ hidden: [8, 28],
3857
+ strikethrough: [9, 29]
3858
+ },
3859
+ color: {
3860
+ black: [30, 39],
3861
+ red: [31, 39],
3862
+ green: [32, 39],
3863
+ yellow: [33, 39],
3864
+ blue: [34, 39],
3865
+ magenta: [35, 39],
3866
+ cyan: [36, 39],
3867
+ white: [37, 39],
3868
+ gray: [90, 39],
3869
+ // Bright color
3870
+ redBright: [91, 39],
3871
+ greenBright: [92, 39],
3872
+ yellowBright: [93, 39],
3873
+ blueBright: [94, 39],
3874
+ magentaBright: [95, 39],
3875
+ cyanBright: [96, 39],
3876
+ whiteBright: [97, 39]
3877
+ },
3878
+ bgColor: {
3879
+ bgBlack: [40, 49],
3880
+ bgRed: [41, 49],
3881
+ bgGreen: [42, 49],
3882
+ bgYellow: [43, 49],
3883
+ bgBlue: [44, 49],
3884
+ bgMagenta: [45, 49],
3885
+ bgCyan: [46, 49],
3886
+ bgWhite: [47, 49],
3887
+ // Bright color
3888
+ bgBlackBright: [100, 49],
3889
+ bgRedBright: [101, 49],
3890
+ bgGreenBright: [102, 49],
3891
+ bgYellowBright: [103, 49],
3892
+ bgBlueBright: [104, 49],
3893
+ bgMagentaBright: [105, 49],
3894
+ bgCyanBright: [106, 49],
3895
+ bgWhiteBright: [107, 49]
3896
+ }
3897
+ };
3898
+ styles.color.grey = styles.color.gray;
3899
+ for (const groupName of Object.keys(styles)) {
3900
+ const group = styles[groupName];
3901
+ for (const styleName of Object.keys(group)) {
3902
+ const style = group[styleName];
3903
+ styles[styleName] = {
3904
+ open: `\x1B[${style[0]}m`,
3905
+ close: `\x1B[${style[1]}m`
3906
+ };
3907
+ group[styleName] = styles[styleName];
3908
+ codes.set(style[0], style[1]);
3909
+ }
3910
+ Object.defineProperty(styles, groupName, {
3911
+ value: group,
3912
+ enumerable: false
3913
+ });
3914
+ Object.defineProperty(styles, "codes", {
3915
+ value: codes,
3916
+ enumerable: false
3917
+ });
3918
+ }
3919
+ const ansi2ansi = (n) => n;
3920
+ const rgb2rgb = (r, g, b) => [r, g, b];
3921
+ styles.color.close = "\x1B[39m";
3922
+ styles.bgColor.close = "\x1B[49m";
3923
+ styles.color.ansi = {
3924
+ ansi: wrapAnsi16(ansi2ansi, 0)
3925
+ };
3926
+ styles.color.ansi256 = {
3927
+ ansi256: wrapAnsi256(ansi2ansi, 0)
3928
+ };
3929
+ styles.color.ansi16m = {
3930
+ rgb: wrapAnsi16m(rgb2rgb, 0)
3931
+ };
3932
+ styles.bgColor.ansi = {
3933
+ ansi: wrapAnsi16(ansi2ansi, 10)
3934
+ };
3935
+ styles.bgColor.ansi256 = {
3936
+ ansi256: wrapAnsi256(ansi2ansi, 10)
3937
+ };
3938
+ styles.bgColor.ansi16m = {
3939
+ rgb: wrapAnsi16m(rgb2rgb, 10)
3940
+ };
3941
+ for (let key of Object.keys(colorConvert)) {
3942
+ if (typeof colorConvert[key] !== "object") {
3943
+ continue;
3944
+ }
3945
+ const suite = colorConvert[key];
3946
+ if (key === "ansi16") {
3947
+ key = "ansi";
3948
+ }
3949
+ if ("ansi16" in suite) {
3950
+ styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
3951
+ styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
3952
+ }
3953
+ if ("ansi256" in suite) {
3954
+ styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
3955
+ styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
3956
+ }
3957
+ if ("rgb" in suite) {
3958
+ styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
3959
+ styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
3960
+ }
3961
+ }
3962
+ return styles;
3963
+ }
3964
+ Object.defineProperty(module, "exports", {
3965
+ enumerable: true,
3966
+ get: assembleStyles
3967
+ });
3968
+ }
3969
+ });
3970
+
3971
+ // ../../node_modules/supports-color/node_modules/has-flag/index.js
3972
+ var require_has_flag = __commonJS({
3973
+ "../../node_modules/supports-color/node_modules/has-flag/index.js"(exports, module) {
3974
+ "use strict";
3975
+ module.exports = (flag, argv) => {
3976
+ argv = argv || process.argv;
3977
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3978
+ const pos = argv.indexOf(prefix + flag);
3979
+ const terminatorPos = argv.indexOf("--");
3980
+ return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
3981
+ };
3982
+ }
3983
+ });
3984
+
3985
+ // ../../node_modules/supports-color/index.js
3986
+ var require_supports_color = __commonJS({
3987
+ "../../node_modules/supports-color/index.js"(exports, module) {
3988
+ "use strict";
3989
+ var os = __require("os");
3990
+ var hasFlag = require_has_flag();
3991
+ var env = process.env;
3992
+ var forceColor;
3993
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false")) {
3994
+ forceColor = false;
3995
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3996
+ forceColor = true;
3997
+ }
3998
+ if ("FORCE_COLOR" in env) {
3999
+ forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
4000
+ }
4001
+ function translateLevel(level) {
4002
+ if (level === 0) {
4003
+ return false;
4004
+ }
4005
+ return {
4006
+ level,
4007
+ hasBasic: true,
4008
+ has256: level >= 2,
4009
+ has16m: level >= 3
4010
+ };
4011
+ }
4012
+ function supportsColor(stream) {
4013
+ if (forceColor === false) {
4014
+ return 0;
4015
+ }
4016
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
4017
+ return 3;
4018
+ }
4019
+ if (hasFlag("color=256")) {
4020
+ return 2;
4021
+ }
4022
+ if (stream && !stream.isTTY && forceColor !== true) {
4023
+ return 0;
4024
+ }
4025
+ const min = forceColor ? 1 : 0;
4026
+ if (process.platform === "win32") {
4027
+ const osRelease = os.release().split(".");
4028
+ if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
4029
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
4030
+ }
4031
+ return 1;
4032
+ }
4033
+ if ("CI" in env) {
4034
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
4035
+ return 1;
4036
+ }
4037
+ return min;
4038
+ }
4039
+ if ("TEAMCITY_VERSION" in env) {
4040
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
4041
+ }
4042
+ if (env.COLORTERM === "truecolor") {
4043
+ return 3;
4044
+ }
4045
+ if ("TERM_PROGRAM" in env) {
4046
+ const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
4047
+ switch (env.TERM_PROGRAM) {
4048
+ case "iTerm.app":
4049
+ return version >= 3 ? 3 : 2;
4050
+ case "Apple_Terminal":
4051
+ return 2;
4052
+ }
4053
+ }
4054
+ if (/-256(color)?$/i.test(env.TERM)) {
4055
+ return 2;
4056
+ }
4057
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
4058
+ return 1;
4059
+ }
4060
+ if ("COLORTERM" in env) {
4061
+ return 1;
4062
+ }
4063
+ if (env.TERM === "dumb") {
4064
+ return min;
4065
+ }
4066
+ return min;
4067
+ }
4068
+ function getSupportLevel(stream) {
4069
+ const level = supportsColor(stream);
4070
+ return translateLevel(level);
4071
+ }
4072
+ module.exports = {
4073
+ supportsColor: getSupportLevel,
4074
+ stdout: getSupportLevel(process.stdout),
4075
+ stderr: getSupportLevel(process.stderr)
4076
+ };
4077
+ }
4078
+ });
4079
+
4080
+ // ../../scripts/node_modules/chalk/templates.js
4081
+ var require_templates = __commonJS({
4082
+ "../../scripts/node_modules/chalk/templates.js"(exports, module) {
4083
+ "use strict";
4084
+ var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
4085
+ var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
4086
+ var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
4087
+ var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
4088
+ var ESCAPES = /* @__PURE__ */ new Map([
4089
+ ["n", "\n"],
4090
+ ["r", "\r"],
4091
+ ["t", " "],
4092
+ ["b", "\b"],
4093
+ ["f", "\f"],
4094
+ ["v", "\v"],
4095
+ ["0", "\0"],
4096
+ ["\\", "\\"],
4097
+ ["e", "\x1B"],
4098
+ ["a", "\x07"]
4099
+ ]);
4100
+ function unescape(c) {
4101
+ if (c[0] === "u" && c.length === 5 || c[0] === "x" && c.length === 3) {
4102
+ return String.fromCharCode(parseInt(c.slice(1), 16));
4103
+ }
4104
+ return ESCAPES.get(c) || c;
4105
+ }
4106
+ function parseArguments(name, args) {
4107
+ const results = [];
4108
+ const chunks = args.trim().split(/\s*,\s*/g);
4109
+ let matches;
4110
+ for (const chunk of chunks) {
4111
+ if (!isNaN(chunk)) {
4112
+ results.push(Number(chunk));
4113
+ } else if (matches = chunk.match(STRING_REGEX)) {
4114
+ results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
4115
+ } else {
4116
+ throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
4117
+ }
4118
+ }
4119
+ return results;
4120
+ }
4121
+ function parseStyle(style) {
4122
+ STYLE_REGEX.lastIndex = 0;
4123
+ const results = [];
4124
+ let matches;
4125
+ while ((matches = STYLE_REGEX.exec(style)) !== null) {
4126
+ const name = matches[1];
4127
+ if (matches[2]) {
4128
+ const args = parseArguments(name, matches[2]);
4129
+ results.push([name].concat(args));
4130
+ } else {
4131
+ results.push([name]);
4132
+ }
4133
+ }
4134
+ return results;
4135
+ }
4136
+ function buildStyle(chalk2, styles) {
4137
+ const enabled = {};
4138
+ for (const layer of styles) {
4139
+ for (const style of layer.styles) {
4140
+ enabled[style[0]] = layer.inverse ? null : style.slice(1);
4141
+ }
4142
+ }
4143
+ let current = chalk2;
4144
+ for (const styleName of Object.keys(enabled)) {
4145
+ if (Array.isArray(enabled[styleName])) {
4146
+ if (!(styleName in current)) {
4147
+ throw new Error(`Unknown Chalk style: ${styleName}`);
4148
+ }
4149
+ if (enabled[styleName].length > 0) {
4150
+ current = current[styleName].apply(current, enabled[styleName]);
4151
+ } else {
4152
+ current = current[styleName];
4153
+ }
4154
+ }
4155
+ }
4156
+ return current;
4157
+ }
4158
+ module.exports = (chalk2, tmp) => {
4159
+ const styles = [];
4160
+ const chunks = [];
4161
+ let chunk = [];
4162
+ tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
4163
+ if (escapeChar) {
4164
+ chunk.push(unescape(escapeChar));
4165
+ } else if (style) {
4166
+ const str = chunk.join("");
4167
+ chunk = [];
4168
+ chunks.push(styles.length === 0 ? str : buildStyle(chalk2, styles)(str));
4169
+ styles.push({ inverse, styles: parseStyle(style) });
4170
+ } else if (close) {
4171
+ if (styles.length === 0) {
4172
+ throw new Error("Found extraneous } in Chalk template literal");
4173
+ }
4174
+ chunks.push(buildStyle(chalk2, styles)(chunk.join("")));
4175
+ chunk = [];
4176
+ styles.pop();
4177
+ } else {
4178
+ chunk.push(chr);
4179
+ }
4180
+ });
4181
+ chunks.push(chunk.join(""));
4182
+ if (styles.length > 0) {
4183
+ const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? "" : "s"} (\`}\`)`;
4184
+ throw new Error(errMsg);
4185
+ }
4186
+ return chunks.join("");
4187
+ };
4188
+ }
4189
+ });
4190
+
4191
+ // ../../scripts/node_modules/chalk/index.js
4192
+ var require_chalk = __commonJS({
4193
+ "../../scripts/node_modules/chalk/index.js"(exports, module) {
4194
+ "use strict";
4195
+ var escapeStringRegexp = require_escape_string_regexp();
4196
+ var ansiStyles = require_ansi_styles();
4197
+ var stdoutColor = require_supports_color().stdout;
4198
+ var template = require_templates();
4199
+ var isSimpleWindowsTerm = process.platform === "win32" && !(process.env.TERM || "").toLowerCase().startsWith("xterm");
4200
+ var levelMapping = ["ansi", "ansi", "ansi256", "ansi16m"];
4201
+ var skipModels = /* @__PURE__ */ new Set(["gray"]);
4202
+ var styles = /* @__PURE__ */ Object.create(null);
4203
+ function applyOptions(obj, options) {
4204
+ options = options || {};
4205
+ const scLevel = stdoutColor ? stdoutColor.level : 0;
4206
+ obj.level = options.level === void 0 ? scLevel : options.level;
4207
+ obj.enabled = "enabled" in options ? options.enabled : obj.level > 0;
4208
+ }
4209
+ function Chalk(options) {
4210
+ if (!this || !(this instanceof Chalk) || this.template) {
4211
+ const chalk2 = {};
4212
+ applyOptions(chalk2, options);
4213
+ chalk2.template = function() {
4214
+ const args = [].slice.call(arguments);
4215
+ return chalkTag.apply(null, [chalk2.template].concat(args));
4216
+ };
4217
+ Object.setPrototypeOf(chalk2, Chalk.prototype);
4218
+ Object.setPrototypeOf(chalk2.template, chalk2);
4219
+ chalk2.template.constructor = Chalk;
4220
+ return chalk2.template;
4221
+ }
4222
+ applyOptions(this, options);
4223
+ }
4224
+ if (isSimpleWindowsTerm) {
4225
+ ansiStyles.blue.open = "\x1B[94m";
4226
+ }
4227
+ for (const key of Object.keys(ansiStyles)) {
4228
+ ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), "g");
4229
+ styles[key] = {
4230
+ get() {
4231
+ const codes = ansiStyles[key];
4232
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
4233
+ }
4234
+ };
4235
+ }
4236
+ styles.visible = {
4237
+ get() {
4238
+ return build.call(this, this._styles || [], true, "visible");
4239
+ }
4240
+ };
4241
+ ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), "g");
4242
+ for (const model of Object.keys(ansiStyles.color.ansi)) {
4243
+ if (skipModels.has(model)) {
4244
+ continue;
4245
+ }
4246
+ styles[model] = {
4247
+ get() {
4248
+ const level = this.level;
4249
+ return function() {
4250
+ const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
4251
+ const codes = {
4252
+ open,
4253
+ close: ansiStyles.color.close,
4254
+ closeRe: ansiStyles.color.closeRe
4255
+ };
4256
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
4257
+ };
4258
+ }
4259
+ };
4260
+ }
4261
+ ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), "g");
4262
+ for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
4263
+ if (skipModels.has(model)) {
4264
+ continue;
4265
+ }
4266
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
4267
+ styles[bgModel] = {
4268
+ get() {
4269
+ const level = this.level;
4270
+ return function() {
4271
+ const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
4272
+ const codes = {
4273
+ open,
4274
+ close: ansiStyles.bgColor.close,
4275
+ closeRe: ansiStyles.bgColor.closeRe
4276
+ };
4277
+ return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
4278
+ };
4279
+ }
4280
+ };
4281
+ }
4282
+ var proto = Object.defineProperties(() => {
4283
+ }, styles);
4284
+ function build(_styles, _empty, key) {
4285
+ const builder = function() {
4286
+ return applyStyle.apply(builder, arguments);
4287
+ };
4288
+ builder._styles = _styles;
4289
+ builder._empty = _empty;
4290
+ const self = this;
4291
+ Object.defineProperty(builder, "level", {
4292
+ enumerable: true,
4293
+ get() {
4294
+ return self.level;
4295
+ },
4296
+ set(level) {
4297
+ self.level = level;
4298
+ }
4299
+ });
4300
+ Object.defineProperty(builder, "enabled", {
4301
+ enumerable: true,
4302
+ get() {
4303
+ return self.enabled;
4304
+ },
4305
+ set(enabled) {
4306
+ self.enabled = enabled;
4307
+ }
4308
+ });
4309
+ builder.hasGrey = this.hasGrey || key === "gray" || key === "grey";
4310
+ builder.__proto__ = proto;
4311
+ return builder;
4312
+ }
4313
+ function applyStyle() {
4314
+ const args = arguments;
4315
+ const argsLen = args.length;
4316
+ let str = String(arguments[0]);
4317
+ if (argsLen === 0) {
4318
+ return "";
4319
+ }
4320
+ if (argsLen > 1) {
4321
+ for (let a = 1; a < argsLen; a++) {
4322
+ str += " " + args[a];
4323
+ }
4324
+ }
4325
+ if (!this.enabled || this.level <= 0 || !str) {
4326
+ return this._empty ? "" : str;
4327
+ }
4328
+ const originalDim = ansiStyles.dim.open;
4329
+ if (isSimpleWindowsTerm && this.hasGrey) {
4330
+ ansiStyles.dim.open = "";
4331
+ }
4332
+ for (const code of this._styles.slice().reverse()) {
4333
+ str = code.open + str.replace(code.closeRe, code.open) + code.close;
4334
+ str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
4335
+ }
4336
+ ansiStyles.dim.open = originalDim;
4337
+ return str;
4338
+ }
4339
+ function chalkTag(chalk2, strings) {
4340
+ if (!Array.isArray(strings)) {
4341
+ return [].slice.call(arguments, 1).join(" ");
4342
+ }
4343
+ const args = [].slice.call(arguments, 2);
4344
+ const parts = [strings.raw[0]];
4345
+ for (let i = 1; i < strings.length; i++) {
4346
+ parts.push(String(args[i - 1]).replace(/[{}\\]/g, "\\$&"));
4347
+ parts.push(String(strings.raw[i]));
4348
+ }
4349
+ return template(chalk2, parts.join(""));
4350
+ }
4351
+ Object.defineProperties(Chalk.prototype, styles);
4352
+ module.exports = Chalk();
4353
+ module.exports.supportsColor = stdoutColor;
4354
+ module.exports.default = module.exports;
4355
+ }
4356
+ });
4357
+
4358
+ // ../../node_modules/@magda/esm-utils/dist/esmUtils.js
4359
+ import { createRequire } from "module";
4360
+ function callsites() {
4361
+ const _prepareStackTrace = Error.prepareStackTrace;
4362
+ try {
4363
+ let result = [];
4364
+ Error.prepareStackTrace = (_, callSites) => {
4365
+ const callSitesWithoutCurrent = callSites.slice(1);
4366
+ result = callSitesWithoutCurrent;
4367
+ return callSitesWithoutCurrent;
4368
+ };
4369
+ new Error().stack;
4370
+ return result;
4371
+ } finally {
4372
+ Error.prepareStackTrace = _prepareStackTrace;
4373
+ }
4374
+ }
4375
+ function callerCallsite({ depth = 0 } = {}) {
4376
+ const callers = [];
4377
+ const callerFileSet = /* @__PURE__ */ new Set();
4378
+ for (const callsite of callsites()) {
4379
+ const fileName = callsite.getFileName();
4380
+ const hasReceiver = callsite.getTypeName() !== null && fileName !== null;
4381
+ if (!callerFileSet.has(fileName)) {
4382
+ callerFileSet.add(fileName);
4383
+ callers.unshift(callsite);
4384
+ }
4385
+ if (hasReceiver) {
4386
+ return callers[depth];
4387
+ }
4388
+ }
4389
+ }
4390
+ function callerpath({ depth = 0 } = {}) {
4391
+ const callsite = callerCallsite({ depth });
4392
+ return callsite && callsite.getFileName();
4393
+ }
4394
+ function require2(id) {
4395
+ const requireFrom = createRequire(callerpath({ depth: 1 }));
4396
+ return requireFrom(id);
4397
+ }
4398
+
4399
+ // ../../node_modules/commander/esm.mjs
4400
+ var import_index = __toESM(require_commander(), 1);
4401
+ var {
4402
+ program,
4403
+ createCommand,
4404
+ createArgument,
4405
+ createOption,
4406
+ CommanderError,
4407
+ InvalidArgumentError,
4408
+ InvalidOptionArgumentError,
4409
+ // deprecated old name
4410
+ Command,
4411
+ Argument,
4412
+ Option,
4413
+ Help
4414
+ } = import_index.default;
4415
+
4416
+ // ../../scripts/org-tree/org-tree-unassign.js
4417
+ var import_chalk = __toESM(require_chalk(), 1);
4418
+
4419
+ // ../../scripts/db/getDBPool.js
4420
+ import pg from "pg";
4421
+
4422
+ // ../../scripts/db/getDBConfig.js
4423
+ function getDBConfig() {
4424
+ const {
4425
+ POSTGRES_HOST: host,
4426
+ POSTGRES_DB: database,
4427
+ POSTGRES_USER: user,
4428
+ POSTGRES_PASSWORD: password,
4429
+ POSTGRES_PORT: port
4430
+ } = process.env;
4431
+ return {
4432
+ host: host ? host : "localhost",
4433
+ database: database ? database : "auth",
4434
+ port: port ? port : 5432,
4435
+ user: user ? user : "postgres",
4436
+ password: password ? password : ""
4437
+ };
4438
+ }
4439
+
4440
+ // ../../scripts/db/getDBPool.js
4441
+ var pool = new pg.Pool(getDBConfig());
4442
+ pool.on("error", function(err, client) {
4443
+ console.error("DB Pool Error: ", err.message, err.stack);
4444
+ });
4445
+ function getDBPool() {
4446
+ return pool;
4447
+ }
4448
+ var getDBPool_default = getDBPool;
4449
+
4450
+ // ../../magda-typescript-common/dist/util/isUuid.js
4451
+ var uuidRegEx = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4452
+ var isUuid = (id) => typeof id === "string" && uuidRegEx.test(id);
4453
+ var isUuid_default = isUuid;
4454
+
4455
+ // ../../scripts/org-tree/getUserIdFromNameOrId.js
4456
+ async function getUserIdFromNameOrId(nameOrId, pool2) {
4457
+ if (isUuid_default(nameOrId)) {
4458
+ return nameOrId;
4459
+ } else {
4460
+ const result = await pool2.query(
4461
+ `SELECT "id" FROM "users" WHERE "displayName" = $1`,
4462
+ [nameOrId]
4463
+ );
4464
+ if (!result || !result.rows || !result.rows.length) {
4465
+ throw new Error(`Cannot locate node record with name: ${nameOrId}`);
4466
+ }
4467
+ return result.rows[0].id;
4468
+ }
4469
+ }
4470
+ var getUserIdFromNameOrId_default = getUserIdFromNameOrId;
4471
+
4472
+ // ../../scripts/org-tree/org-tree-unassign.js
4473
+ var pkg = require2("../package.json");
4474
+ program.description("Remove the specified user to from any org unit.").argument("<userNameOrId>", "user name or id").version(pkg.version).action(async (userNameOrId) => {
4475
+ try {
4476
+ if (process.argv.slice(2).length < 1) {
4477
+ program.help();
4478
+ }
4479
+ userNameOrId = userNameOrId ? userNameOrId.trim() : "";
4480
+ if (userNameOrId === "")
4481
+ throw new Error("User Name or Id can't be empty!");
4482
+ const pool2 = getDBPool_default();
4483
+ const userId = await getUserIdFromNameOrId_default(userNameOrId, pool2);
4484
+ await pool2.query(
4485
+ `UPDATE "users" SET "orgUnitId" = NULL WHERE "id" = $1`,
4486
+ [userId]
4487
+ );
4488
+ console.log(
4489
+ import_chalk.default.green(`The user (id: ${userId}) has been unassigned.`)
4490
+ );
4491
+ } catch (e) {
4492
+ console.error(import_chalk.default.red(`Error: ${e}`));
4493
+ }
4494
+ process.exit(0);
4495
+ }).parse(process.argv);