runcc 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2505 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import { createRequire } from "node:module";
4
+ var __create = Object.create;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __toESM = (mod, isNodeMode, target) => {
10
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
11
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
12
+ for (let key of __getOwnPropNames(mod))
13
+ if (!__hasOwnProp.call(to, key))
14
+ __defProp(to, key, {
15
+ get: () => mod[key],
16
+ enumerable: true
17
+ });
18
+ return to;
19
+ };
20
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
21
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
22
+
23
+ // node_modules/commander/lib/error.js
24
+ var require_error = __commonJS((exports) => {
25
+ class CommanderError extends Error {
26
+ constructor(exitCode, code, message) {
27
+ super(message);
28
+ Error.captureStackTrace(this, this.constructor);
29
+ this.name = this.constructor.name;
30
+ this.code = code;
31
+ this.exitCode = exitCode;
32
+ this.nestedError = undefined;
33
+ }
34
+ }
35
+
36
+ class InvalidArgumentError extends CommanderError {
37
+ constructor(message) {
38
+ super(1, "commander.invalidArgument", message);
39
+ Error.captureStackTrace(this, this.constructor);
40
+ this.name = this.constructor.name;
41
+ }
42
+ }
43
+ exports.CommanderError = CommanderError;
44
+ exports.InvalidArgumentError = InvalidArgumentError;
45
+ });
46
+
47
+ // node_modules/commander/lib/argument.js
48
+ var require_argument = __commonJS((exports) => {
49
+ var { InvalidArgumentError } = require_error();
50
+
51
+ class Argument {
52
+ constructor(name, description) {
53
+ this.description = description || "";
54
+ this.variadic = false;
55
+ this.parseArg = undefined;
56
+ this.defaultValue = undefined;
57
+ this.defaultValueDescription = undefined;
58
+ this.argChoices = undefined;
59
+ switch (name[0]) {
60
+ case "<":
61
+ this.required = true;
62
+ this._name = name.slice(1, -1);
63
+ break;
64
+ case "[":
65
+ this.required = false;
66
+ this._name = name.slice(1, -1);
67
+ break;
68
+ default:
69
+ this.required = true;
70
+ this._name = name;
71
+ break;
72
+ }
73
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
74
+ this.variadic = true;
75
+ this._name = this._name.slice(0, -3);
76
+ }
77
+ }
78
+ name() {
79
+ return this._name;
80
+ }
81
+ _concatValue(value, previous) {
82
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
83
+ return [value];
84
+ }
85
+ return previous.concat(value);
86
+ }
87
+ default(value, description) {
88
+ this.defaultValue = value;
89
+ this.defaultValueDescription = description;
90
+ return this;
91
+ }
92
+ argParser(fn) {
93
+ this.parseArg = fn;
94
+ return this;
95
+ }
96
+ choices(values) {
97
+ this.argChoices = values.slice();
98
+ this.parseArg = (arg, previous) => {
99
+ if (!this.argChoices.includes(arg)) {
100
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
101
+ }
102
+ if (this.variadic) {
103
+ return this._concatValue(arg, previous);
104
+ }
105
+ return arg;
106
+ };
107
+ return this;
108
+ }
109
+ argRequired() {
110
+ this.required = true;
111
+ return this;
112
+ }
113
+ argOptional() {
114
+ this.required = false;
115
+ return this;
116
+ }
117
+ }
118
+ function humanReadableArgName(arg) {
119
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
120
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
121
+ }
122
+ exports.Argument = Argument;
123
+ exports.humanReadableArgName = humanReadableArgName;
124
+ });
125
+
126
+ // node_modules/commander/lib/help.js
127
+ var require_help = __commonJS((exports) => {
128
+ var { humanReadableArgName } = require_argument();
129
+
130
+ class Help {
131
+ constructor() {
132
+ this.helpWidth = undefined;
133
+ this.sortSubcommands = false;
134
+ this.sortOptions = false;
135
+ this.showGlobalOptions = false;
136
+ }
137
+ visibleCommands(cmd) {
138
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
139
+ const helpCommand = cmd._getHelpCommand();
140
+ if (helpCommand && !helpCommand._hidden) {
141
+ visibleCommands.push(helpCommand);
142
+ }
143
+ if (this.sortSubcommands) {
144
+ visibleCommands.sort((a, b) => {
145
+ return a.name().localeCompare(b.name());
146
+ });
147
+ }
148
+ return visibleCommands;
149
+ }
150
+ compareOptions(a, b) {
151
+ const getSortKey = (option) => {
152
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
153
+ };
154
+ return getSortKey(a).localeCompare(getSortKey(b));
155
+ }
156
+ visibleOptions(cmd) {
157
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
158
+ const helpOption = cmd._getHelpOption();
159
+ if (helpOption && !helpOption.hidden) {
160
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
161
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
162
+ if (!removeShort && !removeLong) {
163
+ visibleOptions.push(helpOption);
164
+ } else if (helpOption.long && !removeLong) {
165
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
166
+ } else if (helpOption.short && !removeShort) {
167
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
168
+ }
169
+ }
170
+ if (this.sortOptions) {
171
+ visibleOptions.sort(this.compareOptions);
172
+ }
173
+ return visibleOptions;
174
+ }
175
+ visibleGlobalOptions(cmd) {
176
+ if (!this.showGlobalOptions)
177
+ return [];
178
+ const globalOptions = [];
179
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
180
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
181
+ globalOptions.push(...visibleOptions);
182
+ }
183
+ if (this.sortOptions) {
184
+ globalOptions.sort(this.compareOptions);
185
+ }
186
+ return globalOptions;
187
+ }
188
+ visibleArguments(cmd) {
189
+ if (cmd._argsDescription) {
190
+ cmd.registeredArguments.forEach((argument) => {
191
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
192
+ });
193
+ }
194
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
195
+ return cmd.registeredArguments;
196
+ }
197
+ return [];
198
+ }
199
+ subcommandTerm(cmd) {
200
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
201
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
202
+ }
203
+ optionTerm(option) {
204
+ return option.flags;
205
+ }
206
+ argumentTerm(argument) {
207
+ return argument.name();
208
+ }
209
+ longestSubcommandTermLength(cmd, helper) {
210
+ return helper.visibleCommands(cmd).reduce((max, command) => {
211
+ return Math.max(max, helper.subcommandTerm(command).length);
212
+ }, 0);
213
+ }
214
+ longestOptionTermLength(cmd, helper) {
215
+ return helper.visibleOptions(cmd).reduce((max, option) => {
216
+ return Math.max(max, helper.optionTerm(option).length);
217
+ }, 0);
218
+ }
219
+ longestGlobalOptionTermLength(cmd, helper) {
220
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
221
+ return Math.max(max, helper.optionTerm(option).length);
222
+ }, 0);
223
+ }
224
+ longestArgumentTermLength(cmd, helper) {
225
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
226
+ return Math.max(max, helper.argumentTerm(argument).length);
227
+ }, 0);
228
+ }
229
+ commandUsage(cmd) {
230
+ let cmdName = cmd._name;
231
+ if (cmd._aliases[0]) {
232
+ cmdName = cmdName + "|" + cmd._aliases[0];
233
+ }
234
+ let ancestorCmdNames = "";
235
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
236
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
237
+ }
238
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
239
+ }
240
+ commandDescription(cmd) {
241
+ return cmd.description();
242
+ }
243
+ subcommandDescription(cmd) {
244
+ return cmd.summary() || cmd.description();
245
+ }
246
+ optionDescription(option) {
247
+ const extraInfo = [];
248
+ if (option.argChoices) {
249
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
250
+ }
251
+ if (option.defaultValue !== undefined) {
252
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
253
+ if (showDefault) {
254
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
255
+ }
256
+ }
257
+ if (option.presetArg !== undefined && option.optional) {
258
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
259
+ }
260
+ if (option.envVar !== undefined) {
261
+ extraInfo.push(`env: ${option.envVar}`);
262
+ }
263
+ if (extraInfo.length > 0) {
264
+ return `${option.description} (${extraInfo.join(", ")})`;
265
+ }
266
+ return option.description;
267
+ }
268
+ argumentDescription(argument) {
269
+ const extraInfo = [];
270
+ if (argument.argChoices) {
271
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
272
+ }
273
+ if (argument.defaultValue !== undefined) {
274
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
275
+ }
276
+ if (extraInfo.length > 0) {
277
+ const extraDescripton = `(${extraInfo.join(", ")})`;
278
+ if (argument.description) {
279
+ return `${argument.description} ${extraDescripton}`;
280
+ }
281
+ return extraDescripton;
282
+ }
283
+ return argument.description;
284
+ }
285
+ formatHelp(cmd, helper) {
286
+ const termWidth = helper.padWidth(cmd, helper);
287
+ const helpWidth = helper.helpWidth || 80;
288
+ const itemIndentWidth = 2;
289
+ const itemSeparatorWidth = 2;
290
+ function formatItem(term, description) {
291
+ if (description) {
292
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
293
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
294
+ }
295
+ return term;
296
+ }
297
+ function formatList(textArray) {
298
+ return textArray.join(`
299
+ `).replace(/^/gm, " ".repeat(itemIndentWidth));
300
+ }
301
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
302
+ const commandDescription = helper.commandDescription(cmd);
303
+ if (commandDescription.length > 0) {
304
+ output = output.concat([
305
+ helper.wrap(commandDescription, helpWidth, 0),
306
+ ""
307
+ ]);
308
+ }
309
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
310
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
311
+ });
312
+ if (argumentList.length > 0) {
313
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
314
+ }
315
+ const optionList = helper.visibleOptions(cmd).map((option) => {
316
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
317
+ });
318
+ if (optionList.length > 0) {
319
+ output = output.concat(["Options:", formatList(optionList), ""]);
320
+ }
321
+ if (this.showGlobalOptions) {
322
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
323
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
324
+ });
325
+ if (globalOptionList.length > 0) {
326
+ output = output.concat([
327
+ "Global Options:",
328
+ formatList(globalOptionList),
329
+ ""
330
+ ]);
331
+ }
332
+ }
333
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
334
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
335
+ });
336
+ if (commandList.length > 0) {
337
+ output = output.concat(["Commands:", formatList(commandList), ""]);
338
+ }
339
+ return output.join(`
340
+ `);
341
+ }
342
+ padWidth(cmd, helper) {
343
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
344
+ }
345
+ wrap(str, width, indent, minColumnWidth = 40) {
346
+ const indents = " \\f\\t\\v   -    \uFEFF";
347
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
348
+ if (str.match(manualIndent))
349
+ return str;
350
+ const columnWidth = width - indent;
351
+ if (columnWidth < minColumnWidth)
352
+ return str;
353
+ const leadingStr = str.slice(0, indent);
354
+ const columnText = str.slice(indent).replace(`\r
355
+ `, `
356
+ `);
357
+ const indentString = " ".repeat(indent);
358
+ const zeroWidthSpace = "​";
359
+ const breaks = `\\s${zeroWidthSpace}`;
360
+ const regex = new RegExp(`
361
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
362
+ const lines = columnText.match(regex) || [];
363
+ return leadingStr + lines.map((line, i) => {
364
+ if (line === `
365
+ `)
366
+ return "";
367
+ return (i > 0 ? indentString : "") + line.trimEnd();
368
+ }).join(`
369
+ `);
370
+ }
371
+ }
372
+ exports.Help = Help;
373
+ });
374
+
375
+ // node_modules/commander/lib/option.js
376
+ var require_option = __commonJS((exports) => {
377
+ var { InvalidArgumentError } = require_error();
378
+
379
+ class Option {
380
+ constructor(flags, description) {
381
+ this.flags = flags;
382
+ this.description = description || "";
383
+ this.required = flags.includes("<");
384
+ this.optional = flags.includes("[");
385
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
386
+ this.mandatory = false;
387
+ const optionFlags = splitOptionFlags(flags);
388
+ this.short = optionFlags.shortFlag;
389
+ this.long = optionFlags.longFlag;
390
+ this.negate = false;
391
+ if (this.long) {
392
+ this.negate = this.long.startsWith("--no-");
393
+ }
394
+ this.defaultValue = undefined;
395
+ this.defaultValueDescription = undefined;
396
+ this.presetArg = undefined;
397
+ this.envVar = undefined;
398
+ this.parseArg = undefined;
399
+ this.hidden = false;
400
+ this.argChoices = undefined;
401
+ this.conflictsWith = [];
402
+ this.implied = undefined;
403
+ }
404
+ default(value, description) {
405
+ this.defaultValue = value;
406
+ this.defaultValueDescription = description;
407
+ return this;
408
+ }
409
+ preset(arg) {
410
+ this.presetArg = arg;
411
+ return this;
412
+ }
413
+ conflicts(names) {
414
+ this.conflictsWith = this.conflictsWith.concat(names);
415
+ return this;
416
+ }
417
+ implies(impliedOptionValues) {
418
+ let newImplied = impliedOptionValues;
419
+ if (typeof impliedOptionValues === "string") {
420
+ newImplied = { [impliedOptionValues]: true };
421
+ }
422
+ this.implied = Object.assign(this.implied || {}, newImplied);
423
+ return this;
424
+ }
425
+ env(name) {
426
+ this.envVar = name;
427
+ return this;
428
+ }
429
+ argParser(fn) {
430
+ this.parseArg = fn;
431
+ return this;
432
+ }
433
+ makeOptionMandatory(mandatory = true) {
434
+ this.mandatory = !!mandatory;
435
+ return this;
436
+ }
437
+ hideHelp(hide = true) {
438
+ this.hidden = !!hide;
439
+ return this;
440
+ }
441
+ _concatValue(value, previous) {
442
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
443
+ return [value];
444
+ }
445
+ return previous.concat(value);
446
+ }
447
+ choices(values) {
448
+ this.argChoices = values.slice();
449
+ this.parseArg = (arg, previous) => {
450
+ if (!this.argChoices.includes(arg)) {
451
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
452
+ }
453
+ if (this.variadic) {
454
+ return this._concatValue(arg, previous);
455
+ }
456
+ return arg;
457
+ };
458
+ return this;
459
+ }
460
+ name() {
461
+ if (this.long) {
462
+ return this.long.replace(/^--/, "");
463
+ }
464
+ return this.short.replace(/^-/, "");
465
+ }
466
+ attributeName() {
467
+ return camelcase(this.name().replace(/^no-/, ""));
468
+ }
469
+ is(arg) {
470
+ return this.short === arg || this.long === arg;
471
+ }
472
+ isBoolean() {
473
+ return !this.required && !this.optional && !this.negate;
474
+ }
475
+ }
476
+
477
+ class DualOptions {
478
+ constructor(options) {
479
+ this.positiveOptions = new Map;
480
+ this.negativeOptions = new Map;
481
+ this.dualOptions = new Set;
482
+ options.forEach((option) => {
483
+ if (option.negate) {
484
+ this.negativeOptions.set(option.attributeName(), option);
485
+ } else {
486
+ this.positiveOptions.set(option.attributeName(), option);
487
+ }
488
+ });
489
+ this.negativeOptions.forEach((value, key) => {
490
+ if (this.positiveOptions.has(key)) {
491
+ this.dualOptions.add(key);
492
+ }
493
+ });
494
+ }
495
+ valueFromOption(value, option) {
496
+ const optionKey = option.attributeName();
497
+ if (!this.dualOptions.has(optionKey))
498
+ return true;
499
+ const preset = this.negativeOptions.get(optionKey).presetArg;
500
+ const negativeValue = preset !== undefined ? preset : false;
501
+ return option.negate === (negativeValue === value);
502
+ }
503
+ }
504
+ function camelcase(str) {
505
+ return str.split("-").reduce((str2, word) => {
506
+ return str2 + word[0].toUpperCase() + word.slice(1);
507
+ });
508
+ }
509
+ function splitOptionFlags(flags) {
510
+ let shortFlag;
511
+ let longFlag;
512
+ const flagParts = flags.split(/[ |,]+/);
513
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
514
+ shortFlag = flagParts.shift();
515
+ longFlag = flagParts.shift();
516
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
517
+ shortFlag = longFlag;
518
+ longFlag = undefined;
519
+ }
520
+ return { shortFlag, longFlag };
521
+ }
522
+ exports.Option = Option;
523
+ exports.DualOptions = DualOptions;
524
+ });
525
+
526
+ // node_modules/commander/lib/suggestSimilar.js
527
+ var require_suggestSimilar = __commonJS((exports) => {
528
+ var maxDistance = 3;
529
+ function editDistance(a, b) {
530
+ if (Math.abs(a.length - b.length) > maxDistance)
531
+ return Math.max(a.length, b.length);
532
+ const d = [];
533
+ for (let i = 0;i <= a.length; i++) {
534
+ d[i] = [i];
535
+ }
536
+ for (let j = 0;j <= b.length; j++) {
537
+ d[0][j] = j;
538
+ }
539
+ for (let j = 1;j <= b.length; j++) {
540
+ for (let i = 1;i <= a.length; i++) {
541
+ let cost = 1;
542
+ if (a[i - 1] === b[j - 1]) {
543
+ cost = 0;
544
+ } else {
545
+ cost = 1;
546
+ }
547
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
548
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
549
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
550
+ }
551
+ }
552
+ }
553
+ return d[a.length][b.length];
554
+ }
555
+ function suggestSimilar(word, candidates) {
556
+ if (!candidates || candidates.length === 0)
557
+ return "";
558
+ candidates = Array.from(new Set(candidates));
559
+ const searchingOptions = word.startsWith("--");
560
+ if (searchingOptions) {
561
+ word = word.slice(2);
562
+ candidates = candidates.map((candidate) => candidate.slice(2));
563
+ }
564
+ let similar = [];
565
+ let bestDistance = maxDistance;
566
+ const minSimilarity = 0.4;
567
+ candidates.forEach((candidate) => {
568
+ if (candidate.length <= 1)
569
+ return;
570
+ const distance = editDistance(word, candidate);
571
+ const length = Math.max(word.length, candidate.length);
572
+ const similarity = (length - distance) / length;
573
+ if (similarity > minSimilarity) {
574
+ if (distance < bestDistance) {
575
+ bestDistance = distance;
576
+ similar = [candidate];
577
+ } else if (distance === bestDistance) {
578
+ similar.push(candidate);
579
+ }
580
+ }
581
+ });
582
+ similar.sort((a, b) => a.localeCompare(b));
583
+ if (searchingOptions) {
584
+ similar = similar.map((candidate) => `--${candidate}`);
585
+ }
586
+ if (similar.length > 1) {
587
+ return `
588
+ (Did you mean one of ${similar.join(", ")}?)`;
589
+ }
590
+ if (similar.length === 1) {
591
+ return `
592
+ (Did you mean ${similar[0]}?)`;
593
+ }
594
+ return "";
595
+ }
596
+ exports.suggestSimilar = suggestSimilar;
597
+ });
598
+
599
+ // node_modules/commander/lib/command.js
600
+ var require_command = __commonJS((exports) => {
601
+ var EventEmitter = __require("node:events").EventEmitter;
602
+ var childProcess = __require("node:child_process");
603
+ var path = __require("node:path");
604
+ var fs = __require("node:fs");
605
+ var process2 = __require("node:process");
606
+ var { Argument, humanReadableArgName } = require_argument();
607
+ var { CommanderError } = require_error();
608
+ var { Help } = require_help();
609
+ var { Option, DualOptions } = require_option();
610
+ var { suggestSimilar } = require_suggestSimilar();
611
+
612
+ class Command extends EventEmitter {
613
+ constructor(name) {
614
+ super();
615
+ this.commands = [];
616
+ this.options = [];
617
+ this.parent = null;
618
+ this._allowUnknownOption = false;
619
+ this._allowExcessArguments = true;
620
+ this.registeredArguments = [];
621
+ this._args = this.registeredArguments;
622
+ this.args = [];
623
+ this.rawArgs = [];
624
+ this.processedArgs = [];
625
+ this._scriptPath = null;
626
+ this._name = name || "";
627
+ this._optionValues = {};
628
+ this._optionValueSources = {};
629
+ this._storeOptionsAsProperties = false;
630
+ this._actionHandler = null;
631
+ this._executableHandler = false;
632
+ this._executableFile = null;
633
+ this._executableDir = null;
634
+ this._defaultCommandName = null;
635
+ this._exitCallback = null;
636
+ this._aliases = [];
637
+ this._combineFlagAndOptionalValue = true;
638
+ this._description = "";
639
+ this._summary = "";
640
+ this._argsDescription = undefined;
641
+ this._enablePositionalOptions = false;
642
+ this._passThroughOptions = false;
643
+ this._lifeCycleHooks = {};
644
+ this._showHelpAfterError = false;
645
+ this._showSuggestionAfterError = true;
646
+ this._outputConfiguration = {
647
+ writeOut: (str) => process2.stdout.write(str),
648
+ writeErr: (str) => process2.stderr.write(str),
649
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
650
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
651
+ outputError: (str, write) => write(str)
652
+ };
653
+ this._hidden = false;
654
+ this._helpOption = undefined;
655
+ this._addImplicitHelpCommand = undefined;
656
+ this._helpCommand = undefined;
657
+ this._helpConfiguration = {};
658
+ }
659
+ copyInheritedSettings(sourceCommand) {
660
+ this._outputConfiguration = sourceCommand._outputConfiguration;
661
+ this._helpOption = sourceCommand._helpOption;
662
+ this._helpCommand = sourceCommand._helpCommand;
663
+ this._helpConfiguration = sourceCommand._helpConfiguration;
664
+ this._exitCallback = sourceCommand._exitCallback;
665
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
666
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
667
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
668
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
669
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
670
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
671
+ return this;
672
+ }
673
+ _getCommandAndAncestors() {
674
+ const result = [];
675
+ for (let command = this;command; command = command.parent) {
676
+ result.push(command);
677
+ }
678
+ return result;
679
+ }
680
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
681
+ let desc = actionOptsOrExecDesc;
682
+ let opts = execOpts;
683
+ if (typeof desc === "object" && desc !== null) {
684
+ opts = desc;
685
+ desc = null;
686
+ }
687
+ opts = opts || {};
688
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
689
+ const cmd = this.createCommand(name);
690
+ if (desc) {
691
+ cmd.description(desc);
692
+ cmd._executableHandler = true;
693
+ }
694
+ if (opts.isDefault)
695
+ this._defaultCommandName = cmd._name;
696
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
697
+ cmd._executableFile = opts.executableFile || null;
698
+ if (args)
699
+ cmd.arguments(args);
700
+ this._registerCommand(cmd);
701
+ cmd.parent = this;
702
+ cmd.copyInheritedSettings(this);
703
+ if (desc)
704
+ return this;
705
+ return cmd;
706
+ }
707
+ createCommand(name) {
708
+ return new Command(name);
709
+ }
710
+ createHelp() {
711
+ return Object.assign(new Help, this.configureHelp());
712
+ }
713
+ configureHelp(configuration) {
714
+ if (configuration === undefined)
715
+ return this._helpConfiguration;
716
+ this._helpConfiguration = configuration;
717
+ return this;
718
+ }
719
+ configureOutput(configuration) {
720
+ if (configuration === undefined)
721
+ return this._outputConfiguration;
722
+ Object.assign(this._outputConfiguration, configuration);
723
+ return this;
724
+ }
725
+ showHelpAfterError(displayHelp = true) {
726
+ if (typeof displayHelp !== "string")
727
+ displayHelp = !!displayHelp;
728
+ this._showHelpAfterError = displayHelp;
729
+ return this;
730
+ }
731
+ showSuggestionAfterError(displaySuggestion = true) {
732
+ this._showSuggestionAfterError = !!displaySuggestion;
733
+ return this;
734
+ }
735
+ addCommand(cmd, opts) {
736
+ if (!cmd._name) {
737
+ throw new Error(`Command passed to .addCommand() must have a name
738
+ - specify the name in Command constructor or using .name()`);
739
+ }
740
+ opts = opts || {};
741
+ if (opts.isDefault)
742
+ this._defaultCommandName = cmd._name;
743
+ if (opts.noHelp || opts.hidden)
744
+ cmd._hidden = true;
745
+ this._registerCommand(cmd);
746
+ cmd.parent = this;
747
+ cmd._checkForBrokenPassThrough();
748
+ return this;
749
+ }
750
+ createArgument(name, description) {
751
+ return new Argument(name, description);
752
+ }
753
+ argument(name, description, fn, defaultValue) {
754
+ const argument = this.createArgument(name, description);
755
+ if (typeof fn === "function") {
756
+ argument.default(defaultValue).argParser(fn);
757
+ } else {
758
+ argument.default(fn);
759
+ }
760
+ this.addArgument(argument);
761
+ return this;
762
+ }
763
+ arguments(names) {
764
+ names.trim().split(/ +/).forEach((detail) => {
765
+ this.argument(detail);
766
+ });
767
+ return this;
768
+ }
769
+ addArgument(argument) {
770
+ const previousArgument = this.registeredArguments.slice(-1)[0];
771
+ if (previousArgument && previousArgument.variadic) {
772
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
773
+ }
774
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
775
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
776
+ }
777
+ this.registeredArguments.push(argument);
778
+ return this;
779
+ }
780
+ helpCommand(enableOrNameAndArgs, description) {
781
+ if (typeof enableOrNameAndArgs === "boolean") {
782
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
783
+ return this;
784
+ }
785
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
786
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
787
+ const helpDescription = description ?? "display help for command";
788
+ const helpCommand = this.createCommand(helpName);
789
+ helpCommand.helpOption(false);
790
+ if (helpArgs)
791
+ helpCommand.arguments(helpArgs);
792
+ if (helpDescription)
793
+ helpCommand.description(helpDescription);
794
+ this._addImplicitHelpCommand = true;
795
+ this._helpCommand = helpCommand;
796
+ return this;
797
+ }
798
+ addHelpCommand(helpCommand, deprecatedDescription) {
799
+ if (typeof helpCommand !== "object") {
800
+ this.helpCommand(helpCommand, deprecatedDescription);
801
+ return this;
802
+ }
803
+ this._addImplicitHelpCommand = true;
804
+ this._helpCommand = helpCommand;
805
+ return this;
806
+ }
807
+ _getHelpCommand() {
808
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
809
+ if (hasImplicitHelpCommand) {
810
+ if (this._helpCommand === undefined) {
811
+ this.helpCommand(undefined, undefined);
812
+ }
813
+ return this._helpCommand;
814
+ }
815
+ return null;
816
+ }
817
+ hook(event, listener) {
818
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
819
+ if (!allowedValues.includes(event)) {
820
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
821
+ Expecting one of '${allowedValues.join("', '")}'`);
822
+ }
823
+ if (this._lifeCycleHooks[event]) {
824
+ this._lifeCycleHooks[event].push(listener);
825
+ } else {
826
+ this._lifeCycleHooks[event] = [listener];
827
+ }
828
+ return this;
829
+ }
830
+ exitOverride(fn) {
831
+ if (fn) {
832
+ this._exitCallback = fn;
833
+ } else {
834
+ this._exitCallback = (err) => {
835
+ if (err.code !== "commander.executeSubCommandAsync") {
836
+ throw err;
837
+ } else {}
838
+ };
839
+ }
840
+ return this;
841
+ }
842
+ _exit(exitCode, code, message) {
843
+ if (this._exitCallback) {
844
+ this._exitCallback(new CommanderError(exitCode, code, message));
845
+ }
846
+ process2.exit(exitCode);
847
+ }
848
+ action(fn) {
849
+ const listener = (args) => {
850
+ const expectedArgsCount = this.registeredArguments.length;
851
+ const actionArgs = args.slice(0, expectedArgsCount);
852
+ if (this._storeOptionsAsProperties) {
853
+ actionArgs[expectedArgsCount] = this;
854
+ } else {
855
+ actionArgs[expectedArgsCount] = this.opts();
856
+ }
857
+ actionArgs.push(this);
858
+ return fn.apply(this, actionArgs);
859
+ };
860
+ this._actionHandler = listener;
861
+ return this;
862
+ }
863
+ createOption(flags, description) {
864
+ return new Option(flags, description);
865
+ }
866
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
867
+ try {
868
+ return target.parseArg(value, previous);
869
+ } catch (err) {
870
+ if (err.code === "commander.invalidArgument") {
871
+ const message = `${invalidArgumentMessage} ${err.message}`;
872
+ this.error(message, { exitCode: err.exitCode, code: err.code });
873
+ }
874
+ throw err;
875
+ }
876
+ }
877
+ _registerOption(option) {
878
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
879
+ if (matchingOption) {
880
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
881
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
882
+ - already used by option '${matchingOption.flags}'`);
883
+ }
884
+ this.options.push(option);
885
+ }
886
+ _registerCommand(command) {
887
+ const knownBy = (cmd) => {
888
+ return [cmd.name()].concat(cmd.aliases());
889
+ };
890
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
891
+ if (alreadyUsed) {
892
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
893
+ const newCmd = knownBy(command).join("|");
894
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
895
+ }
896
+ this.commands.push(command);
897
+ }
898
+ addOption(option) {
899
+ this._registerOption(option);
900
+ const oname = option.name();
901
+ const name = option.attributeName();
902
+ if (option.negate) {
903
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
904
+ if (!this._findOption(positiveLongFlag)) {
905
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
906
+ }
907
+ } else if (option.defaultValue !== undefined) {
908
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
909
+ }
910
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
911
+ if (val == null && option.presetArg !== undefined) {
912
+ val = option.presetArg;
913
+ }
914
+ const oldValue = this.getOptionValue(name);
915
+ if (val !== null && option.parseArg) {
916
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
917
+ } else if (val !== null && option.variadic) {
918
+ val = option._concatValue(val, oldValue);
919
+ }
920
+ if (val == null) {
921
+ if (option.negate) {
922
+ val = false;
923
+ } else if (option.isBoolean() || option.optional) {
924
+ val = true;
925
+ } else {
926
+ val = "";
927
+ }
928
+ }
929
+ this.setOptionValueWithSource(name, val, valueSource);
930
+ };
931
+ this.on("option:" + oname, (val) => {
932
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
933
+ handleOptionValue(val, invalidValueMessage, "cli");
934
+ });
935
+ if (option.envVar) {
936
+ this.on("optionEnv:" + oname, (val) => {
937
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
938
+ handleOptionValue(val, invalidValueMessage, "env");
939
+ });
940
+ }
941
+ return this;
942
+ }
943
+ _optionEx(config, flags, description, fn, defaultValue) {
944
+ if (typeof flags === "object" && flags instanceof Option) {
945
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
946
+ }
947
+ const option = this.createOption(flags, description);
948
+ option.makeOptionMandatory(!!config.mandatory);
949
+ if (typeof fn === "function") {
950
+ option.default(defaultValue).argParser(fn);
951
+ } else if (fn instanceof RegExp) {
952
+ const regex = fn;
953
+ fn = (val, def) => {
954
+ const m = regex.exec(val);
955
+ return m ? m[0] : def;
956
+ };
957
+ option.default(defaultValue).argParser(fn);
958
+ } else {
959
+ option.default(fn);
960
+ }
961
+ return this.addOption(option);
962
+ }
963
+ option(flags, description, parseArg, defaultValue) {
964
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
965
+ }
966
+ requiredOption(flags, description, parseArg, defaultValue) {
967
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
968
+ }
969
+ combineFlagAndOptionalValue(combine = true) {
970
+ this._combineFlagAndOptionalValue = !!combine;
971
+ return this;
972
+ }
973
+ allowUnknownOption(allowUnknown = true) {
974
+ this._allowUnknownOption = !!allowUnknown;
975
+ return this;
976
+ }
977
+ allowExcessArguments(allowExcess = true) {
978
+ this._allowExcessArguments = !!allowExcess;
979
+ return this;
980
+ }
981
+ enablePositionalOptions(positional = true) {
982
+ this._enablePositionalOptions = !!positional;
983
+ return this;
984
+ }
985
+ passThroughOptions(passThrough = true) {
986
+ this._passThroughOptions = !!passThrough;
987
+ this._checkForBrokenPassThrough();
988
+ return this;
989
+ }
990
+ _checkForBrokenPassThrough() {
991
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
992
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
993
+ }
994
+ }
995
+ storeOptionsAsProperties(storeAsProperties = true) {
996
+ if (this.options.length) {
997
+ throw new Error("call .storeOptionsAsProperties() before adding options");
998
+ }
999
+ if (Object.keys(this._optionValues).length) {
1000
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1001
+ }
1002
+ this._storeOptionsAsProperties = !!storeAsProperties;
1003
+ return this;
1004
+ }
1005
+ getOptionValue(key) {
1006
+ if (this._storeOptionsAsProperties) {
1007
+ return this[key];
1008
+ }
1009
+ return this._optionValues[key];
1010
+ }
1011
+ setOptionValue(key, value) {
1012
+ return this.setOptionValueWithSource(key, value, undefined);
1013
+ }
1014
+ setOptionValueWithSource(key, value, source) {
1015
+ if (this._storeOptionsAsProperties) {
1016
+ this[key] = value;
1017
+ } else {
1018
+ this._optionValues[key] = value;
1019
+ }
1020
+ this._optionValueSources[key] = source;
1021
+ return this;
1022
+ }
1023
+ getOptionValueSource(key) {
1024
+ return this._optionValueSources[key];
1025
+ }
1026
+ getOptionValueSourceWithGlobals(key) {
1027
+ let source;
1028
+ this._getCommandAndAncestors().forEach((cmd) => {
1029
+ if (cmd.getOptionValueSource(key) !== undefined) {
1030
+ source = cmd.getOptionValueSource(key);
1031
+ }
1032
+ });
1033
+ return source;
1034
+ }
1035
+ _prepareUserArgs(argv, parseOptions) {
1036
+ if (argv !== undefined && !Array.isArray(argv)) {
1037
+ throw new Error("first parameter to parse must be array or undefined");
1038
+ }
1039
+ parseOptions = parseOptions || {};
1040
+ if (argv === undefined && parseOptions.from === undefined) {
1041
+ if (process2.versions?.electron) {
1042
+ parseOptions.from = "electron";
1043
+ }
1044
+ const execArgv = process2.execArgv ?? [];
1045
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1046
+ parseOptions.from = "eval";
1047
+ }
1048
+ }
1049
+ if (argv === undefined) {
1050
+ argv = process2.argv;
1051
+ }
1052
+ this.rawArgs = argv.slice();
1053
+ let userArgs;
1054
+ switch (parseOptions.from) {
1055
+ case undefined:
1056
+ case "node":
1057
+ this._scriptPath = argv[1];
1058
+ userArgs = argv.slice(2);
1059
+ break;
1060
+ case "electron":
1061
+ if (process2.defaultApp) {
1062
+ this._scriptPath = argv[1];
1063
+ userArgs = argv.slice(2);
1064
+ } else {
1065
+ userArgs = argv.slice(1);
1066
+ }
1067
+ break;
1068
+ case "user":
1069
+ userArgs = argv.slice(0);
1070
+ break;
1071
+ case "eval":
1072
+ userArgs = argv.slice(1);
1073
+ break;
1074
+ default:
1075
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1076
+ }
1077
+ if (!this._name && this._scriptPath)
1078
+ this.nameFromFilename(this._scriptPath);
1079
+ this._name = this._name || "program";
1080
+ return userArgs;
1081
+ }
1082
+ parse(argv, parseOptions) {
1083
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1084
+ this._parseCommand([], userArgs);
1085
+ return this;
1086
+ }
1087
+ async parseAsync(argv, parseOptions) {
1088
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1089
+ await this._parseCommand([], userArgs);
1090
+ return this;
1091
+ }
1092
+ _executeSubCommand(subcommand, args) {
1093
+ args = args.slice();
1094
+ let launchWithNode = false;
1095
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1096
+ function findFile(baseDir, baseName) {
1097
+ const localBin = path.resolve(baseDir, baseName);
1098
+ if (fs.existsSync(localBin))
1099
+ return localBin;
1100
+ if (sourceExt.includes(path.extname(baseName)))
1101
+ return;
1102
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1103
+ if (foundExt)
1104
+ return `${localBin}${foundExt}`;
1105
+ return;
1106
+ }
1107
+ this._checkForMissingMandatoryOptions();
1108
+ this._checkForConflictingOptions();
1109
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1110
+ let executableDir = this._executableDir || "";
1111
+ if (this._scriptPath) {
1112
+ let resolvedScriptPath;
1113
+ try {
1114
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1115
+ } catch (err) {
1116
+ resolvedScriptPath = this._scriptPath;
1117
+ }
1118
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1119
+ }
1120
+ if (executableDir) {
1121
+ let localFile = findFile(executableDir, executableFile);
1122
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1123
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1124
+ if (legacyName !== this._name) {
1125
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1126
+ }
1127
+ }
1128
+ executableFile = localFile || executableFile;
1129
+ }
1130
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1131
+ let proc;
1132
+ if (process2.platform !== "win32") {
1133
+ if (launchWithNode) {
1134
+ args.unshift(executableFile);
1135
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1136
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1137
+ } else {
1138
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1139
+ }
1140
+ } else {
1141
+ args.unshift(executableFile);
1142
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1143
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1144
+ }
1145
+ if (!proc.killed) {
1146
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1147
+ signals.forEach((signal) => {
1148
+ process2.on(signal, () => {
1149
+ if (proc.killed === false && proc.exitCode === null) {
1150
+ proc.kill(signal);
1151
+ }
1152
+ });
1153
+ });
1154
+ }
1155
+ const exitCallback = this._exitCallback;
1156
+ proc.on("close", (code) => {
1157
+ code = code ?? 1;
1158
+ if (!exitCallback) {
1159
+ process2.exit(code);
1160
+ } else {
1161
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1162
+ }
1163
+ });
1164
+ proc.on("error", (err) => {
1165
+ if (err.code === "ENOENT") {
1166
+ 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";
1167
+ const executableMissing = `'${executableFile}' does not exist
1168
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1169
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1170
+ - ${executableDirMessage}`;
1171
+ throw new Error(executableMissing);
1172
+ } else if (err.code === "EACCES") {
1173
+ throw new Error(`'${executableFile}' not executable`);
1174
+ }
1175
+ if (!exitCallback) {
1176
+ process2.exit(1);
1177
+ } else {
1178
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1179
+ wrappedError.nestedError = err;
1180
+ exitCallback(wrappedError);
1181
+ }
1182
+ });
1183
+ this.runningCommand = proc;
1184
+ }
1185
+ _dispatchSubcommand(commandName, operands, unknown) {
1186
+ const subCommand = this._findCommand(commandName);
1187
+ if (!subCommand)
1188
+ this.help({ error: true });
1189
+ let promiseChain;
1190
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1191
+ promiseChain = this._chainOrCall(promiseChain, () => {
1192
+ if (subCommand._executableHandler) {
1193
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1194
+ } else {
1195
+ return subCommand._parseCommand(operands, unknown);
1196
+ }
1197
+ });
1198
+ return promiseChain;
1199
+ }
1200
+ _dispatchHelpCommand(subcommandName) {
1201
+ if (!subcommandName) {
1202
+ this.help();
1203
+ }
1204
+ const subCommand = this._findCommand(subcommandName);
1205
+ if (subCommand && !subCommand._executableHandler) {
1206
+ subCommand.help();
1207
+ }
1208
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1209
+ }
1210
+ _checkNumberOfArguments() {
1211
+ this.registeredArguments.forEach((arg, i) => {
1212
+ if (arg.required && this.args[i] == null) {
1213
+ this.missingArgument(arg.name());
1214
+ }
1215
+ });
1216
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1217
+ return;
1218
+ }
1219
+ if (this.args.length > this.registeredArguments.length) {
1220
+ this._excessArguments(this.args);
1221
+ }
1222
+ }
1223
+ _processArguments() {
1224
+ const myParseArg = (argument, value, previous) => {
1225
+ let parsedValue = value;
1226
+ if (value !== null && argument.parseArg) {
1227
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1228
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1229
+ }
1230
+ return parsedValue;
1231
+ };
1232
+ this._checkNumberOfArguments();
1233
+ const processedArgs = [];
1234
+ this.registeredArguments.forEach((declaredArg, index) => {
1235
+ let value = declaredArg.defaultValue;
1236
+ if (declaredArg.variadic) {
1237
+ if (index < this.args.length) {
1238
+ value = this.args.slice(index);
1239
+ if (declaredArg.parseArg) {
1240
+ value = value.reduce((processed, v) => {
1241
+ return myParseArg(declaredArg, v, processed);
1242
+ }, declaredArg.defaultValue);
1243
+ }
1244
+ } else if (value === undefined) {
1245
+ value = [];
1246
+ }
1247
+ } else if (index < this.args.length) {
1248
+ value = this.args[index];
1249
+ if (declaredArg.parseArg) {
1250
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1251
+ }
1252
+ }
1253
+ processedArgs[index] = value;
1254
+ });
1255
+ this.processedArgs = processedArgs;
1256
+ }
1257
+ _chainOrCall(promise, fn) {
1258
+ if (promise && promise.then && typeof promise.then === "function") {
1259
+ return promise.then(() => fn());
1260
+ }
1261
+ return fn();
1262
+ }
1263
+ _chainOrCallHooks(promise, event) {
1264
+ let result = promise;
1265
+ const hooks = [];
1266
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1267
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1268
+ hooks.push({ hookedCommand, callback });
1269
+ });
1270
+ });
1271
+ if (event === "postAction") {
1272
+ hooks.reverse();
1273
+ }
1274
+ hooks.forEach((hookDetail) => {
1275
+ result = this._chainOrCall(result, () => {
1276
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1277
+ });
1278
+ });
1279
+ return result;
1280
+ }
1281
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1282
+ let result = promise;
1283
+ if (this._lifeCycleHooks[event] !== undefined) {
1284
+ this._lifeCycleHooks[event].forEach((hook) => {
1285
+ result = this._chainOrCall(result, () => {
1286
+ return hook(this, subCommand);
1287
+ });
1288
+ });
1289
+ }
1290
+ return result;
1291
+ }
1292
+ _parseCommand(operands, unknown) {
1293
+ const parsed = this.parseOptions(unknown);
1294
+ this._parseOptionsEnv();
1295
+ this._parseOptionsImplied();
1296
+ operands = operands.concat(parsed.operands);
1297
+ unknown = parsed.unknown;
1298
+ this.args = operands.concat(unknown);
1299
+ if (operands && this._findCommand(operands[0])) {
1300
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1301
+ }
1302
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1303
+ return this._dispatchHelpCommand(operands[1]);
1304
+ }
1305
+ if (this._defaultCommandName) {
1306
+ this._outputHelpIfRequested(unknown);
1307
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1308
+ }
1309
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1310
+ this.help({ error: true });
1311
+ }
1312
+ this._outputHelpIfRequested(parsed.unknown);
1313
+ this._checkForMissingMandatoryOptions();
1314
+ this._checkForConflictingOptions();
1315
+ const checkForUnknownOptions = () => {
1316
+ if (parsed.unknown.length > 0) {
1317
+ this.unknownOption(parsed.unknown[0]);
1318
+ }
1319
+ };
1320
+ const commandEvent = `command:${this.name()}`;
1321
+ if (this._actionHandler) {
1322
+ checkForUnknownOptions();
1323
+ this._processArguments();
1324
+ let promiseChain;
1325
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1326
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1327
+ if (this.parent) {
1328
+ promiseChain = this._chainOrCall(promiseChain, () => {
1329
+ this.parent.emit(commandEvent, operands, unknown);
1330
+ });
1331
+ }
1332
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1333
+ return promiseChain;
1334
+ }
1335
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1336
+ checkForUnknownOptions();
1337
+ this._processArguments();
1338
+ this.parent.emit(commandEvent, operands, unknown);
1339
+ } else if (operands.length) {
1340
+ if (this._findCommand("*")) {
1341
+ return this._dispatchSubcommand("*", operands, unknown);
1342
+ }
1343
+ if (this.listenerCount("command:*")) {
1344
+ this.emit("command:*", operands, unknown);
1345
+ } else if (this.commands.length) {
1346
+ this.unknownCommand();
1347
+ } else {
1348
+ checkForUnknownOptions();
1349
+ this._processArguments();
1350
+ }
1351
+ } else if (this.commands.length) {
1352
+ checkForUnknownOptions();
1353
+ this.help({ error: true });
1354
+ } else {
1355
+ checkForUnknownOptions();
1356
+ this._processArguments();
1357
+ }
1358
+ }
1359
+ _findCommand(name) {
1360
+ if (!name)
1361
+ return;
1362
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1363
+ }
1364
+ _findOption(arg) {
1365
+ return this.options.find((option) => option.is(arg));
1366
+ }
1367
+ _checkForMissingMandatoryOptions() {
1368
+ this._getCommandAndAncestors().forEach((cmd) => {
1369
+ cmd.options.forEach((anOption) => {
1370
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1371
+ cmd.missingMandatoryOptionValue(anOption);
1372
+ }
1373
+ });
1374
+ });
1375
+ }
1376
+ _checkForConflictingLocalOptions() {
1377
+ const definedNonDefaultOptions = this.options.filter((option) => {
1378
+ const optionKey = option.attributeName();
1379
+ if (this.getOptionValue(optionKey) === undefined) {
1380
+ return false;
1381
+ }
1382
+ return this.getOptionValueSource(optionKey) !== "default";
1383
+ });
1384
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1385
+ optionsWithConflicting.forEach((option) => {
1386
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1387
+ if (conflictingAndDefined) {
1388
+ this._conflictingOption(option, conflictingAndDefined);
1389
+ }
1390
+ });
1391
+ }
1392
+ _checkForConflictingOptions() {
1393
+ this._getCommandAndAncestors().forEach((cmd) => {
1394
+ cmd._checkForConflictingLocalOptions();
1395
+ });
1396
+ }
1397
+ parseOptions(argv) {
1398
+ const operands = [];
1399
+ const unknown = [];
1400
+ let dest = operands;
1401
+ const args = argv.slice();
1402
+ function maybeOption(arg) {
1403
+ return arg.length > 1 && arg[0] === "-";
1404
+ }
1405
+ let activeVariadicOption = null;
1406
+ while (args.length) {
1407
+ const arg = args.shift();
1408
+ if (arg === "--") {
1409
+ if (dest === unknown)
1410
+ dest.push(arg);
1411
+ dest.push(...args);
1412
+ break;
1413
+ }
1414
+ if (activeVariadicOption && !maybeOption(arg)) {
1415
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1416
+ continue;
1417
+ }
1418
+ activeVariadicOption = null;
1419
+ if (maybeOption(arg)) {
1420
+ const option = this._findOption(arg);
1421
+ if (option) {
1422
+ if (option.required) {
1423
+ const value = args.shift();
1424
+ if (value === undefined)
1425
+ this.optionMissingArgument(option);
1426
+ this.emit(`option:${option.name()}`, value);
1427
+ } else if (option.optional) {
1428
+ let value = null;
1429
+ if (args.length > 0 && !maybeOption(args[0])) {
1430
+ value = args.shift();
1431
+ }
1432
+ this.emit(`option:${option.name()}`, value);
1433
+ } else {
1434
+ this.emit(`option:${option.name()}`);
1435
+ }
1436
+ activeVariadicOption = option.variadic ? option : null;
1437
+ continue;
1438
+ }
1439
+ }
1440
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1441
+ const option = this._findOption(`-${arg[1]}`);
1442
+ if (option) {
1443
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1444
+ this.emit(`option:${option.name()}`, arg.slice(2));
1445
+ } else {
1446
+ this.emit(`option:${option.name()}`);
1447
+ args.unshift(`-${arg.slice(2)}`);
1448
+ }
1449
+ continue;
1450
+ }
1451
+ }
1452
+ if (/^--[^=]+=/.test(arg)) {
1453
+ const index = arg.indexOf("=");
1454
+ const option = this._findOption(arg.slice(0, index));
1455
+ if (option && (option.required || option.optional)) {
1456
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1457
+ continue;
1458
+ }
1459
+ }
1460
+ if (maybeOption(arg)) {
1461
+ dest = unknown;
1462
+ }
1463
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1464
+ if (this._findCommand(arg)) {
1465
+ operands.push(arg);
1466
+ if (args.length > 0)
1467
+ unknown.push(...args);
1468
+ break;
1469
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1470
+ operands.push(arg);
1471
+ if (args.length > 0)
1472
+ operands.push(...args);
1473
+ break;
1474
+ } else if (this._defaultCommandName) {
1475
+ unknown.push(arg);
1476
+ if (args.length > 0)
1477
+ unknown.push(...args);
1478
+ break;
1479
+ }
1480
+ }
1481
+ if (this._passThroughOptions) {
1482
+ dest.push(arg);
1483
+ if (args.length > 0)
1484
+ dest.push(...args);
1485
+ break;
1486
+ }
1487
+ dest.push(arg);
1488
+ }
1489
+ return { operands, unknown };
1490
+ }
1491
+ opts() {
1492
+ if (this._storeOptionsAsProperties) {
1493
+ const result = {};
1494
+ const len = this.options.length;
1495
+ for (let i = 0;i < len; i++) {
1496
+ const key = this.options[i].attributeName();
1497
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1498
+ }
1499
+ return result;
1500
+ }
1501
+ return this._optionValues;
1502
+ }
1503
+ optsWithGlobals() {
1504
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1505
+ }
1506
+ error(message, errorOptions) {
1507
+ this._outputConfiguration.outputError(`${message}
1508
+ `, this._outputConfiguration.writeErr);
1509
+ if (typeof this._showHelpAfterError === "string") {
1510
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1511
+ `);
1512
+ } else if (this._showHelpAfterError) {
1513
+ this._outputConfiguration.writeErr(`
1514
+ `);
1515
+ this.outputHelp({ error: true });
1516
+ }
1517
+ const config = errorOptions || {};
1518
+ const exitCode = config.exitCode || 1;
1519
+ const code = config.code || "commander.error";
1520
+ this._exit(exitCode, code, message);
1521
+ }
1522
+ _parseOptionsEnv() {
1523
+ this.options.forEach((option) => {
1524
+ if (option.envVar && option.envVar in process2.env) {
1525
+ const optionKey = option.attributeName();
1526
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1527
+ if (option.required || option.optional) {
1528
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1529
+ } else {
1530
+ this.emit(`optionEnv:${option.name()}`);
1531
+ }
1532
+ }
1533
+ }
1534
+ });
1535
+ }
1536
+ _parseOptionsImplied() {
1537
+ const dualHelper = new DualOptions(this.options);
1538
+ const hasCustomOptionValue = (optionKey) => {
1539
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1540
+ };
1541
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1542
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1543
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1544
+ });
1545
+ });
1546
+ }
1547
+ missingArgument(name) {
1548
+ const message = `error: missing required argument '${name}'`;
1549
+ this.error(message, { code: "commander.missingArgument" });
1550
+ }
1551
+ optionMissingArgument(option) {
1552
+ const message = `error: option '${option.flags}' argument missing`;
1553
+ this.error(message, { code: "commander.optionMissingArgument" });
1554
+ }
1555
+ missingMandatoryOptionValue(option) {
1556
+ const message = `error: required option '${option.flags}' not specified`;
1557
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1558
+ }
1559
+ _conflictingOption(option, conflictingOption) {
1560
+ const findBestOptionFromValue = (option2) => {
1561
+ const optionKey = option2.attributeName();
1562
+ const optionValue = this.getOptionValue(optionKey);
1563
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1564
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1565
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1566
+ return negativeOption;
1567
+ }
1568
+ return positiveOption || option2;
1569
+ };
1570
+ const getErrorMessage = (option2) => {
1571
+ const bestOption = findBestOptionFromValue(option2);
1572
+ const optionKey = bestOption.attributeName();
1573
+ const source = this.getOptionValueSource(optionKey);
1574
+ if (source === "env") {
1575
+ return `environment variable '${bestOption.envVar}'`;
1576
+ }
1577
+ return `option '${bestOption.flags}'`;
1578
+ };
1579
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1580
+ this.error(message, { code: "commander.conflictingOption" });
1581
+ }
1582
+ unknownOption(flag) {
1583
+ if (this._allowUnknownOption)
1584
+ return;
1585
+ let suggestion = "";
1586
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1587
+ let candidateFlags = [];
1588
+ let command = this;
1589
+ do {
1590
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1591
+ candidateFlags = candidateFlags.concat(moreFlags);
1592
+ command = command.parent;
1593
+ } while (command && !command._enablePositionalOptions);
1594
+ suggestion = suggestSimilar(flag, candidateFlags);
1595
+ }
1596
+ const message = `error: unknown option '${flag}'${suggestion}`;
1597
+ this.error(message, { code: "commander.unknownOption" });
1598
+ }
1599
+ _excessArguments(receivedArgs) {
1600
+ if (this._allowExcessArguments)
1601
+ return;
1602
+ const expected = this.registeredArguments.length;
1603
+ const s = expected === 1 ? "" : "s";
1604
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1605
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1606
+ this.error(message, { code: "commander.excessArguments" });
1607
+ }
1608
+ unknownCommand() {
1609
+ const unknownName = this.args[0];
1610
+ let suggestion = "";
1611
+ if (this._showSuggestionAfterError) {
1612
+ const candidateNames = [];
1613
+ this.createHelp().visibleCommands(this).forEach((command) => {
1614
+ candidateNames.push(command.name());
1615
+ if (command.alias())
1616
+ candidateNames.push(command.alias());
1617
+ });
1618
+ suggestion = suggestSimilar(unknownName, candidateNames);
1619
+ }
1620
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1621
+ this.error(message, { code: "commander.unknownCommand" });
1622
+ }
1623
+ version(str, flags, description) {
1624
+ if (str === undefined)
1625
+ return this._version;
1626
+ this._version = str;
1627
+ flags = flags || "-V, --version";
1628
+ description = description || "output the version number";
1629
+ const versionOption = this.createOption(flags, description);
1630
+ this._versionOptionName = versionOption.attributeName();
1631
+ this._registerOption(versionOption);
1632
+ this.on("option:" + versionOption.name(), () => {
1633
+ this._outputConfiguration.writeOut(`${str}
1634
+ `);
1635
+ this._exit(0, "commander.version", str);
1636
+ });
1637
+ return this;
1638
+ }
1639
+ description(str, argsDescription) {
1640
+ if (str === undefined && argsDescription === undefined)
1641
+ return this._description;
1642
+ this._description = str;
1643
+ if (argsDescription) {
1644
+ this._argsDescription = argsDescription;
1645
+ }
1646
+ return this;
1647
+ }
1648
+ summary(str) {
1649
+ if (str === undefined)
1650
+ return this._summary;
1651
+ this._summary = str;
1652
+ return this;
1653
+ }
1654
+ alias(alias) {
1655
+ if (alias === undefined)
1656
+ return this._aliases[0];
1657
+ let command = this;
1658
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1659
+ command = this.commands[this.commands.length - 1];
1660
+ }
1661
+ if (alias === command._name)
1662
+ throw new Error("Command alias can't be the same as its name");
1663
+ const matchingCommand = this.parent?._findCommand(alias);
1664
+ if (matchingCommand) {
1665
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1666
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1667
+ }
1668
+ command._aliases.push(alias);
1669
+ return this;
1670
+ }
1671
+ aliases(aliases) {
1672
+ if (aliases === undefined)
1673
+ return this._aliases;
1674
+ aliases.forEach((alias) => this.alias(alias));
1675
+ return this;
1676
+ }
1677
+ usage(str) {
1678
+ if (str === undefined) {
1679
+ if (this._usage)
1680
+ return this._usage;
1681
+ const args = this.registeredArguments.map((arg) => {
1682
+ return humanReadableArgName(arg);
1683
+ });
1684
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1685
+ }
1686
+ this._usage = str;
1687
+ return this;
1688
+ }
1689
+ name(str) {
1690
+ if (str === undefined)
1691
+ return this._name;
1692
+ this._name = str;
1693
+ return this;
1694
+ }
1695
+ nameFromFilename(filename) {
1696
+ this._name = path.basename(filename, path.extname(filename));
1697
+ return this;
1698
+ }
1699
+ executableDir(path2) {
1700
+ if (path2 === undefined)
1701
+ return this._executableDir;
1702
+ this._executableDir = path2;
1703
+ return this;
1704
+ }
1705
+ helpInformation(contextOptions) {
1706
+ const helper = this.createHelp();
1707
+ if (helper.helpWidth === undefined) {
1708
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
1709
+ }
1710
+ return helper.formatHelp(this, helper);
1711
+ }
1712
+ _getHelpContext(contextOptions) {
1713
+ contextOptions = contextOptions || {};
1714
+ const context = { error: !!contextOptions.error };
1715
+ let write;
1716
+ if (context.error) {
1717
+ write = (arg) => this._outputConfiguration.writeErr(arg);
1718
+ } else {
1719
+ write = (arg) => this._outputConfiguration.writeOut(arg);
1720
+ }
1721
+ context.write = contextOptions.write || write;
1722
+ context.command = this;
1723
+ return context;
1724
+ }
1725
+ outputHelp(contextOptions) {
1726
+ let deprecatedCallback;
1727
+ if (typeof contextOptions === "function") {
1728
+ deprecatedCallback = contextOptions;
1729
+ contextOptions = undefined;
1730
+ }
1731
+ const context = this._getHelpContext(contextOptions);
1732
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
1733
+ this.emit("beforeHelp", context);
1734
+ let helpInformation = this.helpInformation(context);
1735
+ if (deprecatedCallback) {
1736
+ helpInformation = deprecatedCallback(helpInformation);
1737
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1738
+ throw new Error("outputHelp callback must return a string or a Buffer");
1739
+ }
1740
+ }
1741
+ context.write(helpInformation);
1742
+ if (this._getHelpOption()?.long) {
1743
+ this.emit(this._getHelpOption().long);
1744
+ }
1745
+ this.emit("afterHelp", context);
1746
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
1747
+ }
1748
+ helpOption(flags, description) {
1749
+ if (typeof flags === "boolean") {
1750
+ if (flags) {
1751
+ this._helpOption = this._helpOption ?? undefined;
1752
+ } else {
1753
+ this._helpOption = null;
1754
+ }
1755
+ return this;
1756
+ }
1757
+ flags = flags ?? "-h, --help";
1758
+ description = description ?? "display help for command";
1759
+ this._helpOption = this.createOption(flags, description);
1760
+ return this;
1761
+ }
1762
+ _getHelpOption() {
1763
+ if (this._helpOption === undefined) {
1764
+ this.helpOption(undefined, undefined);
1765
+ }
1766
+ return this._helpOption;
1767
+ }
1768
+ addHelpOption(option) {
1769
+ this._helpOption = option;
1770
+ return this;
1771
+ }
1772
+ help(contextOptions) {
1773
+ this.outputHelp(contextOptions);
1774
+ let exitCode = process2.exitCode || 0;
1775
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1776
+ exitCode = 1;
1777
+ }
1778
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1779
+ }
1780
+ addHelpText(position, text) {
1781
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1782
+ if (!allowedValues.includes(position)) {
1783
+ throw new Error(`Unexpected value for position to addHelpText.
1784
+ Expecting one of '${allowedValues.join("', '")}'`);
1785
+ }
1786
+ const helpEvent = `${position}Help`;
1787
+ this.on(helpEvent, (context) => {
1788
+ let helpStr;
1789
+ if (typeof text === "function") {
1790
+ helpStr = text({ error: context.error, command: context.command });
1791
+ } else {
1792
+ helpStr = text;
1793
+ }
1794
+ if (helpStr) {
1795
+ context.write(`${helpStr}
1796
+ `);
1797
+ }
1798
+ });
1799
+ return this;
1800
+ }
1801
+ _outputHelpIfRequested(args) {
1802
+ const helpOption = this._getHelpOption();
1803
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
1804
+ if (helpRequested) {
1805
+ this.outputHelp();
1806
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
1807
+ }
1808
+ }
1809
+ }
1810
+ function incrementNodeInspectorPort(args) {
1811
+ return args.map((arg) => {
1812
+ if (!arg.startsWith("--inspect")) {
1813
+ return arg;
1814
+ }
1815
+ let debugOption;
1816
+ let debugHost = "127.0.0.1";
1817
+ let debugPort = "9229";
1818
+ let match;
1819
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
1820
+ debugOption = match[1];
1821
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
1822
+ debugOption = match[1];
1823
+ if (/^\d+$/.test(match[3])) {
1824
+ debugPort = match[3];
1825
+ } else {
1826
+ debugHost = match[3];
1827
+ }
1828
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
1829
+ debugOption = match[1];
1830
+ debugHost = match[3];
1831
+ debugPort = match[4];
1832
+ }
1833
+ if (debugOption && debugPort !== "0") {
1834
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
1835
+ }
1836
+ return arg;
1837
+ });
1838
+ }
1839
+ exports.Command = Command;
1840
+ });
1841
+
1842
+ // node_modules/commander/index.js
1843
+ var require_commander = __commonJS((exports) => {
1844
+ var { Argument } = require_argument();
1845
+ var { Command } = require_command();
1846
+ var { CommanderError, InvalidArgumentError } = require_error();
1847
+ var { Help } = require_help();
1848
+ var { Option } = require_option();
1849
+ exports.program = new Command;
1850
+ exports.createCommand = (name) => new Command(name);
1851
+ exports.createOption = (flags, description) => new Option(flags, description);
1852
+ exports.createArgument = (name, description) => new Argument(name, description);
1853
+ exports.Command = Command;
1854
+ exports.Option = Option;
1855
+ exports.Argument = Argument;
1856
+ exports.Help = Help;
1857
+ exports.CommanderError = CommanderError;
1858
+ exports.InvalidArgumentError = InvalidArgumentError;
1859
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
1860
+ });
1861
+
1862
+ // node_modules/commander/esm.mjs
1863
+ var import__ = __toESM(require_commander(), 1);
1864
+ var {
1865
+ program,
1866
+ createCommand,
1867
+ createArgument,
1868
+ createOption,
1869
+ CommanderError,
1870
+ InvalidArgumentError,
1871
+ InvalidOptionArgumentError,
1872
+ Command,
1873
+ Argument,
1874
+ Option,
1875
+ Help
1876
+ } = import__.default;
1877
+
1878
+ // src/config/endpoints.ts
1879
+ var BUILTIN_ENDPOINTS = [
1880
+ {
1881
+ name: "glm",
1882
+ endpoint: "https://open.bigmodel.cn/api/anthropic",
1883
+ models: {
1884
+ haiku: "glm-4.7",
1885
+ opus: "glm-4.7",
1886
+ sonnet: "glm-4.7"
1887
+ }
1888
+ },
1889
+ {
1890
+ name: "deepseek",
1891
+ endpoint: "https://api.deepseek.com/anthropic",
1892
+ models: {
1893
+ haiku: "deepseek-chat",
1894
+ opus: "deepseek-chat",
1895
+ sonnet: "deepseek-chat"
1896
+ }
1897
+ },
1898
+ {
1899
+ name: "minimax",
1900
+ endpoint: "https://api.minimax.io/anthropic",
1901
+ models: {
1902
+ haiku: "MiniMax-M2",
1903
+ opus: "MiniMax-M2",
1904
+ sonnet: "MiniMax-M2"
1905
+ }
1906
+ }
1907
+ ];
1908
+ function getBuiltinEndpoint(name) {
1909
+ return BUILTIN_ENDPOINTS.find((ep) => ep.name === name);
1910
+ }
1911
+ function isBuiltinEndpoint(name) {
1912
+ return BUILTIN_ENDPOINTS.some((ep) => ep.name === name);
1913
+ }
1914
+
1915
+ // src/config/storage.ts
1916
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
1917
+ import { join } from "node:path";
1918
+ import { homedir } from "node:os";
1919
+ function getConfigDir() {
1920
+ const home = process.env.CC_RUN_TEST_HOME || homedir();
1921
+ return join(home, ".cc-run");
1922
+ }
1923
+ function getConfigFilePath() {
1924
+ return join(getConfigDir(), "config.json");
1925
+ }
1926
+ function ensureConfigDir() {
1927
+ const dir = getConfigDir();
1928
+ if (!existsSync(dir)) {
1929
+ mkdirSync(dir, { recursive: true });
1930
+ }
1931
+ }
1932
+ function readConfig() {
1933
+ const filePath = getConfigFilePath();
1934
+ if (!existsSync(filePath)) {
1935
+ return {
1936
+ endpoints: [],
1937
+ tokens: {},
1938
+ proxy: { enabled: false }
1939
+ };
1940
+ }
1941
+ try {
1942
+ const content = readFileSync(filePath, "utf-8");
1943
+ return JSON.parse(content);
1944
+ } catch (error) {
1945
+ console.error(`读取配置文件失败: ${error}`);
1946
+ return {
1947
+ endpoints: [],
1948
+ tokens: {},
1949
+ proxy: { enabled: false }
1950
+ };
1951
+ }
1952
+ }
1953
+ function writeConfig(config) {
1954
+ ensureConfigDir();
1955
+ writeFileSync(getConfigFilePath(), JSON.stringify(config, null, 2), "utf-8");
1956
+ }
1957
+ function getCustomEndpoints() {
1958
+ const config = readConfig();
1959
+ return config.endpoints || [];
1960
+ }
1961
+ function addCustomEndpoint(name, endpoint, token, models) {
1962
+ const config = readConfig();
1963
+ if (!config.endpoints) {
1964
+ config.endpoints = [];
1965
+ }
1966
+ const existingIndex = config.endpoints.findIndex((ep) => ep.name === name);
1967
+ if (existingIndex !== -1) {
1968
+ config.endpoints[existingIndex] = { name, endpoint, token, models };
1969
+ } else {
1970
+ config.endpoints.push({ name, endpoint, token, models });
1971
+ }
1972
+ writeConfig(config);
1973
+ }
1974
+ function removeCustomEndpoint(name) {
1975
+ const config = readConfig();
1976
+ if (!config.endpoints) {
1977
+ return false;
1978
+ }
1979
+ const initialLength = config.endpoints.length;
1980
+ config.endpoints = config.endpoints.filter((ep) => ep.name !== name);
1981
+ if (config.endpoints.length < initialLength) {
1982
+ writeConfig(config);
1983
+ return true;
1984
+ }
1985
+ return false;
1986
+ }
1987
+ function getToken(provider) {
1988
+ const config = readConfig();
1989
+ return config.tokens?.[provider];
1990
+ }
1991
+ function saveToken(provider, token) {
1992
+ const config = readConfig();
1993
+ if (!config.tokens) {
1994
+ config.tokens = {};
1995
+ }
1996
+ config.tokens[provider] = token;
1997
+ writeConfig(config);
1998
+ }
1999
+ function setLastUsed(provider) {
2000
+ const config = readConfig();
2001
+ config.lastUsed = provider;
2002
+ writeConfig(config);
2003
+ }
2004
+ function getProxyConfig() {
2005
+ const config = readConfig();
2006
+ return config.proxy || { enabled: false };
2007
+ }
2008
+ function setProxyConfig(enabled, url, clearForOfficial) {
2009
+ const config = readConfig();
2010
+ config.proxy = {
2011
+ enabled,
2012
+ url,
2013
+ clearForOfficial
2014
+ };
2015
+ writeConfig(config);
2016
+ }
2017
+
2018
+ // src/commands/list.ts
2019
+ function safeLog(message) {
2020
+ const encoder = new TextEncoder;
2021
+ const data = encoder.encode(message + `
2022
+ `);
2023
+ Bun.write(Bun.stdout, data);
2024
+ }
2025
+ function formatEndpoint(name, endpoint, hasToken) {
2026
+ const tokenStatus = hasToken ? "已配置 token" : "未配置 token";
2027
+ return ` ${name.padEnd(12)} ${endpoint} (${tokenStatus})`;
2028
+ }
2029
+ function list() {
2030
+ safeLog("可用的 Endpoints:");
2031
+ safeLog("");
2032
+ safeLog("内置:");
2033
+ for (const ep of BUILTIN_ENDPOINTS) {
2034
+ const token = getToken(ep.name);
2035
+ safeLog(formatEndpoint(ep.name, ep.endpoint, !!token));
2036
+ }
2037
+ const custom = getCustomEndpoints();
2038
+ if (custom.length > 0) {
2039
+ safeLog("");
2040
+ safeLog("自定义:");
2041
+ for (const ep of custom) {
2042
+ safeLog(formatEndpoint(ep.name, ep.endpoint, !!ep.token));
2043
+ }
2044
+ } else {
2045
+ safeLog("");
2046
+ safeLog("自定义: 无");
2047
+ }
2048
+ }
2049
+
2050
+ // src/commands/add.ts
2051
+ import { createInterface } from "node:readline";
2052
+ async function prompt(question) {
2053
+ const rl = createInterface({
2054
+ input: process.stdin,
2055
+ output: process.stdout
2056
+ });
2057
+ return new Promise((resolve) => {
2058
+ rl.question(question, (answer) => {
2059
+ rl.close();
2060
+ resolve(answer.trim());
2061
+ });
2062
+ });
2063
+ }
2064
+ async function add(name, endpoint) {
2065
+ if (isBuiltinEndpoint(name)) {
2066
+ console.error(`错误: 不能使用内置 endpoint 名称 "${name}"`);
2067
+ process.exit(1);
2068
+ }
2069
+ try {
2070
+ new URL(endpoint);
2071
+ } catch {
2072
+ console.error(`错误: 无效的 endpoint URL "${endpoint}"`);
2073
+ process.exit(1);
2074
+ }
2075
+ const token = await prompt(`请输入 ${name} 的 API Token: `);
2076
+ const modelName = await prompt("请输入模型名称: ");
2077
+ const models = {
2078
+ haiku: modelName,
2079
+ opus: modelName,
2080
+ sonnet: modelName
2081
+ };
2082
+ addCustomEndpoint(name, endpoint, token, models);
2083
+ console.log(`已添加 endpoint: ${name}`);
2084
+ }
2085
+
2086
+ // src/commands/remove.ts
2087
+ function remove(name) {
2088
+ if (isBuiltinEndpoint(name)) {
2089
+ console.error(`错误: 不能删除内置 endpoint "${name}"`);
2090
+ process.exit(1);
2091
+ }
2092
+ const success = removeCustomEndpoint(name);
2093
+ if (success) {
2094
+ console.log(`已删除 endpoint: ${name}`);
2095
+ } else {
2096
+ console.error(`错误: 未找到自定义 endpoint "${name}"`);
2097
+ process.exit(1);
2098
+ }
2099
+ }
2100
+
2101
+ // src/commands/proxy.ts
2102
+ import { createInterface as createInterface2 } from "node:readline";
2103
+
2104
+ // src/utils/claude-settings.ts
2105
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "node:fs";
2106
+ import { join as join2 } from "node:path";
2107
+ import { homedir as homedir2 } from "node:os";
2108
+ function getClaudeDir() {
2109
+ const home = process.env.CC_RUN_TEST_HOME || homedir2();
2110
+ return join2(home, ".claude");
2111
+ }
2112
+ function getClaudeSettingsFilePath() {
2113
+ return join2(getClaudeDir(), "settings.json");
2114
+ }
2115
+ function ensureClaudeDir() {
2116
+ const dir = getClaudeDir();
2117
+ if (!existsSync2(dir)) {
2118
+ mkdirSync2(dir, { recursive: true });
2119
+ }
2120
+ }
2121
+ function readClaudeSettings() {
2122
+ const settingsFile = getClaudeSettingsFilePath();
2123
+ if (!existsSync2(settingsFile)) {
2124
+ return {};
2125
+ }
2126
+ try {
2127
+ const content = readFileSync2(settingsFile, "utf-8");
2128
+ return JSON.parse(content);
2129
+ } catch (error) {
2130
+ console.error(`读取 Claude 配置文件失败: ${error}`);
2131
+ return {};
2132
+ }
2133
+ }
2134
+ function writeClaudeSettings(settings) {
2135
+ ensureClaudeDir();
2136
+ writeFileSync2(getClaudeSettingsFilePath(), JSON.stringify(settings, null, 2), "utf-8");
2137
+ }
2138
+ function getClaudeProxy() {
2139
+ const settings = readClaudeSettings();
2140
+ return settings.proxy;
2141
+ }
2142
+ function setClaudeProxy(url) {
2143
+ const settings = readClaudeSettings();
2144
+ settings.proxy = url;
2145
+ writeClaudeSettings(settings);
2146
+ }
2147
+ function removeClaudeProxy() {
2148
+ const settings = readClaudeSettings();
2149
+ delete settings.proxy;
2150
+ writeClaudeSettings(settings);
2151
+ }
2152
+ function setThirdPartyApi(apiUrl, apiKey) {
2153
+ const settings = readClaudeSettings();
2154
+ settings.apiUrl = apiUrl;
2155
+ settings.anthropicApiKey = apiKey;
2156
+ writeClaudeSettings(settings);
2157
+ }
2158
+ function removeThirdPartyApi() {
2159
+ const settings = readClaudeSettings();
2160
+ delete settings.apiUrl;
2161
+ delete settings.anthropicApiKey;
2162
+ writeClaudeSettings(settings);
2163
+ }
2164
+ function backupClaudeSettings() {
2165
+ return readClaudeSettings();
2166
+ }
2167
+ function restoreClaudeSettings(backup) {
2168
+ writeClaudeSettings(backup);
2169
+ }
2170
+ var ANTHROPIC_ENV_KEYS = [
2171
+ "ANTHROPIC_AUTH_TOKEN",
2172
+ "ANTHROPIC_BASE_URL",
2173
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL",
2174
+ "ANTHROPIC_DEFAULT_SONNET_MODEL",
2175
+ "ANTHROPIC_DEFAULT_OPUS_MODEL"
2176
+ ];
2177
+ function hasAnthropicEnv(settings) {
2178
+ if (!settings.env)
2179
+ return false;
2180
+ return ANTHROPIC_ENV_KEYS.some((key) => !!settings.env[key]);
2181
+ }
2182
+ function clearAnthropicEnv(settings) {
2183
+ if (settings.env) {
2184
+ for (const key of ANTHROPIC_ENV_KEYS) {
2185
+ delete settings.env[key];
2186
+ }
2187
+ if (Object.keys(settings.env).length === 0) {
2188
+ delete settings.env;
2189
+ }
2190
+ }
2191
+ }
2192
+
2193
+ // src/commands/proxy.ts
2194
+ async function proxyOn() {
2195
+ const currentConfig = getProxyConfig();
2196
+ let proxyUrl = currentConfig.url;
2197
+ if (!proxyUrl) {
2198
+ proxyUrl = await promptProxyUrl();
2199
+ }
2200
+ setProxyConfig(true, proxyUrl, currentConfig.clearForOfficial);
2201
+ setClaudeProxy(proxyUrl);
2202
+ console.log(`代理已开启: ${proxyUrl}`);
2203
+ console.log(`配置文件: ${getClaudeSettingsFilePath()}`);
2204
+ }
2205
+ function proxyOff() {
2206
+ const currentConfig = getProxyConfig();
2207
+ setProxyConfig(false, currentConfig.url, currentConfig.clearForOfficial);
2208
+ removeClaudeProxy();
2209
+ console.log("代理已关闭");
2210
+ }
2211
+ function proxyReset() {
2212
+ setProxyConfig(false);
2213
+ removeClaudeProxy();
2214
+ console.log("代理配置已重置");
2215
+ }
2216
+ function proxyStatus() {
2217
+ const ccRunConfig = getProxyConfig();
2218
+ const claudeProxy = getClaudeProxy();
2219
+ console.log("CC-Run 代理配置:");
2220
+ console.log(` 状态: ${ccRunConfig.enabled ? "开启" : "关闭"}`);
2221
+ if (ccRunConfig.url) {
2222
+ console.log(` 地址: ${ccRunConfig.url}`);
2223
+ }
2224
+ if (ccRunConfig.clearForOfficial !== undefined) {
2225
+ console.log(` 启动官方时清除: ${ccRunConfig.clearForOfficial ? "是" : "否"}`);
2226
+ }
2227
+ console.log(`
2228
+ Claude 配置文件 (~/.claude/settings.json):`);
2229
+ if (claudeProxy) {
2230
+ console.log(` 代理: ${claudeProxy}`);
2231
+ } else {
2232
+ console.log(" 代理: 未配置");
2233
+ }
2234
+ }
2235
+ function proxyHelp() {
2236
+ console.log(`
2237
+ 代理管理命令:
2238
+
2239
+ cc-run proxy on 开启代理(首次会提示输入代理地址)
2240
+ cc-run proxy off 关闭代理
2241
+ cc-run proxy reset 重置代理配置
2242
+ cc-run proxy status 查看代理状态
2243
+ cc-run proxy help 显示此帮助信息
2244
+
2245
+ 说明:
2246
+ - proxy on 会修改 ~/.claude/settings.json,添加 proxy 配置
2247
+ - proxy off 会删除 ~/.claude/settings.json 中的 proxy 配置
2248
+ - 代理地址保存在 ~/.cc-run/config.json 中
2249
+ `);
2250
+ }
2251
+ async function promptProxyUrl() {
2252
+ const rl = createInterface2({
2253
+ input: process.stdin,
2254
+ output: process.stdout
2255
+ });
2256
+ return new Promise((resolve) => {
2257
+ rl.question("请输入代理地址 (例如 http://agent.baidu.com:8891): ", (answer) => {
2258
+ rl.close();
2259
+ resolve(answer.trim());
2260
+ });
2261
+ });
2262
+ }
2263
+
2264
+ // src/commands/run.ts
2265
+ import { createInterface as createInterface3 } from "node:readline";
2266
+
2267
+ // src/utils/launcher.ts
2268
+ import { spawn } from "node:child_process";
2269
+
2270
+ // src/utils/env.ts
2271
+ function buildEnv(options) {
2272
+ const env = {
2273
+ ANTHROPIC_BASE_URL: options.apiEndpoint,
2274
+ ANTHROPIC_AUTH_TOKEN: options.apiKey
2275
+ };
2276
+ if (options.models) {
2277
+ if (options.models.haiku) {
2278
+ env.ANTHROPIC_DEFAULT_HAIKU_MODEL = options.models.haiku;
2279
+ }
2280
+ if (options.models.opus) {
2281
+ env.ANTHROPIC_DEFAULT_OPUS_MODEL = options.models.opus;
2282
+ }
2283
+ if (options.models.sonnet) {
2284
+ env.ANTHROPIC_DEFAULT_SONNET_MODEL = options.models.sonnet;
2285
+ }
2286
+ }
2287
+ if (options.proxyUrl) {
2288
+ env.http_proxy = options.proxyUrl;
2289
+ env.https_proxy = options.proxyUrl;
2290
+ env.HTTP_PROXY = options.proxyUrl;
2291
+ env.HTTPS_PROXY = options.proxyUrl;
2292
+ }
2293
+ return env;
2294
+ }
2295
+ function buildOfficialEnv(proxyUrl) {
2296
+ const env = {};
2297
+ if (proxyUrl) {
2298
+ env.http_proxy = proxyUrl;
2299
+ env.https_proxy = proxyUrl;
2300
+ env.HTTP_PROXY = proxyUrl;
2301
+ env.HTTPS_PROXY = proxyUrl;
2302
+ }
2303
+ return env;
2304
+ }
2305
+
2306
+ // src/utils/launcher.ts
2307
+ function launchClaude(options, claudeArgs = []) {
2308
+ const env = buildEnv(options);
2309
+ const child = spawn("claude", claudeArgs, {
2310
+ stdio: "inherit",
2311
+ env: { ...process.env, ...env }
2312
+ });
2313
+ return child;
2314
+ }
2315
+ function launchOfficialClaude(proxyUrl, claudeArgs = []) {
2316
+ const env = buildOfficialEnv(proxyUrl);
2317
+ const child = spawn("claude", claudeArgs, {
2318
+ stdio: "inherit",
2319
+ env: { ...process.env, ...env }
2320
+ });
2321
+ return child;
2322
+ }
2323
+ function waitForExit(child) {
2324
+ return new Promise((resolve) => {
2325
+ child.on("close", (code) => {
2326
+ resolve(code ?? 0);
2327
+ });
2328
+ });
2329
+ }
2330
+
2331
+ // src/commands/run.ts
2332
+ async function runOfficial(passthroughArgs = []) {
2333
+ const proxyConfig = getProxyConfig();
2334
+ const claudeProxy = getClaudeProxy();
2335
+ const backup = backupClaudeSettings();
2336
+ let needsRestore = false;
2337
+ if (backup.apiUrl || backup.anthropicApiKey) {
2338
+ removeThirdPartyApi();
2339
+ needsRestore = true;
2340
+ console.log("已临时清除第三方 endpoint 配置");
2341
+ }
2342
+ const shouldClearProxy = proxyConfig.clearForOfficial && claudeProxy !== undefined;
2343
+ const useProxy = shouldClearProxy ? undefined : claudeProxy;
2344
+ if (shouldClearProxy) {
2345
+ removeClaudeProxy();
2346
+ needsRestore = true;
2347
+ console.log("已临时清除代理配置");
2348
+ }
2349
+ if (needsRestore) {
2350
+ console.log("Claude 退出后将恢复配置...");
2351
+ }
2352
+ const child = launchOfficialClaude(useProxy, passthroughArgs);
2353
+ const exitCode = await waitForExit(child);
2354
+ if (needsRestore) {
2355
+ restoreClaudeSettings(backup);
2356
+ console.log("已恢复配置");
2357
+ }
2358
+ process.exit(exitCode);
2359
+ }
2360
+ async function runProvider(providerName, configureClaude, passthroughArgs = []) {
2361
+ const endpoint = getEndpointConfig(providerName);
2362
+ if (!endpoint) {
2363
+ console.error(`错误: 未找到 endpoint "${providerName}"`);
2364
+ console.log('使用 "cc-run list" 查看可用的 endpoints');
2365
+ process.exit(1);
2366
+ }
2367
+ let token = endpoint.token || getToken(providerName);
2368
+ if (!token) {
2369
+ token = await promptToken(providerName);
2370
+ saveToken(providerName, token);
2371
+ }
2372
+ setLastUsed(providerName);
2373
+ const proxyConfig = getProxyConfig();
2374
+ const proxyUrl = proxyConfig.enabled ? proxyConfig.url : undefined;
2375
+ const backup = backupClaudeSettings();
2376
+ let needsRestore = false;
2377
+ if (hasAnthropicEnv(backup)) {
2378
+ const forWrite = structuredClone(backup);
2379
+ clearAnthropicEnv(forWrite);
2380
+ writeClaudeSettings(forWrite);
2381
+ needsRestore = true;
2382
+ console.log("已临时清除 settings.json 中的 ANTHROPIC 配置");
2383
+ }
2384
+ if (needsRestore) {
2385
+ console.log("Claude 退出后将恢复配置...");
2386
+ }
2387
+ if (configureClaude) {
2388
+ setThirdPartyApi(endpoint.endpoint, token);
2389
+ console.log(`已配置原生 claude 命令使用 ${providerName}`);
2390
+ console.log('使用 "cc-run --claude" 可恢复官方配置');
2391
+ }
2392
+ const child = launchClaude({
2393
+ apiEndpoint: endpoint.endpoint,
2394
+ apiKey: token,
2395
+ proxyUrl,
2396
+ models: endpoint.models
2397
+ }, passthroughArgs);
2398
+ const exitCode = await waitForExit(child);
2399
+ if (needsRestore) {
2400
+ restoreClaudeSettings(backup);
2401
+ console.log("已恢复配置");
2402
+ }
2403
+ process.exit(exitCode);
2404
+ }
2405
+ function restoreOfficial(passthroughArgs = []) {
2406
+ removeThirdPartyApi();
2407
+ console.log("已恢复原生 claude 命令使用官方 endpoint");
2408
+ if (passthroughArgs.length > 0) {
2409
+ console.log("透传参数:", passthroughArgs);
2410
+ const child = launchOfficialClaude(undefined, passthroughArgs);
2411
+ waitForExit(child).then((exitCode) => process.exit(exitCode));
2412
+ }
2413
+ }
2414
+ function getEndpointConfig(name) {
2415
+ if (isBuiltinEndpoint(name)) {
2416
+ return getBuiltinEndpoint(name);
2417
+ }
2418
+ const custom = getCustomEndpoints();
2419
+ return custom.find((ep) => ep.name === name);
2420
+ }
2421
+ async function promptToken(providerName) {
2422
+ const rl = createInterface3({
2423
+ input: process.stdin,
2424
+ output: process.stdout
2425
+ });
2426
+ return new Promise((resolve) => {
2427
+ rl.question(`请输入 ${providerName} 的 API Token: `, (answer) => {
2428
+ rl.close();
2429
+ resolve(answer.trim());
2430
+ });
2431
+ });
2432
+ }
2433
+
2434
+ // src/utils/passthrough-args.ts
2435
+ class PassthroughArgsError extends Error {
2436
+ constructor(message) {
2437
+ super(message);
2438
+ this.name = "PassthroughArgsError";
2439
+ }
2440
+ }
2441
+ function extractPassthroughArgs(argv) {
2442
+ const userArgs = argv.slice(2);
2443
+ const dashIndex = userArgs.indexOf("--");
2444
+ if (dashIndex === -1) {
2445
+ return [];
2446
+ }
2447
+ return userArgs.slice(dashIndex + 1);
2448
+ }
2449
+ function validateDashPosition(argv) {
2450
+ const userArgs = argv.slice(2);
2451
+ const dashIndex = userArgs.indexOf("--");
2452
+ if (dashIndex === -1) {
2453
+ return;
2454
+ }
2455
+ if (dashIndex === 0) {
2456
+ throw new PassthroughArgsError("必须在 provider 名称或 --claude 选项之后");
2457
+ }
2458
+ const beforeDash = userArgs.slice(0, dashIndex);
2459
+ const hasValidPrefix = beforeDash.some((arg) => !arg.startsWith("-") || arg === "--claude");
2460
+ if (!hasValidPrefix) {
2461
+ throw new PassthroughArgsError("必须在 provider 名称或 --claude 选项之后");
2462
+ }
2463
+ }
2464
+
2465
+ // src/index.ts
2466
+ var program2 = new Command;
2467
+ program2.name("cc-run").description("Claude \u542F\u52A8\u5668 - \u652F\u6301\u5207\u6362\u4E0D\u540C\u7684 API endpoint").version("0.1.0");
2468
+ program2.command("list").description("\u5217\u51FA\u6240\u6709\u53EF\u7528\u7684 endpoints").action(list);
2469
+ program2.command("add").description("\u6DFB\u52A0\u81EA\u5B9A\u4E49 endpoint").argument("<name>", "endpoint \u540D\u79F0").argument("<endpoint>", "API \u5730\u5740").action(add);
2470
+ program2.command("remove").description("\u5220\u9664\u81EA\u5B9A\u4E49 endpoint").argument("<name>", "endpoint \u540D\u79F0").action(remove);
2471
+ var proxyCmd = program2.command("proxy").description("\u4EE3\u7406\u7BA1\u7406");
2472
+ proxyCmd.command("on").description("\u5F00\u542F\u4EE3\u7406").action(proxyOn);
2473
+ proxyCmd.command("off").description("\u5173\u95ED\u4EE3\u7406").action(proxyOff);
2474
+ proxyCmd.command("reset").description("\u91CD\u7F6E\u4EE3\u7406\u914D\u7F6E").action(proxyReset);
2475
+ proxyCmd.command("status").description("\u67E5\u770B\u4EE3\u7406\u72B6\u6001").action(proxyStatus);
2476
+ proxyCmd.command("help").description("\u4EE3\u7406\u5E2E\u52A9\u4FE1\u606F").action(proxyHelp);
2477
+ program2.argument("[provider]", "provider \u540D\u79F0 (glm, deepseek, minimax \u6216\u81EA\u5B9A\u4E49)").option("--claude", "\u914D\u7F6E\u539F\u751F claude \u547D\u4EE4").allowExcessArguments(true).action(async (provider, options) => {
2478
+ try {
2479
+ validateDashPosition(process.argv);
2480
+ const passthroughArgs = extractPassthroughArgs(process.argv);
2481
+ if (!provider) {
2482
+ if (options.claude) {
2483
+ restoreOfficial(passthroughArgs);
2484
+ } else {
2485
+ await runOfficial(passthroughArgs);
2486
+ }
2487
+ } else {
2488
+ await runProvider(provider, options.claude, passthroughArgs);
2489
+ }
2490
+ } catch (error) {
2491
+ if (error instanceof PassthroughArgsError) {
2492
+ console.error("\u274C \u53C2\u6570\u4F4D\u7F6E\u4E0D\u6B63\u786E");
2493
+ console.error("");
2494
+ console.error("\u6B63\u786E\u7684\u7528\u6CD5\u793A\u4F8B:");
2495
+ console.error(" cc-run glm -- <claude\u53C2\u6570> # \u4F7F\u7528 glm provider \u5E76\u900F\u4F20\u53C2\u6570");
2496
+ console.error(" cc-run --claude -- <\u53C2\u6570> # \u6062\u590D\u5B98\u65B9\u914D\u7F6E\u5E76\u900F\u4F20\u53C2\u6570");
2497
+ console.error(" cc-run glm --claude -- <\u53C2\u6570> # \u914D\u7F6E\u539F\u751F claude \u547D\u4EE4\u4F7F\u7528 glm");
2498
+ console.error("");
2499
+ console.error("\u8BF4\u660E: -- \u5206\u9694\u7B26\u7528\u4E8E\u5C06\u540E\u7EED\u53C2\u6570\u900F\u4F20\u7ED9 Claude CLI");
2500
+ process.exit(1);
2501
+ }
2502
+ throw error;
2503
+ }
2504
+ });
2505
+ program2.parse();