xmemory-cli 0.1.0

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