brch 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,3028 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // node_modules/commander/lib/error.js
23
+ var require_error = __commonJS((exports) => {
24
+ class CommanderError extends Error {
25
+ constructor(exitCode, code, message) {
26
+ super(message);
27
+ Error.captureStackTrace(this, this.constructor);
28
+ this.name = this.constructor.name;
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.nestedError = undefined;
32
+ }
33
+ }
34
+
35
+ class InvalidArgumentError extends CommanderError {
36
+ constructor(message) {
37
+ super(1, "commander.invalidArgument", message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
40
+ }
41
+ }
42
+ exports.CommanderError = CommanderError;
43
+ exports.InvalidArgumentError = InvalidArgumentError;
44
+ });
45
+
46
+ // node_modules/commander/lib/argument.js
47
+ var require_argument = __commonJS((exports) => {
48
+ var { InvalidArgumentError } = require_error();
49
+
50
+ class Argument {
51
+ constructor(name, description) {
52
+ this.description = description || "";
53
+ this.variadic = false;
54
+ this.parseArg = undefined;
55
+ this.defaultValue = undefined;
56
+ this.defaultValueDescription = undefined;
57
+ this.argChoices = undefined;
58
+ switch (name[0]) {
59
+ case "<":
60
+ this.required = true;
61
+ this._name = name.slice(1, -1);
62
+ break;
63
+ case "[":
64
+ this.required = false;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ default:
68
+ this.required = true;
69
+ this._name = name;
70
+ break;
71
+ }
72
+ if (this._name.endsWith("...")) {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
76
+ }
77
+ name() {
78
+ return this._name;
79
+ }
80
+ _collectValue(value, previous) {
81
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
82
+ return [value];
83
+ }
84
+ previous.push(value);
85
+ return previous;
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._collectValue(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.minWidthToWrap = 40;
134
+ this.sortSubcommands = false;
135
+ this.sortOptions = false;
136
+ this.showGlobalOptions = false;
137
+ }
138
+ prepareContext(contextOptions) {
139
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
140
+ }
141
+ visibleCommands(cmd) {
142
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
143
+ const helpCommand = cmd._getHelpCommand();
144
+ if (helpCommand && !helpCommand._hidden) {
145
+ visibleCommands.push(helpCommand);
146
+ }
147
+ if (this.sortSubcommands) {
148
+ visibleCommands.sort((a, b) => {
149
+ return a.name().localeCompare(b.name());
150
+ });
151
+ }
152
+ return visibleCommands;
153
+ }
154
+ compareOptions(a, b) {
155
+ const getSortKey = (option) => {
156
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
157
+ };
158
+ return getSortKey(a).localeCompare(getSortKey(b));
159
+ }
160
+ visibleOptions(cmd) {
161
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
162
+ const helpOption = cmd._getHelpOption();
163
+ if (helpOption && !helpOption.hidden) {
164
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
165
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
166
+ if (!removeShort && !removeLong) {
167
+ visibleOptions.push(helpOption);
168
+ } else if (helpOption.long && !removeLong) {
169
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
170
+ } else if (helpOption.short && !removeShort) {
171
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
172
+ }
173
+ }
174
+ if (this.sortOptions) {
175
+ visibleOptions.sort(this.compareOptions);
176
+ }
177
+ return visibleOptions;
178
+ }
179
+ visibleGlobalOptions(cmd) {
180
+ if (!this.showGlobalOptions)
181
+ return [];
182
+ const globalOptions = [];
183
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
184
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
185
+ globalOptions.push(...visibleOptions);
186
+ }
187
+ if (this.sortOptions) {
188
+ globalOptions.sort(this.compareOptions);
189
+ }
190
+ return globalOptions;
191
+ }
192
+ visibleArguments(cmd) {
193
+ if (cmd._argsDescription) {
194
+ cmd.registeredArguments.forEach((argument) => {
195
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
196
+ });
197
+ }
198
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
199
+ return cmd.registeredArguments;
200
+ }
201
+ return [];
202
+ }
203
+ subcommandTerm(cmd) {
204
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
205
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
206
+ }
207
+ optionTerm(option) {
208
+ return option.flags;
209
+ }
210
+ argumentTerm(argument) {
211
+ return argument.name();
212
+ }
213
+ longestSubcommandTermLength(cmd, helper) {
214
+ return helper.visibleCommands(cmd).reduce((max, command) => {
215
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
216
+ }, 0);
217
+ }
218
+ longestOptionTermLength(cmd, helper) {
219
+ return helper.visibleOptions(cmd).reduce((max, option) => {
220
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
221
+ }, 0);
222
+ }
223
+ longestGlobalOptionTermLength(cmd, helper) {
224
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
225
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
226
+ }, 0);
227
+ }
228
+ longestArgumentTermLength(cmd, helper) {
229
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
230
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
231
+ }, 0);
232
+ }
233
+ commandUsage(cmd) {
234
+ let cmdName = cmd._name;
235
+ if (cmd._aliases[0]) {
236
+ cmdName = cmdName + "|" + cmd._aliases[0];
237
+ }
238
+ let ancestorCmdNames = "";
239
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
240
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
241
+ }
242
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
243
+ }
244
+ commandDescription(cmd) {
245
+ return cmd.description();
246
+ }
247
+ subcommandDescription(cmd) {
248
+ return cmd.summary() || cmd.description();
249
+ }
250
+ optionDescription(option) {
251
+ const extraInfo = [];
252
+ if (option.argChoices) {
253
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
254
+ }
255
+ if (option.defaultValue !== undefined) {
256
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
257
+ if (showDefault) {
258
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
259
+ }
260
+ }
261
+ if (option.presetArg !== undefined && option.optional) {
262
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
263
+ }
264
+ if (option.envVar !== undefined) {
265
+ extraInfo.push(`env: ${option.envVar}`);
266
+ }
267
+ if (extraInfo.length > 0) {
268
+ const extraDescription = `(${extraInfo.join(", ")})`;
269
+ if (option.description) {
270
+ return `${option.description} ${extraDescription}`;
271
+ }
272
+ return extraDescription;
273
+ }
274
+ return option.description;
275
+ }
276
+ argumentDescription(argument) {
277
+ const extraInfo = [];
278
+ if (argument.argChoices) {
279
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
280
+ }
281
+ if (argument.defaultValue !== undefined) {
282
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
283
+ }
284
+ if (extraInfo.length > 0) {
285
+ const extraDescription = `(${extraInfo.join(", ")})`;
286
+ if (argument.description) {
287
+ return `${argument.description} ${extraDescription}`;
288
+ }
289
+ return extraDescription;
290
+ }
291
+ return argument.description;
292
+ }
293
+ formatItemList(heading, items, helper) {
294
+ if (items.length === 0)
295
+ return [];
296
+ return [helper.styleTitle(heading), ...items, ""];
297
+ }
298
+ groupItems(unsortedItems, visibleItems, getGroup) {
299
+ const result = new Map;
300
+ unsortedItems.forEach((item) => {
301
+ const group = getGroup(item);
302
+ if (!result.has(group))
303
+ result.set(group, []);
304
+ });
305
+ visibleItems.forEach((item) => {
306
+ const group = getGroup(item);
307
+ if (!result.has(group)) {
308
+ result.set(group, []);
309
+ }
310
+ result.get(group).push(item);
311
+ });
312
+ return result;
313
+ }
314
+ formatHelp(cmd, helper) {
315
+ const termWidth = helper.padWidth(cmd, helper);
316
+ const helpWidth = helper.helpWidth ?? 80;
317
+ function callFormatItem(term, description) {
318
+ return helper.formatItem(term, termWidth, description, helper);
319
+ }
320
+ let output = [
321
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
322
+ ""
323
+ ];
324
+ const commandDescription = helper.commandDescription(cmd);
325
+ if (commandDescription.length > 0) {
326
+ output = output.concat([
327
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
328
+ ""
329
+ ]);
330
+ }
331
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
332
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
333
+ });
334
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
335
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
336
+ optionGroups.forEach((options, group) => {
337
+ const optionList = options.map((option) => {
338
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
339
+ });
340
+ output = output.concat(this.formatItemList(group, optionList, helper));
341
+ });
342
+ if (helper.showGlobalOptions) {
343
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
344
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
345
+ });
346
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
347
+ }
348
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
349
+ commandGroups.forEach((commands, group) => {
350
+ const commandList = commands.map((sub) => {
351
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
352
+ });
353
+ output = output.concat(this.formatItemList(group, commandList, helper));
354
+ });
355
+ return output.join(`
356
+ `);
357
+ }
358
+ displayWidth(str) {
359
+ return stripColor(str).length;
360
+ }
361
+ styleTitle(str) {
362
+ return str;
363
+ }
364
+ styleUsage(str) {
365
+ return str.split(" ").map((word) => {
366
+ if (word === "[options]")
367
+ return this.styleOptionText(word);
368
+ if (word === "[command]")
369
+ return this.styleSubcommandText(word);
370
+ if (word[0] === "[" || word[0] === "<")
371
+ return this.styleArgumentText(word);
372
+ return this.styleCommandText(word);
373
+ }).join(" ");
374
+ }
375
+ styleCommandDescription(str) {
376
+ return this.styleDescriptionText(str);
377
+ }
378
+ styleOptionDescription(str) {
379
+ return this.styleDescriptionText(str);
380
+ }
381
+ styleSubcommandDescription(str) {
382
+ return this.styleDescriptionText(str);
383
+ }
384
+ styleArgumentDescription(str) {
385
+ return this.styleDescriptionText(str);
386
+ }
387
+ styleDescriptionText(str) {
388
+ return str;
389
+ }
390
+ styleOptionTerm(str) {
391
+ return this.styleOptionText(str);
392
+ }
393
+ styleSubcommandTerm(str) {
394
+ return str.split(" ").map((word) => {
395
+ if (word === "[options]")
396
+ return this.styleOptionText(word);
397
+ if (word[0] === "[" || word[0] === "<")
398
+ return this.styleArgumentText(word);
399
+ return this.styleSubcommandText(word);
400
+ }).join(" ");
401
+ }
402
+ styleArgumentTerm(str) {
403
+ return this.styleArgumentText(str);
404
+ }
405
+ styleOptionText(str) {
406
+ return str;
407
+ }
408
+ styleArgumentText(str) {
409
+ return str;
410
+ }
411
+ styleSubcommandText(str) {
412
+ return str;
413
+ }
414
+ styleCommandText(str) {
415
+ return str;
416
+ }
417
+ padWidth(cmd, helper) {
418
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
419
+ }
420
+ preformatted(str) {
421
+ return /\n[^\S\r\n]/.test(str);
422
+ }
423
+ formatItem(term, termWidth, description, helper) {
424
+ const itemIndent = 2;
425
+ const itemIndentStr = " ".repeat(itemIndent);
426
+ if (!description)
427
+ return itemIndentStr + term;
428
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
429
+ const spacerWidth = 2;
430
+ const helpWidth = this.helpWidth ?? 80;
431
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
432
+ let formattedDescription;
433
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
434
+ formattedDescription = description;
435
+ } else {
436
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
437
+ formattedDescription = wrappedDescription.replace(/\n/g, `
438
+ ` + " ".repeat(termWidth + spacerWidth));
439
+ }
440
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
441
+ ${itemIndentStr}`);
442
+ }
443
+ boxWrap(str, width) {
444
+ if (width < this.minWidthToWrap)
445
+ return str;
446
+ const rawLines = str.split(/\r\n|\n/);
447
+ const chunkPattern = /[\s]*[^\s]+/g;
448
+ const wrappedLines = [];
449
+ rawLines.forEach((line) => {
450
+ const chunks = line.match(chunkPattern);
451
+ if (chunks === null) {
452
+ wrappedLines.push("");
453
+ return;
454
+ }
455
+ let sumChunks = [chunks.shift()];
456
+ let sumWidth = this.displayWidth(sumChunks[0]);
457
+ chunks.forEach((chunk) => {
458
+ const visibleWidth = this.displayWidth(chunk);
459
+ if (sumWidth + visibleWidth <= width) {
460
+ sumChunks.push(chunk);
461
+ sumWidth += visibleWidth;
462
+ return;
463
+ }
464
+ wrappedLines.push(sumChunks.join(""));
465
+ const nextChunk = chunk.trimStart();
466
+ sumChunks = [nextChunk];
467
+ sumWidth = this.displayWidth(nextChunk);
468
+ });
469
+ wrappedLines.push(sumChunks.join(""));
470
+ });
471
+ return wrappedLines.join(`
472
+ `);
473
+ }
474
+ }
475
+ function stripColor(str) {
476
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
477
+ return str.replace(sgrPattern, "");
478
+ }
479
+ exports.Help = Help;
480
+ exports.stripColor = stripColor;
481
+ });
482
+
483
+ // node_modules/commander/lib/option.js
484
+ var require_option = __commonJS((exports) => {
485
+ var { InvalidArgumentError } = require_error();
486
+
487
+ class Option {
488
+ constructor(flags, description) {
489
+ this.flags = flags;
490
+ this.description = description || "";
491
+ this.required = flags.includes("<");
492
+ this.optional = flags.includes("[");
493
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
494
+ this.mandatory = false;
495
+ const optionFlags = splitOptionFlags(flags);
496
+ this.short = optionFlags.shortFlag;
497
+ this.long = optionFlags.longFlag;
498
+ this.negate = false;
499
+ if (this.long) {
500
+ this.negate = this.long.startsWith("--no-");
501
+ }
502
+ this.defaultValue = undefined;
503
+ this.defaultValueDescription = undefined;
504
+ this.presetArg = undefined;
505
+ this.envVar = undefined;
506
+ this.parseArg = undefined;
507
+ this.hidden = false;
508
+ this.argChoices = undefined;
509
+ this.conflictsWith = [];
510
+ this.implied = undefined;
511
+ this.helpGroupHeading = undefined;
512
+ }
513
+ default(value, description) {
514
+ this.defaultValue = value;
515
+ this.defaultValueDescription = description;
516
+ return this;
517
+ }
518
+ preset(arg) {
519
+ this.presetArg = arg;
520
+ return this;
521
+ }
522
+ conflicts(names) {
523
+ this.conflictsWith = this.conflictsWith.concat(names);
524
+ return this;
525
+ }
526
+ implies(impliedOptionValues) {
527
+ let newImplied = impliedOptionValues;
528
+ if (typeof impliedOptionValues === "string") {
529
+ newImplied = { [impliedOptionValues]: true };
530
+ }
531
+ this.implied = Object.assign(this.implied || {}, newImplied);
532
+ return this;
533
+ }
534
+ env(name) {
535
+ this.envVar = name;
536
+ return this;
537
+ }
538
+ argParser(fn) {
539
+ this.parseArg = fn;
540
+ return this;
541
+ }
542
+ makeOptionMandatory(mandatory = true) {
543
+ this.mandatory = !!mandatory;
544
+ return this;
545
+ }
546
+ hideHelp(hide = true) {
547
+ this.hidden = !!hide;
548
+ return this;
549
+ }
550
+ _collectValue(value, previous) {
551
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
552
+ return [value];
553
+ }
554
+ previous.push(value);
555
+ return previous;
556
+ }
557
+ choices(values) {
558
+ this.argChoices = values.slice();
559
+ this.parseArg = (arg, previous) => {
560
+ if (!this.argChoices.includes(arg)) {
561
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
562
+ }
563
+ if (this.variadic) {
564
+ return this._collectValue(arg, previous);
565
+ }
566
+ return arg;
567
+ };
568
+ return this;
569
+ }
570
+ name() {
571
+ if (this.long) {
572
+ return this.long.replace(/^--/, "");
573
+ }
574
+ return this.short.replace(/^-/, "");
575
+ }
576
+ attributeName() {
577
+ if (this.negate) {
578
+ return camelcase(this.name().replace(/^no-/, ""));
579
+ }
580
+ return camelcase(this.name());
581
+ }
582
+ helpGroup(heading) {
583
+ this.helpGroupHeading = heading;
584
+ return this;
585
+ }
586
+ is(arg) {
587
+ return this.short === arg || this.long === arg;
588
+ }
589
+ isBoolean() {
590
+ return !this.required && !this.optional && !this.negate;
591
+ }
592
+ }
593
+
594
+ class DualOptions {
595
+ constructor(options) {
596
+ this.positiveOptions = new Map;
597
+ this.negativeOptions = new Map;
598
+ this.dualOptions = new Set;
599
+ options.forEach((option) => {
600
+ if (option.negate) {
601
+ this.negativeOptions.set(option.attributeName(), option);
602
+ } else {
603
+ this.positiveOptions.set(option.attributeName(), option);
604
+ }
605
+ });
606
+ this.negativeOptions.forEach((value, key) => {
607
+ if (this.positiveOptions.has(key)) {
608
+ this.dualOptions.add(key);
609
+ }
610
+ });
611
+ }
612
+ valueFromOption(value, option) {
613
+ const optionKey = option.attributeName();
614
+ if (!this.dualOptions.has(optionKey))
615
+ return true;
616
+ const preset = this.negativeOptions.get(optionKey).presetArg;
617
+ const negativeValue = preset !== undefined ? preset : false;
618
+ return option.negate === (negativeValue === value);
619
+ }
620
+ }
621
+ function camelcase(str) {
622
+ return str.split("-").reduce((str2, word) => {
623
+ return str2 + word[0].toUpperCase() + word.slice(1);
624
+ });
625
+ }
626
+ function splitOptionFlags(flags) {
627
+ let shortFlag;
628
+ let longFlag;
629
+ const shortFlagExp = /^-[^-]$/;
630
+ const longFlagExp = /^--[^-]/;
631
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
632
+ if (shortFlagExp.test(flagParts[0]))
633
+ shortFlag = flagParts.shift();
634
+ if (longFlagExp.test(flagParts[0]))
635
+ longFlag = flagParts.shift();
636
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
637
+ shortFlag = flagParts.shift();
638
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
639
+ shortFlag = longFlag;
640
+ longFlag = flagParts.shift();
641
+ }
642
+ if (flagParts[0].startsWith("-")) {
643
+ const unsupportedFlag = flagParts[0];
644
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
645
+ if (/^-[^-][^-]/.test(unsupportedFlag))
646
+ throw new Error(`${baseError}
647
+ - a short flag is a single dash and a single character
648
+ - either use a single dash and a single character (for a short flag)
649
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
650
+ if (shortFlagExp.test(unsupportedFlag))
651
+ throw new Error(`${baseError}
652
+ - too many short flags`);
653
+ if (longFlagExp.test(unsupportedFlag))
654
+ throw new Error(`${baseError}
655
+ - too many long flags`);
656
+ throw new Error(`${baseError}
657
+ - unrecognised flag format`);
658
+ }
659
+ if (shortFlag === undefined && longFlag === undefined)
660
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
661
+ return { shortFlag, longFlag };
662
+ }
663
+ exports.Option = Option;
664
+ exports.DualOptions = DualOptions;
665
+ });
666
+
667
+ // node_modules/commander/lib/suggestSimilar.js
668
+ var require_suggestSimilar = __commonJS((exports) => {
669
+ var maxDistance = 3;
670
+ function editDistance(a, b) {
671
+ if (Math.abs(a.length - b.length) > maxDistance)
672
+ return Math.max(a.length, b.length);
673
+ const d = [];
674
+ for (let i = 0;i <= a.length; i++) {
675
+ d[i] = [i];
676
+ }
677
+ for (let j = 0;j <= b.length; j++) {
678
+ d[0][j] = j;
679
+ }
680
+ for (let j = 1;j <= b.length; j++) {
681
+ for (let i = 1;i <= a.length; i++) {
682
+ let cost = 1;
683
+ if (a[i - 1] === b[j - 1]) {
684
+ cost = 0;
685
+ } else {
686
+ cost = 1;
687
+ }
688
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
689
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
690
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
691
+ }
692
+ }
693
+ }
694
+ return d[a.length][b.length];
695
+ }
696
+ function suggestSimilar(word, candidates) {
697
+ if (!candidates || candidates.length === 0)
698
+ return "";
699
+ candidates = Array.from(new Set(candidates));
700
+ const searchingOptions = word.startsWith("--");
701
+ if (searchingOptions) {
702
+ word = word.slice(2);
703
+ candidates = candidates.map((candidate) => candidate.slice(2));
704
+ }
705
+ let similar = [];
706
+ let bestDistance = maxDistance;
707
+ const minSimilarity = 0.4;
708
+ candidates.forEach((candidate) => {
709
+ if (candidate.length <= 1)
710
+ return;
711
+ const distance = editDistance(word, candidate);
712
+ const length = Math.max(word.length, candidate.length);
713
+ const similarity = (length - distance) / length;
714
+ if (similarity > minSimilarity) {
715
+ if (distance < bestDistance) {
716
+ bestDistance = distance;
717
+ similar = [candidate];
718
+ } else if (distance === bestDistance) {
719
+ similar.push(candidate);
720
+ }
721
+ }
722
+ });
723
+ similar.sort((a, b) => a.localeCompare(b));
724
+ if (searchingOptions) {
725
+ similar = similar.map((candidate) => `--${candidate}`);
726
+ }
727
+ if (similar.length > 1) {
728
+ return `
729
+ (Did you mean one of ${similar.join(", ")}?)`;
730
+ }
731
+ if (similar.length === 1) {
732
+ return `
733
+ (Did you mean ${similar[0]}?)`;
734
+ }
735
+ return "";
736
+ }
737
+ exports.suggestSimilar = suggestSimilar;
738
+ });
739
+
740
+ // node_modules/commander/lib/command.js
741
+ var require_command = __commonJS((exports) => {
742
+ var EventEmitter = __require("node:events").EventEmitter;
743
+ var childProcess = __require("node:child_process");
744
+ var path = __require("node:path");
745
+ var fs = __require("node:fs");
746
+ var process2 = __require("node:process");
747
+ var { Argument, humanReadableArgName } = require_argument();
748
+ var { CommanderError } = require_error();
749
+ var { Help, stripColor } = require_help();
750
+ var { Option, DualOptions } = require_option();
751
+ var { suggestSimilar } = require_suggestSimilar();
752
+
753
+ class Command extends EventEmitter {
754
+ constructor(name) {
755
+ super();
756
+ this.commands = [];
757
+ this.options = [];
758
+ this.parent = null;
759
+ this._allowUnknownOption = false;
760
+ this._allowExcessArguments = false;
761
+ this.registeredArguments = [];
762
+ this._args = this.registeredArguments;
763
+ this.args = [];
764
+ this.rawArgs = [];
765
+ this.processedArgs = [];
766
+ this._scriptPath = null;
767
+ this._name = name || "";
768
+ this._optionValues = {};
769
+ this._optionValueSources = {};
770
+ this._storeOptionsAsProperties = false;
771
+ this._actionHandler = null;
772
+ this._executableHandler = false;
773
+ this._executableFile = null;
774
+ this._executableDir = null;
775
+ this._defaultCommandName = null;
776
+ this._exitCallback = null;
777
+ this._aliases = [];
778
+ this._combineFlagAndOptionalValue = true;
779
+ this._description = "";
780
+ this._summary = "";
781
+ this._argsDescription = undefined;
782
+ this._enablePositionalOptions = false;
783
+ this._passThroughOptions = false;
784
+ this._lifeCycleHooks = {};
785
+ this._showHelpAfterError = false;
786
+ this._showSuggestionAfterError = true;
787
+ this._savedState = null;
788
+ this._outputConfiguration = {
789
+ writeOut: (str) => process2.stdout.write(str),
790
+ writeErr: (str) => process2.stderr.write(str),
791
+ outputError: (str, write) => write(str),
792
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
793
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
794
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
795
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
796
+ stripColor: (str) => stripColor(str)
797
+ };
798
+ this._hidden = false;
799
+ this._helpOption = undefined;
800
+ this._addImplicitHelpCommand = undefined;
801
+ this._helpCommand = undefined;
802
+ this._helpConfiguration = {};
803
+ this._helpGroupHeading = undefined;
804
+ this._defaultCommandGroup = undefined;
805
+ this._defaultOptionGroup = undefined;
806
+ }
807
+ copyInheritedSettings(sourceCommand) {
808
+ this._outputConfiguration = sourceCommand._outputConfiguration;
809
+ this._helpOption = sourceCommand._helpOption;
810
+ this._helpCommand = sourceCommand._helpCommand;
811
+ this._helpConfiguration = sourceCommand._helpConfiguration;
812
+ this._exitCallback = sourceCommand._exitCallback;
813
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
814
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
815
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
816
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
817
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
818
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
819
+ return this;
820
+ }
821
+ _getCommandAndAncestors() {
822
+ const result = [];
823
+ for (let command = this;command; command = command.parent) {
824
+ result.push(command);
825
+ }
826
+ return result;
827
+ }
828
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
829
+ let desc = actionOptsOrExecDesc;
830
+ let opts = execOpts;
831
+ if (typeof desc === "object" && desc !== null) {
832
+ opts = desc;
833
+ desc = null;
834
+ }
835
+ opts = opts || {};
836
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
837
+ const cmd = this.createCommand(name);
838
+ if (desc) {
839
+ cmd.description(desc);
840
+ cmd._executableHandler = true;
841
+ }
842
+ if (opts.isDefault)
843
+ this._defaultCommandName = cmd._name;
844
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
845
+ cmd._executableFile = opts.executableFile || null;
846
+ if (args)
847
+ cmd.arguments(args);
848
+ this._registerCommand(cmd);
849
+ cmd.parent = this;
850
+ cmd.copyInheritedSettings(this);
851
+ if (desc)
852
+ return this;
853
+ return cmd;
854
+ }
855
+ createCommand(name) {
856
+ return new Command(name);
857
+ }
858
+ createHelp() {
859
+ return Object.assign(new Help, this.configureHelp());
860
+ }
861
+ configureHelp(configuration) {
862
+ if (configuration === undefined)
863
+ return this._helpConfiguration;
864
+ this._helpConfiguration = configuration;
865
+ return this;
866
+ }
867
+ configureOutput(configuration) {
868
+ if (configuration === undefined)
869
+ return this._outputConfiguration;
870
+ this._outputConfiguration = {
871
+ ...this._outputConfiguration,
872
+ ...configuration
873
+ };
874
+ return this;
875
+ }
876
+ showHelpAfterError(displayHelp = true) {
877
+ if (typeof displayHelp !== "string")
878
+ displayHelp = !!displayHelp;
879
+ this._showHelpAfterError = displayHelp;
880
+ return this;
881
+ }
882
+ showSuggestionAfterError(displaySuggestion = true) {
883
+ this._showSuggestionAfterError = !!displaySuggestion;
884
+ return this;
885
+ }
886
+ addCommand(cmd, opts) {
887
+ if (!cmd._name) {
888
+ throw new Error(`Command passed to .addCommand() must have a name
889
+ - specify the name in Command constructor or using .name()`);
890
+ }
891
+ opts = opts || {};
892
+ if (opts.isDefault)
893
+ this._defaultCommandName = cmd._name;
894
+ if (opts.noHelp || opts.hidden)
895
+ cmd._hidden = true;
896
+ this._registerCommand(cmd);
897
+ cmd.parent = this;
898
+ cmd._checkForBrokenPassThrough();
899
+ return this;
900
+ }
901
+ createArgument(name, description) {
902
+ return new Argument(name, description);
903
+ }
904
+ argument(name, description, parseArg, defaultValue) {
905
+ const argument = this.createArgument(name, description);
906
+ if (typeof parseArg === "function") {
907
+ argument.default(defaultValue).argParser(parseArg);
908
+ } else {
909
+ argument.default(parseArg);
910
+ }
911
+ this.addArgument(argument);
912
+ return this;
913
+ }
914
+ arguments(names) {
915
+ names.trim().split(/ +/).forEach((detail) => {
916
+ this.argument(detail);
917
+ });
918
+ return this;
919
+ }
920
+ addArgument(argument) {
921
+ const previousArgument = this.registeredArguments.slice(-1)[0];
922
+ if (previousArgument?.variadic) {
923
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
924
+ }
925
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
926
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
927
+ }
928
+ this.registeredArguments.push(argument);
929
+ return this;
930
+ }
931
+ helpCommand(enableOrNameAndArgs, description) {
932
+ if (typeof enableOrNameAndArgs === "boolean") {
933
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
934
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
935
+ this._initCommandGroup(this._getHelpCommand());
936
+ }
937
+ return this;
938
+ }
939
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
940
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
941
+ const helpDescription = description ?? "display help for command";
942
+ const helpCommand = this.createCommand(helpName);
943
+ helpCommand.helpOption(false);
944
+ if (helpArgs)
945
+ helpCommand.arguments(helpArgs);
946
+ if (helpDescription)
947
+ helpCommand.description(helpDescription);
948
+ this._addImplicitHelpCommand = true;
949
+ this._helpCommand = helpCommand;
950
+ if (enableOrNameAndArgs || description)
951
+ this._initCommandGroup(helpCommand);
952
+ return this;
953
+ }
954
+ addHelpCommand(helpCommand, deprecatedDescription) {
955
+ if (typeof helpCommand !== "object") {
956
+ this.helpCommand(helpCommand, deprecatedDescription);
957
+ return this;
958
+ }
959
+ this._addImplicitHelpCommand = true;
960
+ this._helpCommand = helpCommand;
961
+ this._initCommandGroup(helpCommand);
962
+ return this;
963
+ }
964
+ _getHelpCommand() {
965
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
966
+ if (hasImplicitHelpCommand) {
967
+ if (this._helpCommand === undefined) {
968
+ this.helpCommand(undefined, undefined);
969
+ }
970
+ return this._helpCommand;
971
+ }
972
+ return null;
973
+ }
974
+ hook(event, listener) {
975
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
976
+ if (!allowedValues.includes(event)) {
977
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
978
+ Expecting one of '${allowedValues.join("', '")}'`);
979
+ }
980
+ if (this._lifeCycleHooks[event]) {
981
+ this._lifeCycleHooks[event].push(listener);
982
+ } else {
983
+ this._lifeCycleHooks[event] = [listener];
984
+ }
985
+ return this;
986
+ }
987
+ exitOverride(fn) {
988
+ if (fn) {
989
+ this._exitCallback = fn;
990
+ } else {
991
+ this._exitCallback = (err) => {
992
+ if (err.code !== "commander.executeSubCommandAsync") {
993
+ throw err;
994
+ } else {}
995
+ };
996
+ }
997
+ return this;
998
+ }
999
+ _exit(exitCode, code, message) {
1000
+ if (this._exitCallback) {
1001
+ this._exitCallback(new CommanderError(exitCode, code, message));
1002
+ }
1003
+ process2.exit(exitCode);
1004
+ }
1005
+ action(fn) {
1006
+ const listener = (args) => {
1007
+ const expectedArgsCount = this.registeredArguments.length;
1008
+ const actionArgs = args.slice(0, expectedArgsCount);
1009
+ if (this._storeOptionsAsProperties) {
1010
+ actionArgs[expectedArgsCount] = this;
1011
+ } else {
1012
+ actionArgs[expectedArgsCount] = this.opts();
1013
+ }
1014
+ actionArgs.push(this);
1015
+ return fn.apply(this, actionArgs);
1016
+ };
1017
+ this._actionHandler = listener;
1018
+ return this;
1019
+ }
1020
+ createOption(flags, description) {
1021
+ return new Option(flags, description);
1022
+ }
1023
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1024
+ try {
1025
+ return target.parseArg(value, previous);
1026
+ } catch (err) {
1027
+ if (err.code === "commander.invalidArgument") {
1028
+ const message = `${invalidArgumentMessage} ${err.message}`;
1029
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1030
+ }
1031
+ throw err;
1032
+ }
1033
+ }
1034
+ _registerOption(option) {
1035
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1036
+ if (matchingOption) {
1037
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1038
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1039
+ - already used by option '${matchingOption.flags}'`);
1040
+ }
1041
+ this._initOptionGroup(option);
1042
+ this.options.push(option);
1043
+ }
1044
+ _registerCommand(command) {
1045
+ const knownBy = (cmd) => {
1046
+ return [cmd.name()].concat(cmd.aliases());
1047
+ };
1048
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1049
+ if (alreadyUsed) {
1050
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1051
+ const newCmd = knownBy(command).join("|");
1052
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1053
+ }
1054
+ this._initCommandGroup(command);
1055
+ this.commands.push(command);
1056
+ }
1057
+ addOption(option) {
1058
+ this._registerOption(option);
1059
+ const oname = option.name();
1060
+ const name = option.attributeName();
1061
+ if (option.negate) {
1062
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1063
+ if (!this._findOption(positiveLongFlag)) {
1064
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1065
+ }
1066
+ } else if (option.defaultValue !== undefined) {
1067
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1068
+ }
1069
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1070
+ if (val == null && option.presetArg !== undefined) {
1071
+ val = option.presetArg;
1072
+ }
1073
+ const oldValue = this.getOptionValue(name);
1074
+ if (val !== null && option.parseArg) {
1075
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1076
+ } else if (val !== null && option.variadic) {
1077
+ val = option._collectValue(val, oldValue);
1078
+ }
1079
+ if (val == null) {
1080
+ if (option.negate) {
1081
+ val = false;
1082
+ } else if (option.isBoolean() || option.optional) {
1083
+ val = true;
1084
+ } else {
1085
+ val = "";
1086
+ }
1087
+ }
1088
+ this.setOptionValueWithSource(name, val, valueSource);
1089
+ };
1090
+ this.on("option:" + oname, (val) => {
1091
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1092
+ handleOptionValue(val, invalidValueMessage, "cli");
1093
+ });
1094
+ if (option.envVar) {
1095
+ this.on("optionEnv:" + oname, (val) => {
1096
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1097
+ handleOptionValue(val, invalidValueMessage, "env");
1098
+ });
1099
+ }
1100
+ return this;
1101
+ }
1102
+ _optionEx(config, flags, description, fn, defaultValue) {
1103
+ if (typeof flags === "object" && flags instanceof Option) {
1104
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1105
+ }
1106
+ const option = this.createOption(flags, description);
1107
+ option.makeOptionMandatory(!!config.mandatory);
1108
+ if (typeof fn === "function") {
1109
+ option.default(defaultValue).argParser(fn);
1110
+ } else if (fn instanceof RegExp) {
1111
+ const regex = fn;
1112
+ fn = (val, def) => {
1113
+ const m = regex.exec(val);
1114
+ return m ? m[0] : def;
1115
+ };
1116
+ option.default(defaultValue).argParser(fn);
1117
+ } else {
1118
+ option.default(fn);
1119
+ }
1120
+ return this.addOption(option);
1121
+ }
1122
+ option(flags, description, parseArg, defaultValue) {
1123
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1124
+ }
1125
+ requiredOption(flags, description, parseArg, defaultValue) {
1126
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1127
+ }
1128
+ combineFlagAndOptionalValue(combine = true) {
1129
+ this._combineFlagAndOptionalValue = !!combine;
1130
+ return this;
1131
+ }
1132
+ allowUnknownOption(allowUnknown = true) {
1133
+ this._allowUnknownOption = !!allowUnknown;
1134
+ return this;
1135
+ }
1136
+ allowExcessArguments(allowExcess = true) {
1137
+ this._allowExcessArguments = !!allowExcess;
1138
+ return this;
1139
+ }
1140
+ enablePositionalOptions(positional = true) {
1141
+ this._enablePositionalOptions = !!positional;
1142
+ return this;
1143
+ }
1144
+ passThroughOptions(passThrough = true) {
1145
+ this._passThroughOptions = !!passThrough;
1146
+ this._checkForBrokenPassThrough();
1147
+ return this;
1148
+ }
1149
+ _checkForBrokenPassThrough() {
1150
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1151
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1152
+ }
1153
+ }
1154
+ storeOptionsAsProperties(storeAsProperties = true) {
1155
+ if (this.options.length) {
1156
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1157
+ }
1158
+ if (Object.keys(this._optionValues).length) {
1159
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1160
+ }
1161
+ this._storeOptionsAsProperties = !!storeAsProperties;
1162
+ return this;
1163
+ }
1164
+ getOptionValue(key) {
1165
+ if (this._storeOptionsAsProperties) {
1166
+ return this[key];
1167
+ }
1168
+ return this._optionValues[key];
1169
+ }
1170
+ setOptionValue(key, value) {
1171
+ return this.setOptionValueWithSource(key, value, undefined);
1172
+ }
1173
+ setOptionValueWithSource(key, value, source) {
1174
+ if (this._storeOptionsAsProperties) {
1175
+ this[key] = value;
1176
+ } else {
1177
+ this._optionValues[key] = value;
1178
+ }
1179
+ this._optionValueSources[key] = source;
1180
+ return this;
1181
+ }
1182
+ getOptionValueSource(key) {
1183
+ return this._optionValueSources[key];
1184
+ }
1185
+ getOptionValueSourceWithGlobals(key) {
1186
+ let source;
1187
+ this._getCommandAndAncestors().forEach((cmd) => {
1188
+ if (cmd.getOptionValueSource(key) !== undefined) {
1189
+ source = cmd.getOptionValueSource(key);
1190
+ }
1191
+ });
1192
+ return source;
1193
+ }
1194
+ _prepareUserArgs(argv, parseOptions) {
1195
+ if (argv !== undefined && !Array.isArray(argv)) {
1196
+ throw new Error("first parameter to parse must be array or undefined");
1197
+ }
1198
+ parseOptions = parseOptions || {};
1199
+ if (argv === undefined && parseOptions.from === undefined) {
1200
+ if (process2.versions?.electron) {
1201
+ parseOptions.from = "electron";
1202
+ }
1203
+ const execArgv = process2.execArgv ?? [];
1204
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1205
+ parseOptions.from = "eval";
1206
+ }
1207
+ }
1208
+ if (argv === undefined) {
1209
+ argv = process2.argv;
1210
+ }
1211
+ this.rawArgs = argv.slice();
1212
+ let userArgs;
1213
+ switch (parseOptions.from) {
1214
+ case undefined:
1215
+ case "node":
1216
+ this._scriptPath = argv[1];
1217
+ userArgs = argv.slice(2);
1218
+ break;
1219
+ case "electron":
1220
+ if (process2.defaultApp) {
1221
+ this._scriptPath = argv[1];
1222
+ userArgs = argv.slice(2);
1223
+ } else {
1224
+ userArgs = argv.slice(1);
1225
+ }
1226
+ break;
1227
+ case "user":
1228
+ userArgs = argv.slice(0);
1229
+ break;
1230
+ case "eval":
1231
+ userArgs = argv.slice(1);
1232
+ break;
1233
+ default:
1234
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1235
+ }
1236
+ if (!this._name && this._scriptPath)
1237
+ this.nameFromFilename(this._scriptPath);
1238
+ this._name = this._name || "program";
1239
+ return userArgs;
1240
+ }
1241
+ parse(argv, parseOptions) {
1242
+ this._prepareForParse();
1243
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1244
+ this._parseCommand([], userArgs);
1245
+ return this;
1246
+ }
1247
+ async parseAsync(argv, parseOptions) {
1248
+ this._prepareForParse();
1249
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1250
+ await this._parseCommand([], userArgs);
1251
+ return this;
1252
+ }
1253
+ _prepareForParse() {
1254
+ if (this._savedState === null) {
1255
+ this.saveStateBeforeParse();
1256
+ } else {
1257
+ this.restoreStateBeforeParse();
1258
+ }
1259
+ }
1260
+ saveStateBeforeParse() {
1261
+ this._savedState = {
1262
+ _name: this._name,
1263
+ _optionValues: { ...this._optionValues },
1264
+ _optionValueSources: { ...this._optionValueSources }
1265
+ };
1266
+ }
1267
+ restoreStateBeforeParse() {
1268
+ if (this._storeOptionsAsProperties)
1269
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1270
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1271
+ this._name = this._savedState._name;
1272
+ this._scriptPath = null;
1273
+ this.rawArgs = [];
1274
+ this._optionValues = { ...this._savedState._optionValues };
1275
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1276
+ this.args = [];
1277
+ this.processedArgs = [];
1278
+ }
1279
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1280
+ if (fs.existsSync(executableFile))
1281
+ return;
1282
+ 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";
1283
+ const executableMissing = `'${executableFile}' does not exist
1284
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1285
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1286
+ - ${executableDirMessage}`;
1287
+ throw new Error(executableMissing);
1288
+ }
1289
+ _executeSubCommand(subcommand, args) {
1290
+ args = args.slice();
1291
+ let launchWithNode = false;
1292
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1293
+ function findFile(baseDir, baseName) {
1294
+ const localBin = path.resolve(baseDir, baseName);
1295
+ if (fs.existsSync(localBin))
1296
+ return localBin;
1297
+ if (sourceExt.includes(path.extname(baseName)))
1298
+ return;
1299
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1300
+ if (foundExt)
1301
+ return `${localBin}${foundExt}`;
1302
+ return;
1303
+ }
1304
+ this._checkForMissingMandatoryOptions();
1305
+ this._checkForConflictingOptions();
1306
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1307
+ let executableDir = this._executableDir || "";
1308
+ if (this._scriptPath) {
1309
+ let resolvedScriptPath;
1310
+ try {
1311
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1312
+ } catch {
1313
+ resolvedScriptPath = this._scriptPath;
1314
+ }
1315
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1316
+ }
1317
+ if (executableDir) {
1318
+ let localFile = findFile(executableDir, executableFile);
1319
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1320
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1321
+ if (legacyName !== this._name) {
1322
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1323
+ }
1324
+ }
1325
+ executableFile = localFile || executableFile;
1326
+ }
1327
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1328
+ let proc;
1329
+ if (process2.platform !== "win32") {
1330
+ if (launchWithNode) {
1331
+ args.unshift(executableFile);
1332
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1333
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1334
+ } else {
1335
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1336
+ }
1337
+ } else {
1338
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1339
+ args.unshift(executableFile);
1340
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1341
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1342
+ }
1343
+ if (!proc.killed) {
1344
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1345
+ signals.forEach((signal) => {
1346
+ process2.on(signal, () => {
1347
+ if (proc.killed === false && proc.exitCode === null) {
1348
+ proc.kill(signal);
1349
+ }
1350
+ });
1351
+ });
1352
+ }
1353
+ const exitCallback = this._exitCallback;
1354
+ proc.on("close", (code) => {
1355
+ code = code ?? 1;
1356
+ if (!exitCallback) {
1357
+ process2.exit(code);
1358
+ } else {
1359
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1360
+ }
1361
+ });
1362
+ proc.on("error", (err) => {
1363
+ if (err.code === "ENOENT") {
1364
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1365
+ } else if (err.code === "EACCES") {
1366
+ throw new Error(`'${executableFile}' not executable`);
1367
+ }
1368
+ if (!exitCallback) {
1369
+ process2.exit(1);
1370
+ } else {
1371
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1372
+ wrappedError.nestedError = err;
1373
+ exitCallback(wrappedError);
1374
+ }
1375
+ });
1376
+ this.runningCommand = proc;
1377
+ }
1378
+ _dispatchSubcommand(commandName, operands, unknown) {
1379
+ const subCommand = this._findCommand(commandName);
1380
+ if (!subCommand)
1381
+ this.help({ error: true });
1382
+ subCommand._prepareForParse();
1383
+ let promiseChain;
1384
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1385
+ promiseChain = this._chainOrCall(promiseChain, () => {
1386
+ if (subCommand._executableHandler) {
1387
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1388
+ } else {
1389
+ return subCommand._parseCommand(operands, unknown);
1390
+ }
1391
+ });
1392
+ return promiseChain;
1393
+ }
1394
+ _dispatchHelpCommand(subcommandName) {
1395
+ if (!subcommandName) {
1396
+ this.help();
1397
+ }
1398
+ const subCommand = this._findCommand(subcommandName);
1399
+ if (subCommand && !subCommand._executableHandler) {
1400
+ subCommand.help();
1401
+ }
1402
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1403
+ }
1404
+ _checkNumberOfArguments() {
1405
+ this.registeredArguments.forEach((arg, i) => {
1406
+ if (arg.required && this.args[i] == null) {
1407
+ this.missingArgument(arg.name());
1408
+ }
1409
+ });
1410
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1411
+ return;
1412
+ }
1413
+ if (this.args.length > this.registeredArguments.length) {
1414
+ this._excessArguments(this.args);
1415
+ }
1416
+ }
1417
+ _processArguments() {
1418
+ const myParseArg = (argument, value, previous) => {
1419
+ let parsedValue = value;
1420
+ if (value !== null && argument.parseArg) {
1421
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1422
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1423
+ }
1424
+ return parsedValue;
1425
+ };
1426
+ this._checkNumberOfArguments();
1427
+ const processedArgs = [];
1428
+ this.registeredArguments.forEach((declaredArg, index) => {
1429
+ let value = declaredArg.defaultValue;
1430
+ if (declaredArg.variadic) {
1431
+ if (index < this.args.length) {
1432
+ value = this.args.slice(index);
1433
+ if (declaredArg.parseArg) {
1434
+ value = value.reduce((processed, v) => {
1435
+ return myParseArg(declaredArg, v, processed);
1436
+ }, declaredArg.defaultValue);
1437
+ }
1438
+ } else if (value === undefined) {
1439
+ value = [];
1440
+ }
1441
+ } else if (index < this.args.length) {
1442
+ value = this.args[index];
1443
+ if (declaredArg.parseArg) {
1444
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1445
+ }
1446
+ }
1447
+ processedArgs[index] = value;
1448
+ });
1449
+ this.processedArgs = processedArgs;
1450
+ }
1451
+ _chainOrCall(promise, fn) {
1452
+ if (promise?.then && typeof promise.then === "function") {
1453
+ return promise.then(() => fn());
1454
+ }
1455
+ return fn();
1456
+ }
1457
+ _chainOrCallHooks(promise, event) {
1458
+ let result = promise;
1459
+ const hooks = [];
1460
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1461
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1462
+ hooks.push({ hookedCommand, callback });
1463
+ });
1464
+ });
1465
+ if (event === "postAction") {
1466
+ hooks.reverse();
1467
+ }
1468
+ hooks.forEach((hookDetail) => {
1469
+ result = this._chainOrCall(result, () => {
1470
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1471
+ });
1472
+ });
1473
+ return result;
1474
+ }
1475
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1476
+ let result = promise;
1477
+ if (this._lifeCycleHooks[event] !== undefined) {
1478
+ this._lifeCycleHooks[event].forEach((hook) => {
1479
+ result = this._chainOrCall(result, () => {
1480
+ return hook(this, subCommand);
1481
+ });
1482
+ });
1483
+ }
1484
+ return result;
1485
+ }
1486
+ _parseCommand(operands, unknown) {
1487
+ const parsed = this.parseOptions(unknown);
1488
+ this._parseOptionsEnv();
1489
+ this._parseOptionsImplied();
1490
+ operands = operands.concat(parsed.operands);
1491
+ unknown = parsed.unknown;
1492
+ this.args = operands.concat(unknown);
1493
+ if (operands && this._findCommand(operands[0])) {
1494
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1495
+ }
1496
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1497
+ return this._dispatchHelpCommand(operands[1]);
1498
+ }
1499
+ if (this._defaultCommandName) {
1500
+ this._outputHelpIfRequested(unknown);
1501
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1502
+ }
1503
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1504
+ this.help({ error: true });
1505
+ }
1506
+ this._outputHelpIfRequested(parsed.unknown);
1507
+ this._checkForMissingMandatoryOptions();
1508
+ this._checkForConflictingOptions();
1509
+ const checkForUnknownOptions = () => {
1510
+ if (parsed.unknown.length > 0) {
1511
+ this.unknownOption(parsed.unknown[0]);
1512
+ }
1513
+ };
1514
+ const commandEvent = `command:${this.name()}`;
1515
+ if (this._actionHandler) {
1516
+ checkForUnknownOptions();
1517
+ this._processArguments();
1518
+ let promiseChain;
1519
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1520
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1521
+ if (this.parent) {
1522
+ promiseChain = this._chainOrCall(promiseChain, () => {
1523
+ this.parent.emit(commandEvent, operands, unknown);
1524
+ });
1525
+ }
1526
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1527
+ return promiseChain;
1528
+ }
1529
+ if (this.parent?.listenerCount(commandEvent)) {
1530
+ checkForUnknownOptions();
1531
+ this._processArguments();
1532
+ this.parent.emit(commandEvent, operands, unknown);
1533
+ } else if (operands.length) {
1534
+ if (this._findCommand("*")) {
1535
+ return this._dispatchSubcommand("*", operands, unknown);
1536
+ }
1537
+ if (this.listenerCount("command:*")) {
1538
+ this.emit("command:*", operands, unknown);
1539
+ } else if (this.commands.length) {
1540
+ this.unknownCommand();
1541
+ } else {
1542
+ checkForUnknownOptions();
1543
+ this._processArguments();
1544
+ }
1545
+ } else if (this.commands.length) {
1546
+ checkForUnknownOptions();
1547
+ this.help({ error: true });
1548
+ } else {
1549
+ checkForUnknownOptions();
1550
+ this._processArguments();
1551
+ }
1552
+ }
1553
+ _findCommand(name) {
1554
+ if (!name)
1555
+ return;
1556
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1557
+ }
1558
+ _findOption(arg) {
1559
+ return this.options.find((option) => option.is(arg));
1560
+ }
1561
+ _checkForMissingMandatoryOptions() {
1562
+ this._getCommandAndAncestors().forEach((cmd) => {
1563
+ cmd.options.forEach((anOption) => {
1564
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1565
+ cmd.missingMandatoryOptionValue(anOption);
1566
+ }
1567
+ });
1568
+ });
1569
+ }
1570
+ _checkForConflictingLocalOptions() {
1571
+ const definedNonDefaultOptions = this.options.filter((option) => {
1572
+ const optionKey = option.attributeName();
1573
+ if (this.getOptionValue(optionKey) === undefined) {
1574
+ return false;
1575
+ }
1576
+ return this.getOptionValueSource(optionKey) !== "default";
1577
+ });
1578
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1579
+ optionsWithConflicting.forEach((option) => {
1580
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1581
+ if (conflictingAndDefined) {
1582
+ this._conflictingOption(option, conflictingAndDefined);
1583
+ }
1584
+ });
1585
+ }
1586
+ _checkForConflictingOptions() {
1587
+ this._getCommandAndAncestors().forEach((cmd) => {
1588
+ cmd._checkForConflictingLocalOptions();
1589
+ });
1590
+ }
1591
+ parseOptions(args) {
1592
+ const operands = [];
1593
+ const unknown = [];
1594
+ let dest = operands;
1595
+ function maybeOption(arg) {
1596
+ return arg.length > 1 && arg[0] === "-";
1597
+ }
1598
+ const negativeNumberArg = (arg) => {
1599
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1600
+ return false;
1601
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1602
+ };
1603
+ let activeVariadicOption = null;
1604
+ let activeGroup = null;
1605
+ let i = 0;
1606
+ while (i < args.length || activeGroup) {
1607
+ const arg = activeGroup ?? args[i++];
1608
+ activeGroup = null;
1609
+ if (arg === "--") {
1610
+ if (dest === unknown)
1611
+ dest.push(arg);
1612
+ dest.push(...args.slice(i));
1613
+ break;
1614
+ }
1615
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1616
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1617
+ continue;
1618
+ }
1619
+ activeVariadicOption = null;
1620
+ if (maybeOption(arg)) {
1621
+ const option = this._findOption(arg);
1622
+ if (option) {
1623
+ if (option.required) {
1624
+ const value = args[i++];
1625
+ if (value === undefined)
1626
+ this.optionMissingArgument(option);
1627
+ this.emit(`option:${option.name()}`, value);
1628
+ } else if (option.optional) {
1629
+ let value = null;
1630
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1631
+ value = args[i++];
1632
+ }
1633
+ this.emit(`option:${option.name()}`, value);
1634
+ } else {
1635
+ this.emit(`option:${option.name()}`);
1636
+ }
1637
+ activeVariadicOption = option.variadic ? option : null;
1638
+ continue;
1639
+ }
1640
+ }
1641
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1642
+ const option = this._findOption(`-${arg[1]}`);
1643
+ if (option) {
1644
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1645
+ this.emit(`option:${option.name()}`, arg.slice(2));
1646
+ } else {
1647
+ this.emit(`option:${option.name()}`);
1648
+ activeGroup = `-${arg.slice(2)}`;
1649
+ }
1650
+ continue;
1651
+ }
1652
+ }
1653
+ if (/^--[^=]+=/.test(arg)) {
1654
+ const index = arg.indexOf("=");
1655
+ const option = this._findOption(arg.slice(0, index));
1656
+ if (option && (option.required || option.optional)) {
1657
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1658
+ continue;
1659
+ }
1660
+ }
1661
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1662
+ dest = unknown;
1663
+ }
1664
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1665
+ if (this._findCommand(arg)) {
1666
+ operands.push(arg);
1667
+ unknown.push(...args.slice(i));
1668
+ break;
1669
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1670
+ operands.push(arg, ...args.slice(i));
1671
+ break;
1672
+ } else if (this._defaultCommandName) {
1673
+ unknown.push(arg, ...args.slice(i));
1674
+ break;
1675
+ }
1676
+ }
1677
+ if (this._passThroughOptions) {
1678
+ dest.push(arg, ...args.slice(i));
1679
+ break;
1680
+ }
1681
+ dest.push(arg);
1682
+ }
1683
+ return { operands, unknown };
1684
+ }
1685
+ opts() {
1686
+ if (this._storeOptionsAsProperties) {
1687
+ const result = {};
1688
+ const len = this.options.length;
1689
+ for (let i = 0;i < len; i++) {
1690
+ const key = this.options[i].attributeName();
1691
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1692
+ }
1693
+ return result;
1694
+ }
1695
+ return this._optionValues;
1696
+ }
1697
+ optsWithGlobals() {
1698
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1699
+ }
1700
+ error(message, errorOptions) {
1701
+ this._outputConfiguration.outputError(`${message}
1702
+ `, this._outputConfiguration.writeErr);
1703
+ if (typeof this._showHelpAfterError === "string") {
1704
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1705
+ `);
1706
+ } else if (this._showHelpAfterError) {
1707
+ this._outputConfiguration.writeErr(`
1708
+ `);
1709
+ this.outputHelp({ error: true });
1710
+ }
1711
+ const config = errorOptions || {};
1712
+ const exitCode = config.exitCode || 1;
1713
+ const code = config.code || "commander.error";
1714
+ this._exit(exitCode, code, message);
1715
+ }
1716
+ _parseOptionsEnv() {
1717
+ this.options.forEach((option) => {
1718
+ if (option.envVar && option.envVar in process2.env) {
1719
+ const optionKey = option.attributeName();
1720
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1721
+ if (option.required || option.optional) {
1722
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1723
+ } else {
1724
+ this.emit(`optionEnv:${option.name()}`);
1725
+ }
1726
+ }
1727
+ }
1728
+ });
1729
+ }
1730
+ _parseOptionsImplied() {
1731
+ const dualHelper = new DualOptions(this.options);
1732
+ const hasCustomOptionValue = (optionKey) => {
1733
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1734
+ };
1735
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1736
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1737
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1738
+ });
1739
+ });
1740
+ }
1741
+ missingArgument(name) {
1742
+ const message = `error: missing required argument '${name}'`;
1743
+ this.error(message, { code: "commander.missingArgument" });
1744
+ }
1745
+ optionMissingArgument(option) {
1746
+ const message = `error: option '${option.flags}' argument missing`;
1747
+ this.error(message, { code: "commander.optionMissingArgument" });
1748
+ }
1749
+ missingMandatoryOptionValue(option) {
1750
+ const message = `error: required option '${option.flags}' not specified`;
1751
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1752
+ }
1753
+ _conflictingOption(option, conflictingOption) {
1754
+ const findBestOptionFromValue = (option2) => {
1755
+ const optionKey = option2.attributeName();
1756
+ const optionValue = this.getOptionValue(optionKey);
1757
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1758
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1759
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1760
+ return negativeOption;
1761
+ }
1762
+ return positiveOption || option2;
1763
+ };
1764
+ const getErrorMessage = (option2) => {
1765
+ const bestOption = findBestOptionFromValue(option2);
1766
+ const optionKey = bestOption.attributeName();
1767
+ const source = this.getOptionValueSource(optionKey);
1768
+ if (source === "env") {
1769
+ return `environment variable '${bestOption.envVar}'`;
1770
+ }
1771
+ return `option '${bestOption.flags}'`;
1772
+ };
1773
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1774
+ this.error(message, { code: "commander.conflictingOption" });
1775
+ }
1776
+ unknownOption(flag) {
1777
+ if (this._allowUnknownOption)
1778
+ return;
1779
+ let suggestion = "";
1780
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1781
+ let candidateFlags = [];
1782
+ let command = this;
1783
+ do {
1784
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1785
+ candidateFlags = candidateFlags.concat(moreFlags);
1786
+ command = command.parent;
1787
+ } while (command && !command._enablePositionalOptions);
1788
+ suggestion = suggestSimilar(flag, candidateFlags);
1789
+ }
1790
+ const message = `error: unknown option '${flag}'${suggestion}`;
1791
+ this.error(message, { code: "commander.unknownOption" });
1792
+ }
1793
+ _excessArguments(receivedArgs) {
1794
+ if (this._allowExcessArguments)
1795
+ return;
1796
+ const expected = this.registeredArguments.length;
1797
+ const s = expected === 1 ? "" : "s";
1798
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1799
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1800
+ this.error(message, { code: "commander.excessArguments" });
1801
+ }
1802
+ unknownCommand() {
1803
+ const unknownName = this.args[0];
1804
+ let suggestion = "";
1805
+ if (this._showSuggestionAfterError) {
1806
+ const candidateNames = [];
1807
+ this.createHelp().visibleCommands(this).forEach((command) => {
1808
+ candidateNames.push(command.name());
1809
+ if (command.alias())
1810
+ candidateNames.push(command.alias());
1811
+ });
1812
+ suggestion = suggestSimilar(unknownName, candidateNames);
1813
+ }
1814
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1815
+ this.error(message, { code: "commander.unknownCommand" });
1816
+ }
1817
+ version(str, flags, description) {
1818
+ if (str === undefined)
1819
+ return this._version;
1820
+ this._version = str;
1821
+ flags = flags || "-V, --version";
1822
+ description = description || "output the version number";
1823
+ const versionOption = this.createOption(flags, description);
1824
+ this._versionOptionName = versionOption.attributeName();
1825
+ this._registerOption(versionOption);
1826
+ this.on("option:" + versionOption.name(), () => {
1827
+ this._outputConfiguration.writeOut(`${str}
1828
+ `);
1829
+ this._exit(0, "commander.version", str);
1830
+ });
1831
+ return this;
1832
+ }
1833
+ description(str, argsDescription) {
1834
+ if (str === undefined && argsDescription === undefined)
1835
+ return this._description;
1836
+ this._description = str;
1837
+ if (argsDescription) {
1838
+ this._argsDescription = argsDescription;
1839
+ }
1840
+ return this;
1841
+ }
1842
+ summary(str) {
1843
+ if (str === undefined)
1844
+ return this._summary;
1845
+ this._summary = str;
1846
+ return this;
1847
+ }
1848
+ alias(alias) {
1849
+ if (alias === undefined)
1850
+ return this._aliases[0];
1851
+ let command = this;
1852
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1853
+ command = this.commands[this.commands.length - 1];
1854
+ }
1855
+ if (alias === command._name)
1856
+ throw new Error("Command alias can't be the same as its name");
1857
+ const matchingCommand = this.parent?._findCommand(alias);
1858
+ if (matchingCommand) {
1859
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1860
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1861
+ }
1862
+ command._aliases.push(alias);
1863
+ return this;
1864
+ }
1865
+ aliases(aliases) {
1866
+ if (aliases === undefined)
1867
+ return this._aliases;
1868
+ aliases.forEach((alias) => this.alias(alias));
1869
+ return this;
1870
+ }
1871
+ usage(str) {
1872
+ if (str === undefined) {
1873
+ if (this._usage)
1874
+ return this._usage;
1875
+ const args = this.registeredArguments.map((arg) => {
1876
+ return humanReadableArgName(arg);
1877
+ });
1878
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1879
+ }
1880
+ this._usage = str;
1881
+ return this;
1882
+ }
1883
+ name(str) {
1884
+ if (str === undefined)
1885
+ return this._name;
1886
+ this._name = str;
1887
+ return this;
1888
+ }
1889
+ helpGroup(heading) {
1890
+ if (heading === undefined)
1891
+ return this._helpGroupHeading ?? "";
1892
+ this._helpGroupHeading = heading;
1893
+ return this;
1894
+ }
1895
+ commandsGroup(heading) {
1896
+ if (heading === undefined)
1897
+ return this._defaultCommandGroup ?? "";
1898
+ this._defaultCommandGroup = heading;
1899
+ return this;
1900
+ }
1901
+ optionsGroup(heading) {
1902
+ if (heading === undefined)
1903
+ return this._defaultOptionGroup ?? "";
1904
+ this._defaultOptionGroup = heading;
1905
+ return this;
1906
+ }
1907
+ _initOptionGroup(option) {
1908
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1909
+ option.helpGroup(this._defaultOptionGroup);
1910
+ }
1911
+ _initCommandGroup(cmd) {
1912
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1913
+ cmd.helpGroup(this._defaultCommandGroup);
1914
+ }
1915
+ nameFromFilename(filename) {
1916
+ this._name = path.basename(filename, path.extname(filename));
1917
+ return this;
1918
+ }
1919
+ executableDir(path2) {
1920
+ if (path2 === undefined)
1921
+ return this._executableDir;
1922
+ this._executableDir = path2;
1923
+ return this;
1924
+ }
1925
+ helpInformation(contextOptions) {
1926
+ const helper = this.createHelp();
1927
+ const context = this._getOutputContext(contextOptions);
1928
+ helper.prepareContext({
1929
+ error: context.error,
1930
+ helpWidth: context.helpWidth,
1931
+ outputHasColors: context.hasColors
1932
+ });
1933
+ const text = helper.formatHelp(this, helper);
1934
+ if (context.hasColors)
1935
+ return text;
1936
+ return this._outputConfiguration.stripColor(text);
1937
+ }
1938
+ _getOutputContext(contextOptions) {
1939
+ contextOptions = contextOptions || {};
1940
+ const error = !!contextOptions.error;
1941
+ let baseWrite;
1942
+ let hasColors;
1943
+ let helpWidth;
1944
+ if (error) {
1945
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1946
+ hasColors = this._outputConfiguration.getErrHasColors();
1947
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1948
+ } else {
1949
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1950
+ hasColors = this._outputConfiguration.getOutHasColors();
1951
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1952
+ }
1953
+ const write = (str) => {
1954
+ if (!hasColors)
1955
+ str = this._outputConfiguration.stripColor(str);
1956
+ return baseWrite(str);
1957
+ };
1958
+ return { error, write, hasColors, helpWidth };
1959
+ }
1960
+ outputHelp(contextOptions) {
1961
+ let deprecatedCallback;
1962
+ if (typeof contextOptions === "function") {
1963
+ deprecatedCallback = contextOptions;
1964
+ contextOptions = undefined;
1965
+ }
1966
+ const outputContext = this._getOutputContext(contextOptions);
1967
+ const eventContext = {
1968
+ error: outputContext.error,
1969
+ write: outputContext.write,
1970
+ command: this
1971
+ };
1972
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1973
+ this.emit("beforeHelp", eventContext);
1974
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1975
+ if (deprecatedCallback) {
1976
+ helpInformation = deprecatedCallback(helpInformation);
1977
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1978
+ throw new Error("outputHelp callback must return a string or a Buffer");
1979
+ }
1980
+ }
1981
+ outputContext.write(helpInformation);
1982
+ if (this._getHelpOption()?.long) {
1983
+ this.emit(this._getHelpOption().long);
1984
+ }
1985
+ this.emit("afterHelp", eventContext);
1986
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1987
+ }
1988
+ helpOption(flags, description) {
1989
+ if (typeof flags === "boolean") {
1990
+ if (flags) {
1991
+ if (this._helpOption === null)
1992
+ this._helpOption = undefined;
1993
+ if (this._defaultOptionGroup) {
1994
+ this._initOptionGroup(this._getHelpOption());
1995
+ }
1996
+ } else {
1997
+ this._helpOption = null;
1998
+ }
1999
+ return this;
2000
+ }
2001
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2002
+ if (flags || description)
2003
+ this._initOptionGroup(this._helpOption);
2004
+ return this;
2005
+ }
2006
+ _getHelpOption() {
2007
+ if (this._helpOption === undefined) {
2008
+ this.helpOption(undefined, undefined);
2009
+ }
2010
+ return this._helpOption;
2011
+ }
2012
+ addHelpOption(option) {
2013
+ this._helpOption = option;
2014
+ this._initOptionGroup(option);
2015
+ return this;
2016
+ }
2017
+ help(contextOptions) {
2018
+ this.outputHelp(contextOptions);
2019
+ let exitCode = Number(process2.exitCode ?? 0);
2020
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2021
+ exitCode = 1;
2022
+ }
2023
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2024
+ }
2025
+ addHelpText(position, text) {
2026
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2027
+ if (!allowedValues.includes(position)) {
2028
+ throw new Error(`Unexpected value for position to addHelpText.
2029
+ Expecting one of '${allowedValues.join("', '")}'`);
2030
+ }
2031
+ const helpEvent = `${position}Help`;
2032
+ this.on(helpEvent, (context) => {
2033
+ let helpStr;
2034
+ if (typeof text === "function") {
2035
+ helpStr = text({ error: context.error, command: context.command });
2036
+ } else {
2037
+ helpStr = text;
2038
+ }
2039
+ if (helpStr) {
2040
+ context.write(`${helpStr}
2041
+ `);
2042
+ }
2043
+ });
2044
+ return this;
2045
+ }
2046
+ _outputHelpIfRequested(args) {
2047
+ const helpOption = this._getHelpOption();
2048
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2049
+ if (helpRequested) {
2050
+ this.outputHelp();
2051
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2052
+ }
2053
+ }
2054
+ }
2055
+ function incrementNodeInspectorPort(args) {
2056
+ return args.map((arg) => {
2057
+ if (!arg.startsWith("--inspect")) {
2058
+ return arg;
2059
+ }
2060
+ let debugOption;
2061
+ let debugHost = "127.0.0.1";
2062
+ let debugPort = "9229";
2063
+ let match;
2064
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2065
+ debugOption = match[1];
2066
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2067
+ debugOption = match[1];
2068
+ if (/^\d+$/.test(match[3])) {
2069
+ debugPort = match[3];
2070
+ } else {
2071
+ debugHost = match[3];
2072
+ }
2073
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2074
+ debugOption = match[1];
2075
+ debugHost = match[3];
2076
+ debugPort = match[4];
2077
+ }
2078
+ if (debugOption && debugPort !== "0") {
2079
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2080
+ }
2081
+ return arg;
2082
+ });
2083
+ }
2084
+ function useColor() {
2085
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2086
+ return false;
2087
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2088
+ return true;
2089
+ return;
2090
+ }
2091
+ exports.Command = Command;
2092
+ exports.useColor = useColor;
2093
+ });
2094
+
2095
+ // node_modules/commander/index.js
2096
+ var require_commander = __commonJS((exports) => {
2097
+ var { Argument } = require_argument();
2098
+ var { Command } = require_command();
2099
+ var { CommanderError, InvalidArgumentError } = require_error();
2100
+ var { Help } = require_help();
2101
+ var { Option } = require_option();
2102
+ exports.program = new Command;
2103
+ exports.createCommand = (name) => new Command(name);
2104
+ exports.createOption = (flags, description) => new Option(flags, description);
2105
+ exports.createArgument = (name, description) => new Argument(name, description);
2106
+ exports.Command = Command;
2107
+ exports.Option = Option;
2108
+ exports.Argument = Argument;
2109
+ exports.Help = Help;
2110
+ exports.CommanderError = CommanderError;
2111
+ exports.InvalidArgumentError = InvalidArgumentError;
2112
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2113
+ });
2114
+
2115
+ // node_modules/ini/lib/ini.js
2116
+ var require_ini = __commonJS((exports, module) => {
2117
+ var { hasOwnProperty } = Object.prototype;
2118
+ var encode = (obj, opt = {}) => {
2119
+ if (typeof opt === "string") {
2120
+ opt = { section: opt };
2121
+ }
2122
+ opt.align = opt.align === true;
2123
+ opt.newline = opt.newline === true;
2124
+ opt.sort = opt.sort === true;
2125
+ opt.whitespace = opt.whitespace === true || opt.align === true;
2126
+ opt.platform = opt.platform || typeof process !== "undefined" && process.platform;
2127
+ opt.bracketedArray = opt.bracketedArray !== false;
2128
+ const eol = opt.platform === "win32" ? `\r
2129
+ ` : `
2130
+ `;
2131
+ const separator = opt.whitespace ? " = " : "=";
2132
+ const children = [];
2133
+ const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj);
2134
+ let padToChars = 0;
2135
+ if (opt.align) {
2136
+ padToChars = safe(keys.filter((k) => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== "object").map((k) => Array.isArray(obj[k]) ? `${k}[]` : k).concat([""]).reduce((a, b) => safe(a).length >= safe(b).length ? a : b)).length;
2137
+ }
2138
+ let out = "";
2139
+ const arraySuffix = opt.bracketedArray ? "[]" : "";
2140
+ for (const k of keys) {
2141
+ const val = obj[k];
2142
+ if (val && Array.isArray(val)) {
2143
+ for (const item of val) {
2144
+ out += safe(`${k}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol;
2145
+ }
2146
+ } else if (val && typeof val === "object") {
2147
+ children.push(k);
2148
+ } else {
2149
+ out += safe(k).padEnd(padToChars, " ") + separator + safe(val) + eol;
2150
+ }
2151
+ }
2152
+ if (opt.section && out.length) {
2153
+ out = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out;
2154
+ }
2155
+ for (const k of children) {
2156
+ const nk = splitSections(k, ".").join("\\.");
2157
+ const section = (opt.section ? opt.section + "." : "") + nk;
2158
+ const child = encode(obj[k], {
2159
+ ...opt,
2160
+ section
2161
+ });
2162
+ if (out.length && child.length) {
2163
+ out += eol;
2164
+ }
2165
+ out += child;
2166
+ }
2167
+ return out;
2168
+ };
2169
+ function splitSections(str, separator) {
2170
+ var lastMatchIndex = 0;
2171
+ var lastSeparatorIndex = 0;
2172
+ var nextIndex = 0;
2173
+ var sections = [];
2174
+ do {
2175
+ nextIndex = str.indexOf(separator, lastMatchIndex);
2176
+ if (nextIndex !== -1) {
2177
+ lastMatchIndex = nextIndex + separator.length;
2178
+ if (nextIndex > 0 && str[nextIndex - 1] === "\\") {
2179
+ continue;
2180
+ }
2181
+ sections.push(str.slice(lastSeparatorIndex, nextIndex));
2182
+ lastSeparatorIndex = nextIndex + separator.length;
2183
+ }
2184
+ } while (nextIndex !== -1);
2185
+ sections.push(str.slice(lastSeparatorIndex));
2186
+ return sections;
2187
+ }
2188
+ var decode = (str, opt = {}) => {
2189
+ opt.bracketedArray = opt.bracketedArray !== false;
2190
+ const out = Object.create(null);
2191
+ let p = out;
2192
+ let section = null;
2193
+ const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i;
2194
+ const lines = str.split(/[\r\n]+/g);
2195
+ const duplicates = {};
2196
+ for (const line of lines) {
2197
+ if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) {
2198
+ continue;
2199
+ }
2200
+ const match = line.match(re);
2201
+ if (!match) {
2202
+ continue;
2203
+ }
2204
+ if (match[1] !== undefined) {
2205
+ section = unsafe(match[1]);
2206
+ if (section === "__proto__") {
2207
+ p = Object.create(null);
2208
+ continue;
2209
+ }
2210
+ p = out[section] = out[section] || Object.create(null);
2211
+ continue;
2212
+ }
2213
+ const keyRaw = unsafe(match[2]);
2214
+ let isArray;
2215
+ if (opt.bracketedArray) {
2216
+ isArray = keyRaw.length > 2 && keyRaw.slice(-2) === "[]";
2217
+ } else {
2218
+ duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1;
2219
+ isArray = duplicates[keyRaw] > 1;
2220
+ }
2221
+ const key = isArray && keyRaw.endsWith("[]") ? keyRaw.slice(0, -2) : keyRaw;
2222
+ if (key === "__proto__") {
2223
+ continue;
2224
+ }
2225
+ const valueRaw = match[3] ? unsafe(match[4]) : true;
2226
+ const value = valueRaw === "true" || valueRaw === "false" || valueRaw === "null" ? JSON.parse(valueRaw) : valueRaw;
2227
+ if (isArray) {
2228
+ if (!hasOwnProperty.call(p, key)) {
2229
+ p[key] = [];
2230
+ } else if (!Array.isArray(p[key])) {
2231
+ p[key] = [p[key]];
2232
+ }
2233
+ }
2234
+ if (Array.isArray(p[key])) {
2235
+ p[key].push(value);
2236
+ } else {
2237
+ p[key] = value;
2238
+ }
2239
+ }
2240
+ const remove = [];
2241
+ for (const k of Object.keys(out)) {
2242
+ if (!hasOwnProperty.call(out, k) || typeof out[k] !== "object" || Array.isArray(out[k])) {
2243
+ continue;
2244
+ }
2245
+ const parts = splitSections(k, ".");
2246
+ p = out;
2247
+ const l = parts.pop();
2248
+ const nl = l.replace(/\\\./g, ".");
2249
+ for (const part of parts) {
2250
+ if (part === "__proto__") {
2251
+ continue;
2252
+ }
2253
+ if (!hasOwnProperty.call(p, part) || typeof p[part] !== "object") {
2254
+ p[part] = Object.create(null);
2255
+ }
2256
+ p = p[part];
2257
+ }
2258
+ if (p === out && nl === l) {
2259
+ continue;
2260
+ }
2261
+ p[nl] = out[k];
2262
+ remove.push(k);
2263
+ }
2264
+ for (const del of remove) {
2265
+ delete out[del];
2266
+ }
2267
+ return out;
2268
+ };
2269
+ var isQuoted = (val) => {
2270
+ return val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'");
2271
+ };
2272
+ var safe = (val) => {
2273
+ if (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim()) {
2274
+ return JSON.stringify(val);
2275
+ }
2276
+ return val.split(";").join("\\;").split("#").join("\\#");
2277
+ };
2278
+ var unsafe = (val) => {
2279
+ val = (val || "").trim();
2280
+ if (isQuoted(val)) {
2281
+ if (val.charAt(0) === "'") {
2282
+ val = val.slice(1, -1);
2283
+ }
2284
+ try {
2285
+ val = JSON.parse(val);
2286
+ } catch {}
2287
+ } else {
2288
+ let esc = false;
2289
+ let unesc = "";
2290
+ for (let i = 0, l = val.length;i < l; i++) {
2291
+ const c = val.charAt(i);
2292
+ if (esc) {
2293
+ if ("\\;#".indexOf(c) !== -1) {
2294
+ unesc += c;
2295
+ } else {
2296
+ unesc += "\\" + c;
2297
+ }
2298
+ esc = false;
2299
+ } else if (";#".indexOf(c) !== -1) {
2300
+ break;
2301
+ } else if (c === "\\") {
2302
+ esc = true;
2303
+ } else {
2304
+ unesc += c;
2305
+ }
2306
+ }
2307
+ if (esc) {
2308
+ unesc += "\\";
2309
+ }
2310
+ return unesc.trim();
2311
+ }
2312
+ return val;
2313
+ };
2314
+ module.exports = {
2315
+ parse: decode,
2316
+ decode,
2317
+ stringify: encode,
2318
+ encode,
2319
+ safe,
2320
+ unsafe
2321
+ };
2322
+ });
2323
+
2324
+ // node_modules/commander/esm.mjs
2325
+ var import__ = __toESM(require_commander(), 1);
2326
+ var {
2327
+ program,
2328
+ createCommand,
2329
+ createArgument,
2330
+ createOption,
2331
+ CommanderError,
2332
+ InvalidArgumentError,
2333
+ InvalidOptionArgumentError,
2334
+ Command,
2335
+ Argument,
2336
+ Option,
2337
+ Help
2338
+ } = import__.default;
2339
+
2340
+ // src/services/configService.ts
2341
+ import { readFileSync, writeFileSync, existsSync } from "fs";
2342
+
2343
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
2344
+ var ANSI_BACKGROUND_OFFSET = 10;
2345
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
2346
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
2347
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
2348
+ var styles = {
2349
+ modifier: {
2350
+ reset: [0, 0],
2351
+ bold: [1, 22],
2352
+ dim: [2, 22],
2353
+ italic: [3, 23],
2354
+ underline: [4, 24],
2355
+ overline: [53, 55],
2356
+ inverse: [7, 27],
2357
+ hidden: [8, 28],
2358
+ strikethrough: [9, 29]
2359
+ },
2360
+ color: {
2361
+ black: [30, 39],
2362
+ red: [31, 39],
2363
+ green: [32, 39],
2364
+ yellow: [33, 39],
2365
+ blue: [34, 39],
2366
+ magenta: [35, 39],
2367
+ cyan: [36, 39],
2368
+ white: [37, 39],
2369
+ blackBright: [90, 39],
2370
+ gray: [90, 39],
2371
+ grey: [90, 39],
2372
+ redBright: [91, 39],
2373
+ greenBright: [92, 39],
2374
+ yellowBright: [93, 39],
2375
+ blueBright: [94, 39],
2376
+ magentaBright: [95, 39],
2377
+ cyanBright: [96, 39],
2378
+ whiteBright: [97, 39]
2379
+ },
2380
+ bgColor: {
2381
+ bgBlack: [40, 49],
2382
+ bgRed: [41, 49],
2383
+ bgGreen: [42, 49],
2384
+ bgYellow: [43, 49],
2385
+ bgBlue: [44, 49],
2386
+ bgMagenta: [45, 49],
2387
+ bgCyan: [46, 49],
2388
+ bgWhite: [47, 49],
2389
+ bgBlackBright: [100, 49],
2390
+ bgGray: [100, 49],
2391
+ bgGrey: [100, 49],
2392
+ bgRedBright: [101, 49],
2393
+ bgGreenBright: [102, 49],
2394
+ bgYellowBright: [103, 49],
2395
+ bgBlueBright: [104, 49],
2396
+ bgMagentaBright: [105, 49],
2397
+ bgCyanBright: [106, 49],
2398
+ bgWhiteBright: [107, 49]
2399
+ }
2400
+ };
2401
+ var modifierNames = Object.keys(styles.modifier);
2402
+ var foregroundColorNames = Object.keys(styles.color);
2403
+ var backgroundColorNames = Object.keys(styles.bgColor);
2404
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
2405
+ function assembleStyles() {
2406
+ const codes = new Map;
2407
+ for (const [groupName, group] of Object.entries(styles)) {
2408
+ for (const [styleName, style] of Object.entries(group)) {
2409
+ styles[styleName] = {
2410
+ open: `\x1B[${style[0]}m`,
2411
+ close: `\x1B[${style[1]}m`
2412
+ };
2413
+ group[styleName] = styles[styleName];
2414
+ codes.set(style[0], style[1]);
2415
+ }
2416
+ Object.defineProperty(styles, groupName, {
2417
+ value: group,
2418
+ enumerable: false
2419
+ });
2420
+ }
2421
+ Object.defineProperty(styles, "codes", {
2422
+ value: codes,
2423
+ enumerable: false
2424
+ });
2425
+ styles.color.close = "\x1B[39m";
2426
+ styles.bgColor.close = "\x1B[49m";
2427
+ styles.color.ansi = wrapAnsi16();
2428
+ styles.color.ansi256 = wrapAnsi256();
2429
+ styles.color.ansi16m = wrapAnsi16m();
2430
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
2431
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
2432
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
2433
+ Object.defineProperties(styles, {
2434
+ rgbToAnsi256: {
2435
+ value(red, green, blue) {
2436
+ if (red === green && green === blue) {
2437
+ if (red < 8) {
2438
+ return 16;
2439
+ }
2440
+ if (red > 248) {
2441
+ return 231;
2442
+ }
2443
+ return Math.round((red - 8) / 247 * 24) + 232;
2444
+ }
2445
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
2446
+ },
2447
+ enumerable: false
2448
+ },
2449
+ hexToRgb: {
2450
+ value(hex) {
2451
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
2452
+ if (!matches) {
2453
+ return [0, 0, 0];
2454
+ }
2455
+ let [colorString] = matches;
2456
+ if (colorString.length === 3) {
2457
+ colorString = [...colorString].map((character) => character + character).join("");
2458
+ }
2459
+ const integer = Number.parseInt(colorString, 16);
2460
+ return [
2461
+ integer >> 16 & 255,
2462
+ integer >> 8 & 255,
2463
+ integer & 255
2464
+ ];
2465
+ },
2466
+ enumerable: false
2467
+ },
2468
+ hexToAnsi256: {
2469
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
2470
+ enumerable: false
2471
+ },
2472
+ ansi256ToAnsi: {
2473
+ value(code) {
2474
+ if (code < 8) {
2475
+ return 30 + code;
2476
+ }
2477
+ if (code < 16) {
2478
+ return 90 + (code - 8);
2479
+ }
2480
+ let red;
2481
+ let green;
2482
+ let blue;
2483
+ if (code >= 232) {
2484
+ red = ((code - 232) * 10 + 8) / 255;
2485
+ green = red;
2486
+ blue = red;
2487
+ } else {
2488
+ code -= 16;
2489
+ const remainder = code % 36;
2490
+ red = Math.floor(code / 36) / 5;
2491
+ green = Math.floor(remainder / 6) / 5;
2492
+ blue = remainder % 6 / 5;
2493
+ }
2494
+ const value = Math.max(red, green, blue) * 2;
2495
+ if (value === 0) {
2496
+ return 30;
2497
+ }
2498
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
2499
+ if (value === 2) {
2500
+ result += 60;
2501
+ }
2502
+ return result;
2503
+ },
2504
+ enumerable: false
2505
+ },
2506
+ rgbToAnsi: {
2507
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
2508
+ enumerable: false
2509
+ },
2510
+ hexToAnsi: {
2511
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
2512
+ enumerable: false
2513
+ }
2514
+ });
2515
+ return styles;
2516
+ }
2517
+ var ansiStyles = assembleStyles();
2518
+ var ansi_styles_default = ansiStyles;
2519
+
2520
+ // node_modules/chalk/source/vendor/supports-color/index.js
2521
+ import process2 from "node:process";
2522
+ import os from "node:os";
2523
+ import tty from "node:tty";
2524
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2525
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2526
+ const position = argv.indexOf(prefix + flag);
2527
+ const terminatorPosition = argv.indexOf("--");
2528
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2529
+ }
2530
+ var { env } = process2;
2531
+ var flagForceColor;
2532
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2533
+ flagForceColor = 0;
2534
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2535
+ flagForceColor = 1;
2536
+ }
2537
+ function envForceColor() {
2538
+ if ("FORCE_COLOR" in env) {
2539
+ if (env.FORCE_COLOR === "true") {
2540
+ return 1;
2541
+ }
2542
+ if (env.FORCE_COLOR === "false") {
2543
+ return 0;
2544
+ }
2545
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2546
+ }
2547
+ }
2548
+ function translateLevel(level) {
2549
+ if (level === 0) {
2550
+ return false;
2551
+ }
2552
+ return {
2553
+ level,
2554
+ hasBasic: true,
2555
+ has256: level >= 2,
2556
+ has16m: level >= 3
2557
+ };
2558
+ }
2559
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2560
+ const noFlagForceColor = envForceColor();
2561
+ if (noFlagForceColor !== undefined) {
2562
+ flagForceColor = noFlagForceColor;
2563
+ }
2564
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2565
+ if (forceColor === 0) {
2566
+ return 0;
2567
+ }
2568
+ if (sniffFlags) {
2569
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2570
+ return 3;
2571
+ }
2572
+ if (hasFlag("color=256")) {
2573
+ return 2;
2574
+ }
2575
+ }
2576
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2577
+ return 1;
2578
+ }
2579
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
2580
+ return 0;
2581
+ }
2582
+ const min = forceColor || 0;
2583
+ if (env.TERM === "dumb") {
2584
+ return min;
2585
+ }
2586
+ if (process2.platform === "win32") {
2587
+ const osRelease = os.release().split(".");
2588
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2589
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2590
+ }
2591
+ return 1;
2592
+ }
2593
+ if ("CI" in env) {
2594
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
2595
+ return 3;
2596
+ }
2597
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
2598
+ return 1;
2599
+ }
2600
+ return min;
2601
+ }
2602
+ if ("TEAMCITY_VERSION" in env) {
2603
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2604
+ }
2605
+ if (env.COLORTERM === "truecolor") {
2606
+ return 3;
2607
+ }
2608
+ if (env.TERM === "xterm-kitty") {
2609
+ return 3;
2610
+ }
2611
+ if (env.TERM === "xterm-ghostty") {
2612
+ return 3;
2613
+ }
2614
+ if (env.TERM === "wezterm") {
2615
+ return 3;
2616
+ }
2617
+ if ("TERM_PROGRAM" in env) {
2618
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2619
+ switch (env.TERM_PROGRAM) {
2620
+ case "iTerm.app": {
2621
+ return version >= 3 ? 3 : 2;
2622
+ }
2623
+ case "Apple_Terminal": {
2624
+ return 2;
2625
+ }
2626
+ }
2627
+ }
2628
+ if (/-256(color)?$/i.test(env.TERM)) {
2629
+ return 2;
2630
+ }
2631
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2632
+ return 1;
2633
+ }
2634
+ if ("COLORTERM" in env) {
2635
+ return 1;
2636
+ }
2637
+ return min;
2638
+ }
2639
+ function createSupportsColor(stream, options = {}) {
2640
+ const level = _supportsColor(stream, {
2641
+ streamIsTTY: stream && stream.isTTY,
2642
+ ...options
2643
+ });
2644
+ return translateLevel(level);
2645
+ }
2646
+ var supportsColor = {
2647
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2648
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2649
+ };
2650
+ var supports_color_default = supportsColor;
2651
+
2652
+ // node_modules/chalk/source/utilities.js
2653
+ function stringReplaceAll(string, substring, replacer) {
2654
+ let index = string.indexOf(substring);
2655
+ if (index === -1) {
2656
+ return string;
2657
+ }
2658
+ const substringLength = substring.length;
2659
+ let endIndex = 0;
2660
+ let returnValue = "";
2661
+ do {
2662
+ returnValue += string.slice(endIndex, index) + substring + replacer;
2663
+ endIndex = index + substringLength;
2664
+ index = string.indexOf(substring, endIndex);
2665
+ } while (index !== -1);
2666
+ returnValue += string.slice(endIndex);
2667
+ return returnValue;
2668
+ }
2669
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2670
+ let endIndex = 0;
2671
+ let returnValue = "";
2672
+ do {
2673
+ const gotCR = string[index - 1] === "\r";
2674
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
2675
+ ` : `
2676
+ `) + postfix;
2677
+ endIndex = index + 1;
2678
+ index = string.indexOf(`
2679
+ `, endIndex);
2680
+ } while (index !== -1);
2681
+ returnValue += string.slice(endIndex);
2682
+ return returnValue;
2683
+ }
2684
+
2685
+ // node_modules/chalk/source/index.js
2686
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
2687
+ var GENERATOR = Symbol("GENERATOR");
2688
+ var STYLER = Symbol("STYLER");
2689
+ var IS_EMPTY = Symbol("IS_EMPTY");
2690
+ var levelMapping = [
2691
+ "ansi",
2692
+ "ansi",
2693
+ "ansi256",
2694
+ "ansi16m"
2695
+ ];
2696
+ var styles2 = Object.create(null);
2697
+ var applyOptions = (object, options = {}) => {
2698
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2699
+ throw new Error("The `level` option should be an integer from 0 to 3");
2700
+ }
2701
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2702
+ object.level = options.level === undefined ? colorLevel : options.level;
2703
+ };
2704
+ var chalkFactory = (options) => {
2705
+ const chalk = (...strings) => strings.join(" ");
2706
+ applyOptions(chalk, options);
2707
+ Object.setPrototypeOf(chalk, createChalk.prototype);
2708
+ return chalk;
2709
+ };
2710
+ function createChalk(options) {
2711
+ return chalkFactory(options);
2712
+ }
2713
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
2714
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
2715
+ styles2[styleName] = {
2716
+ get() {
2717
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
2718
+ Object.defineProperty(this, styleName, { value: builder });
2719
+ return builder;
2720
+ }
2721
+ };
2722
+ }
2723
+ styles2.visible = {
2724
+ get() {
2725
+ const builder = createBuilder(this, this[STYLER], true);
2726
+ Object.defineProperty(this, "visible", { value: builder });
2727
+ return builder;
2728
+ }
2729
+ };
2730
+ var getModelAnsi = (model, level, type, ...arguments_) => {
2731
+ if (model === "rgb") {
2732
+ if (level === "ansi16m") {
2733
+ return ansi_styles_default[type].ansi16m(...arguments_);
2734
+ }
2735
+ if (level === "ansi256") {
2736
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
2737
+ }
2738
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
2739
+ }
2740
+ if (model === "hex") {
2741
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
2742
+ }
2743
+ return ansi_styles_default[type][model](...arguments_);
2744
+ };
2745
+ var usedModels = ["rgb", "hex", "ansi256"];
2746
+ for (const model of usedModels) {
2747
+ styles2[model] = {
2748
+ get() {
2749
+ const { level } = this;
2750
+ return function(...arguments_) {
2751
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
2752
+ return createBuilder(this, styler, this[IS_EMPTY]);
2753
+ };
2754
+ }
2755
+ };
2756
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2757
+ styles2[bgModel] = {
2758
+ get() {
2759
+ const { level } = this;
2760
+ return function(...arguments_) {
2761
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
2762
+ return createBuilder(this, styler, this[IS_EMPTY]);
2763
+ };
2764
+ }
2765
+ };
2766
+ }
2767
+ var proto = Object.defineProperties(() => {}, {
2768
+ ...styles2,
2769
+ level: {
2770
+ enumerable: true,
2771
+ get() {
2772
+ return this[GENERATOR].level;
2773
+ },
2774
+ set(level) {
2775
+ this[GENERATOR].level = level;
2776
+ }
2777
+ }
2778
+ });
2779
+ var createStyler = (open, close, parent) => {
2780
+ let openAll;
2781
+ let closeAll;
2782
+ if (parent === undefined) {
2783
+ openAll = open;
2784
+ closeAll = close;
2785
+ } else {
2786
+ openAll = parent.openAll + open;
2787
+ closeAll = close + parent.closeAll;
2788
+ }
2789
+ return {
2790
+ open,
2791
+ close,
2792
+ openAll,
2793
+ closeAll,
2794
+ parent
2795
+ };
2796
+ };
2797
+ var createBuilder = (self, _styler, _isEmpty) => {
2798
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2799
+ Object.setPrototypeOf(builder, proto);
2800
+ builder[GENERATOR] = self;
2801
+ builder[STYLER] = _styler;
2802
+ builder[IS_EMPTY] = _isEmpty;
2803
+ return builder;
2804
+ };
2805
+ var applyStyle = (self, string) => {
2806
+ if (self.level <= 0 || !string) {
2807
+ return self[IS_EMPTY] ? "" : string;
2808
+ }
2809
+ let styler = self[STYLER];
2810
+ if (styler === undefined) {
2811
+ return string;
2812
+ }
2813
+ const { openAll, closeAll } = styler;
2814
+ if (string.includes("\x1B")) {
2815
+ while (styler !== undefined) {
2816
+ string = stringReplaceAll(string, styler.close, styler.open);
2817
+ styler = styler.parent;
2818
+ }
2819
+ }
2820
+ const lfIndex = string.indexOf(`
2821
+ `);
2822
+ if (lfIndex !== -1) {
2823
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2824
+ }
2825
+ return openAll + string + closeAll;
2826
+ };
2827
+ Object.defineProperties(createChalk.prototype, styles2);
2828
+ var chalk = createChalk();
2829
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2830
+ var source_default = chalk;
2831
+
2832
+ // src/services/configService.ts
2833
+ var import_ini = __toESM(require_ini(), 1);
2834
+
2835
+ // src/utils/constants.ts
2836
+ import { homedir } from "os";
2837
+ var VCS_NAME = "brch";
2838
+ var VCS_CONFIG = ".brchconfig";
2839
+ var HOME_DIR = homedir();
2840
+ var GLOBAL_CONFIG_PATH = `${HOME_DIR}/${VCS_CONFIG}`;
2841
+ var VCS_DIR = ".brch";
2842
+ var OBJECT_DIR = `${VCS_DIR}/objects`;
2843
+ var HEAD_FILE = `${VCS_DIR}/HEAD`;
2844
+
2845
+ // src/services/configService.ts
2846
+ var setConfig = async ({ scopeKey, value, isGlobal }) => {
2847
+ const configPath = isGlobal ? GLOBAL_CONFIG_PATH : VCS_CONFIG;
2848
+ if (!existsSync(configPath)) {
2849
+ writeFileSync(configPath, "");
2850
+ }
2851
+ const configFileContent = readConfigFile({ isGlobal });
2852
+ const configFileJson = import_ini.parse(configFileContent || "");
2853
+ const scopeKeyAttrs = scopeKey.split(".");
2854
+ const scope = scopeKeyAttrs[0];
2855
+ const key = scopeKeyAttrs[1];
2856
+ if (!configFileJson[scope]) {
2857
+ configFileJson[scope] = {};
2858
+ }
2859
+ configFileJson[scope][key] = value;
2860
+ const configFileString = import_ini.stringify(configFileJson);
2861
+ writeFileSync(configPath, configFileString);
2862
+ console.log(source_default.green("Configuration set successfully."));
2863
+ };
2864
+ var readConfigFile = ({ isGlobal }) => {
2865
+ return readFileSync(isGlobal ? GLOBAL_CONFIG_PATH : VCS_CONFIG, {
2866
+ encoding: "utf-8"
2867
+ });
2868
+ };
2869
+
2870
+ // src/commands/configCommand.ts
2871
+ var configCommand = new Command("config").description("Manage repository or global configuration").option("--global", "Set global configuration").addCommand(new Command("set").argument("<scopeKey>", "Configuration key (e.g. user.name)").argument("<value>", "Configuration value").description("Set a configuration value").action(async function(scopeKey, value) {
2872
+ await setConfig({ scopeKey, value, isGlobal: this.parent?.opts().global ?? false });
2873
+ }));
2874
+
2875
+ // src/services/initService.ts
2876
+ import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
2877
+ var initRepo = async () => {
2878
+ try {
2879
+ mkdirSync(VCS_DIR);
2880
+ mkdirSync(OBJECT_DIR);
2881
+ writeFileSync2(HEAD_FILE, "ref: refs/heads/master");
2882
+ console.log("Initialized empty " + source_default.green("dlt") + " repository in " + source_default.green(process.cwd() + "/" + VCS_DIR));
2883
+ } catch (error) {
2884
+ if (error.code === "EEXIST") {
2885
+ console.log(source_default.red("dlt repository already initialized."));
2886
+ return;
2887
+ }
2888
+ console.error("Error initializing repository:", error);
2889
+ }
2890
+ };
2891
+
2892
+ // src/commands/initCommand.ts
2893
+ var initCommand = new Command("init").description("Initialize a new repository").action(async () => {
2894
+ initRepo();
2895
+ });
2896
+
2897
+ // src/services/addService.ts
2898
+ import { createHash } from "node:crypto";
2899
+ import { existsSync as existsSync2 } from "node:fs";
2900
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
2901
+ import { join, relative, resolve, sep } from "node:path";
2902
+ var INDEX_FILE = "index.json";
2903
+ var addFiles = async (paths) => {
2904
+ const repoRoot = process.cwd();
2905
+ const brchPath = join(repoRoot, VCS_DIR);
2906
+ if (!existsSync2(brchPath)) {
2907
+ throw new Error("Not a brch repository (or any of the parent directories). Run `brch init` first.");
2908
+ }
2909
+ const objectDir = join(repoRoot, OBJECT_DIR);
2910
+ await mkdir(objectDir, { recursive: true });
2911
+ const { filesToStage, missing } = await collectFiles(paths, repoRoot);
2912
+ const indexPath = join(brchPath, INDEX_FILE);
2913
+ const indexEntries = await readIndex(indexPath);
2914
+ const staged = [];
2915
+ const skipped = [...missing];
2916
+ for (const absPath of filesToStage) {
2917
+ const relPath = normalizeRelativePath(relative(repoRoot, absPath));
2918
+ const fileBuffer = await readFile(absPath);
2919
+ const hash = createHash("sha1").update(fileBuffer).digest("hex");
2920
+ const objectPath = join(objectDir, hash);
2921
+ if (!existsSync2(objectPath)) {
2922
+ await writeFile(objectPath, fileBuffer);
2923
+ }
2924
+ if (indexEntries[relPath] === hash) {
2925
+ skipped.push(relPath);
2926
+ continue;
2927
+ }
2928
+ indexEntries[relPath] = hash;
2929
+ staged.push(relPath);
2930
+ }
2931
+ await writeFile(indexPath, JSON.stringify(indexEntries, null, 2));
2932
+ return { staged, skipped };
2933
+ };
2934
+ var collectFiles = async (targets, repoRoot) => {
2935
+ const filesToStage = new Set;
2936
+ const missing = [];
2937
+ for (const target of targets) {
2938
+ const absTargetPath = resolve(repoRoot, target);
2939
+ if (!isWithinRepo(absTargetPath, repoRoot)) {
2940
+ missing.push(target);
2941
+ continue;
2942
+ }
2943
+ try {
2944
+ const targetStat = await stat(absTargetPath);
2945
+ if (targetStat.isDirectory()) {
2946
+ await walkDirectory(absTargetPath, repoRoot, filesToStage);
2947
+ } else if (targetStat.isFile()) {
2948
+ filesToStage.add(absTargetPath);
2949
+ }
2950
+ } catch (error) {
2951
+ missing.push(target);
2952
+ }
2953
+ }
2954
+ return { filesToStage, missing };
2955
+ };
2956
+ var walkDirectory = async (dir, repoRoot, collector) => {
2957
+ const entries = await readdir(dir, { withFileTypes: true });
2958
+ for (const entry of entries) {
2959
+ const entryPath = join(dir, entry.name);
2960
+ if (shouldIgnore(entryPath, repoRoot)) {
2961
+ continue;
2962
+ }
2963
+ if (entry.isDirectory()) {
2964
+ await walkDirectory(entryPath, repoRoot, collector);
2965
+ } else if (entry.isFile()) {
2966
+ collector.add(entryPath);
2967
+ }
2968
+ }
2969
+ };
2970
+ var shouldIgnore = (absPath, repoRoot) => {
2971
+ const relPath = normalizeRelativePath(relative(repoRoot, absPath));
2972
+ if (relPath === "") {
2973
+ return false;
2974
+ }
2975
+ return relPath === VCS_DIR || relPath.startsWith(`${VCS_DIR}/`);
2976
+ };
2977
+ var isWithinRepo = (absPath, repoRoot) => {
2978
+ const relPath = relative(repoRoot, absPath);
2979
+ if (relPath === "") {
2980
+ return true;
2981
+ }
2982
+ return !relPath.startsWith("..") && !relPath.includes(`..${sep}`);
2983
+ };
2984
+ var normalizeRelativePath = (pathValue) => {
2985
+ return pathValue.split("\\").join("/");
2986
+ };
2987
+ var readIndex = async (indexPath) => {
2988
+ try {
2989
+ const content = await readFile(indexPath, "utf-8");
2990
+ return content ? JSON.parse(content) : {};
2991
+ } catch (error) {
2992
+ return {};
2993
+ }
2994
+ };
2995
+
2996
+ // src/commands/addCommand.ts
2997
+ var addCommand = new Command("add").argument("<paths...>", 'Files or directories to add to staging (supports "." for current directory)').description("Add files to the staging area").action(async (paths) => {
2998
+ const targets = paths;
2999
+ try {
3000
+ const { staged, skipped } = await addFiles(targets);
3001
+ if (staged.length > 0) {
3002
+ console.log(source_default.green("Staged:"));
3003
+ staged.forEach((path) => console.log(` ${path}`));
3004
+ }
3005
+ if (skipped.length > 0) {
3006
+ console.log(source_default.yellow("Skipped (unchanged or not found):"));
3007
+ skipped.forEach((path) => console.log(` ${path}`));
3008
+ }
3009
+ if (staged.length === 0 && skipped.length === 0) {
3010
+ console.log(source_default.yellow("Nothing to add."));
3011
+ }
3012
+ } catch (error) {
3013
+ console.error(source_default.red(error.message));
3014
+ process.exitCode = 1;
3015
+ }
3016
+ });
3017
+
3018
+ // src/commands/index.ts
3019
+ var registerCommands = (program2) => {
3020
+ program2.addCommand(configCommand);
3021
+ program2.addCommand(initCommand);
3022
+ program2.addCommand(addCommand);
3023
+ };
3024
+
3025
+ // src/index.ts
3026
+ program.name(VCS_NAME).description("A simple VCS").version("0.0.1");
3027
+ registerCommands(program);
3028
+ program.parse(process.argv);