@oriro/cli 1.0.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.
Files changed (2) hide show
  1. package/dist/index.js +4889 -0
  2. package/package.json +19 -0
package/dist/index.js ADDED
@@ -0,0 +1,4889 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as ___cr}from'module';const require=___cr(import.meta.url);
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key2 of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
22
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js
36
+ var require_error = __commonJS({
37
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js"(exports) {
38
+ var CommanderError2 = class extends Error {
39
+ /**
40
+ * Constructs the CommanderError class
41
+ * @param {number} exitCode suggested exit code which could be used with process.exit
42
+ * @param {string} code an id string representing the error
43
+ * @param {string} message human-readable description of the error
44
+ */
45
+ constructor(exitCode, code, message) {
46
+ super(message);
47
+ Error.captureStackTrace(this, this.constructor);
48
+ this.name = this.constructor.name;
49
+ this.code = code;
50
+ this.exitCode = exitCode;
51
+ this.nestedError = void 0;
52
+ }
53
+ };
54
+ var InvalidArgumentError2 = class extends CommanderError2 {
55
+ /**
56
+ * Constructs the InvalidArgumentError class
57
+ * @param {string} [message] explanation of why argument is invalid
58
+ */
59
+ constructor(message) {
60
+ super(1, "commander.invalidArgument", message);
61
+ Error.captureStackTrace(this, this.constructor);
62
+ this.name = this.constructor.name;
63
+ }
64
+ };
65
+ exports.CommanderError = CommanderError2;
66
+ exports.InvalidArgumentError = InvalidArgumentError2;
67
+ }
68
+ });
69
+
70
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js
71
+ var require_argument = __commonJS({
72
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js"(exports) {
73
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
74
+ var Argument2 = class {
75
+ /**
76
+ * Initialize a new command argument with the given name and description.
77
+ * The default is that the argument is required, and you can explicitly
78
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
79
+ *
80
+ * @param {string} name
81
+ * @param {string} [description]
82
+ */
83
+ constructor(name, description) {
84
+ this.description = description || "";
85
+ this.variadic = false;
86
+ this.parseArg = void 0;
87
+ this.defaultValue = void 0;
88
+ this.defaultValueDescription = void 0;
89
+ this.argChoices = void 0;
90
+ switch (name[0]) {
91
+ case "<":
92
+ this.required = true;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ case "[":
96
+ this.required = false;
97
+ this._name = name.slice(1, -1);
98
+ break;
99
+ default:
100
+ this.required = true;
101
+ this._name = name;
102
+ break;
103
+ }
104
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
105
+ this.variadic = true;
106
+ this._name = this._name.slice(0, -3);
107
+ }
108
+ }
109
+ /**
110
+ * Return argument name.
111
+ *
112
+ * @return {string}
113
+ */
114
+ name() {
115
+ return this._name;
116
+ }
117
+ /**
118
+ * @package
119
+ */
120
+ _concatValue(value, previous) {
121
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
122
+ return [value];
123
+ }
124
+ return previous.concat(value);
125
+ }
126
+ /**
127
+ * Set the default value, and optionally supply the description to be displayed in the help.
128
+ *
129
+ * @param {*} value
130
+ * @param {string} [description]
131
+ * @return {Argument}
132
+ */
133
+ default(value, description) {
134
+ this.defaultValue = value;
135
+ this.defaultValueDescription = description;
136
+ return this;
137
+ }
138
+ /**
139
+ * Set the custom handler for processing CLI command arguments into argument values.
140
+ *
141
+ * @param {Function} [fn]
142
+ * @return {Argument}
143
+ */
144
+ argParser(fn) {
145
+ this.parseArg = fn;
146
+ return this;
147
+ }
148
+ /**
149
+ * Only allow argument value to be one of choices.
150
+ *
151
+ * @param {string[]} values
152
+ * @return {Argument}
153
+ */
154
+ choices(values) {
155
+ this.argChoices = values.slice();
156
+ this.parseArg = (arg, previous) => {
157
+ if (!this.argChoices.includes(arg)) {
158
+ throw new InvalidArgumentError2(
159
+ `Allowed choices are ${this.argChoices.join(", ")}.`
160
+ );
161
+ }
162
+ if (this.variadic) {
163
+ return this._concatValue(arg, previous);
164
+ }
165
+ return arg;
166
+ };
167
+ return this;
168
+ }
169
+ /**
170
+ * Make argument required.
171
+ *
172
+ * @returns {Argument}
173
+ */
174
+ argRequired() {
175
+ this.required = true;
176
+ return this;
177
+ }
178
+ /**
179
+ * Make argument optional.
180
+ *
181
+ * @returns {Argument}
182
+ */
183
+ argOptional() {
184
+ this.required = false;
185
+ return this;
186
+ }
187
+ };
188
+ function humanReadableArgName(arg) {
189
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
190
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
191
+ }
192
+ exports.Argument = Argument2;
193
+ exports.humanReadableArgName = humanReadableArgName;
194
+ }
195
+ });
196
+
197
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js
198
+ var require_help = __commonJS({
199
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js"(exports) {
200
+ var { humanReadableArgName } = require_argument();
201
+ var Help2 = class {
202
+ constructor() {
203
+ this.helpWidth = void 0;
204
+ this.sortSubcommands = false;
205
+ this.sortOptions = false;
206
+ this.showGlobalOptions = false;
207
+ }
208
+ /**
209
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
210
+ *
211
+ * @param {Command} cmd
212
+ * @returns {Command[]}
213
+ */
214
+ visibleCommands(cmd) {
215
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
216
+ const helpCommand = cmd._getHelpCommand();
217
+ if (helpCommand && !helpCommand._hidden) {
218
+ visibleCommands.push(helpCommand);
219
+ }
220
+ if (this.sortSubcommands) {
221
+ visibleCommands.sort((a, b) => {
222
+ return a.name().localeCompare(b.name());
223
+ });
224
+ }
225
+ return visibleCommands;
226
+ }
227
+ /**
228
+ * Compare options for sort.
229
+ *
230
+ * @param {Option} a
231
+ * @param {Option} b
232
+ * @returns {number}
233
+ */
234
+ compareOptions(a, b) {
235
+ const getSortKey = (option) => {
236
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
237
+ };
238
+ return getSortKey(a).localeCompare(getSortKey(b));
239
+ }
240
+ /**
241
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
242
+ *
243
+ * @param {Command} cmd
244
+ * @returns {Option[]}
245
+ */
246
+ visibleOptions(cmd) {
247
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
248
+ const helpOption = cmd._getHelpOption();
249
+ if (helpOption && !helpOption.hidden) {
250
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
251
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
252
+ if (!removeShort && !removeLong) {
253
+ visibleOptions.push(helpOption);
254
+ } else if (helpOption.long && !removeLong) {
255
+ visibleOptions.push(
256
+ cmd.createOption(helpOption.long, helpOption.description)
257
+ );
258
+ } else if (helpOption.short && !removeShort) {
259
+ visibleOptions.push(
260
+ cmd.createOption(helpOption.short, helpOption.description)
261
+ );
262
+ }
263
+ }
264
+ if (this.sortOptions) {
265
+ visibleOptions.sort(this.compareOptions);
266
+ }
267
+ return visibleOptions;
268
+ }
269
+ /**
270
+ * Get an array of the visible global options. (Not including help.)
271
+ *
272
+ * @param {Command} cmd
273
+ * @returns {Option[]}
274
+ */
275
+ visibleGlobalOptions(cmd) {
276
+ if (!this.showGlobalOptions) return [];
277
+ const globalOptions = [];
278
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
279
+ const visibleOptions = ancestorCmd.options.filter(
280
+ (option) => !option.hidden
281
+ );
282
+ globalOptions.push(...visibleOptions);
283
+ }
284
+ if (this.sortOptions) {
285
+ globalOptions.sort(this.compareOptions);
286
+ }
287
+ return globalOptions;
288
+ }
289
+ /**
290
+ * Get an array of the arguments if any have a description.
291
+ *
292
+ * @param {Command} cmd
293
+ * @returns {Argument[]}
294
+ */
295
+ visibleArguments(cmd) {
296
+ if (cmd._argsDescription) {
297
+ cmd.registeredArguments.forEach((argument) => {
298
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
299
+ });
300
+ }
301
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
302
+ return cmd.registeredArguments;
303
+ }
304
+ return [];
305
+ }
306
+ /**
307
+ * Get the command term to show in the list of subcommands.
308
+ *
309
+ * @param {Command} cmd
310
+ * @returns {string}
311
+ */
312
+ subcommandTerm(cmd) {
313
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
314
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
315
+ (args ? " " + args : "");
316
+ }
317
+ /**
318
+ * Get the option term to show in the list of options.
319
+ *
320
+ * @param {Option} option
321
+ * @returns {string}
322
+ */
323
+ optionTerm(option) {
324
+ return option.flags;
325
+ }
326
+ /**
327
+ * Get the argument term to show in the list of arguments.
328
+ *
329
+ * @param {Argument} argument
330
+ * @returns {string}
331
+ */
332
+ argumentTerm(argument) {
333
+ return argument.name();
334
+ }
335
+ /**
336
+ * Get the longest command term length.
337
+ *
338
+ * @param {Command} cmd
339
+ * @param {Help} helper
340
+ * @returns {number}
341
+ */
342
+ longestSubcommandTermLength(cmd, helper) {
343
+ return helper.visibleCommands(cmd).reduce((max, command) => {
344
+ return Math.max(max, helper.subcommandTerm(command).length);
345
+ }, 0);
346
+ }
347
+ /**
348
+ * Get the longest option term length.
349
+ *
350
+ * @param {Command} cmd
351
+ * @param {Help} helper
352
+ * @returns {number}
353
+ */
354
+ longestOptionTermLength(cmd, helper) {
355
+ return helper.visibleOptions(cmd).reduce((max, option) => {
356
+ return Math.max(max, helper.optionTerm(option).length);
357
+ }, 0);
358
+ }
359
+ /**
360
+ * Get the longest global option term length.
361
+ *
362
+ * @param {Command} cmd
363
+ * @param {Help} helper
364
+ * @returns {number}
365
+ */
366
+ longestGlobalOptionTermLength(cmd, helper) {
367
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
368
+ return Math.max(max, helper.optionTerm(option).length);
369
+ }, 0);
370
+ }
371
+ /**
372
+ * Get the longest argument term length.
373
+ *
374
+ * @param {Command} cmd
375
+ * @param {Help} helper
376
+ * @returns {number}
377
+ */
378
+ longestArgumentTermLength(cmd, helper) {
379
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
380
+ return Math.max(max, helper.argumentTerm(argument).length);
381
+ }, 0);
382
+ }
383
+ /**
384
+ * Get the command usage to be displayed at the top of the built-in help.
385
+ *
386
+ * @param {Command} cmd
387
+ * @returns {string}
388
+ */
389
+ commandUsage(cmd) {
390
+ let cmdName = cmd._name;
391
+ if (cmd._aliases[0]) {
392
+ cmdName = cmdName + "|" + cmd._aliases[0];
393
+ }
394
+ let ancestorCmdNames = "";
395
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
396
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
397
+ }
398
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
399
+ }
400
+ /**
401
+ * Get the description for the command.
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ commandDescription(cmd) {
407
+ return cmd.description();
408
+ }
409
+ /**
410
+ * Get the subcommand summary to show in the list of subcommands.
411
+ * (Fallback to description for backwards compatibility.)
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ subcommandDescription(cmd) {
417
+ return cmd.summary() || cmd.description();
418
+ }
419
+ /**
420
+ * Get the option description to show in the list of options.
421
+ *
422
+ * @param {Option} option
423
+ * @return {string}
424
+ */
425
+ optionDescription(option) {
426
+ const extraInfo = [];
427
+ if (option.argChoices) {
428
+ extraInfo.push(
429
+ // use stringify to match the display of the default value
430
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
431
+ );
432
+ }
433
+ if (option.defaultValue !== void 0) {
434
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
435
+ if (showDefault) {
436
+ extraInfo.push(
437
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
438
+ );
439
+ }
440
+ }
441
+ if (option.presetArg !== void 0 && option.optional) {
442
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
+ }
444
+ if (option.envVar !== void 0) {
445
+ extraInfo.push(`env: ${option.envVar}`);
446
+ }
447
+ if (extraInfo.length > 0) {
448
+ return `${option.description} (${extraInfo.join(", ")})`;
449
+ }
450
+ return option.description;
451
+ }
452
+ /**
453
+ * Get the argument description to show in the list of arguments.
454
+ *
455
+ * @param {Argument} argument
456
+ * @return {string}
457
+ */
458
+ argumentDescription(argument) {
459
+ const extraInfo = [];
460
+ if (argument.argChoices) {
461
+ extraInfo.push(
462
+ // use stringify to match the display of the default value
463
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
464
+ );
465
+ }
466
+ if (argument.defaultValue !== void 0) {
467
+ extraInfo.push(
468
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
469
+ );
470
+ }
471
+ if (extraInfo.length > 0) {
472
+ const extraDescripton = `(${extraInfo.join(", ")})`;
473
+ if (argument.description) {
474
+ return `${argument.description} ${extraDescripton}`;
475
+ }
476
+ return extraDescripton;
477
+ }
478
+ return argument.description;
479
+ }
480
+ /**
481
+ * Generate the built-in help text.
482
+ *
483
+ * @param {Command} cmd
484
+ * @param {Help} helper
485
+ * @returns {string}
486
+ */
487
+ formatHelp(cmd, helper) {
488
+ const termWidth = helper.padWidth(cmd, helper);
489
+ const helpWidth = helper.helpWidth || 80;
490
+ const itemIndentWidth = 2;
491
+ const itemSeparatorWidth = 2;
492
+ function formatItem(term, description) {
493
+ if (description) {
494
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
495
+ return helper.wrap(
496
+ fullText,
497
+ helpWidth - itemIndentWidth,
498
+ termWidth + itemSeparatorWidth
499
+ );
500
+ }
501
+ return term;
502
+ }
503
+ function formatList(textArray) {
504
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
505
+ }
506
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
507
+ const commandDescription = helper.commandDescription(cmd);
508
+ if (commandDescription.length > 0) {
509
+ output = output.concat([
510
+ helper.wrap(commandDescription, helpWidth, 0),
511
+ ""
512
+ ]);
513
+ }
514
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
515
+ return formatItem(
516
+ helper.argumentTerm(argument),
517
+ helper.argumentDescription(argument)
518
+ );
519
+ });
520
+ if (argumentList.length > 0) {
521
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
522
+ }
523
+ const optionList = helper.visibleOptions(cmd).map((option) => {
524
+ return formatItem(
525
+ helper.optionTerm(option),
526
+ helper.optionDescription(option)
527
+ );
528
+ });
529
+ if (optionList.length > 0) {
530
+ output = output.concat(["Options:", formatList(optionList), ""]);
531
+ }
532
+ if (this.showGlobalOptions) {
533
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
534
+ return formatItem(
535
+ helper.optionTerm(option),
536
+ helper.optionDescription(option)
537
+ );
538
+ });
539
+ if (globalOptionList.length > 0) {
540
+ output = output.concat([
541
+ "Global Options:",
542
+ formatList(globalOptionList),
543
+ ""
544
+ ]);
545
+ }
546
+ }
547
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
548
+ return formatItem(
549
+ helper.subcommandTerm(cmd2),
550
+ helper.subcommandDescription(cmd2)
551
+ );
552
+ });
553
+ if (commandList.length > 0) {
554
+ output = output.concat(["Commands:", formatList(commandList), ""]);
555
+ }
556
+ return output.join("\n");
557
+ }
558
+ /**
559
+ * Calculate the pad width from the maximum term length.
560
+ *
561
+ * @param {Command} cmd
562
+ * @param {Help} helper
563
+ * @returns {number}
564
+ */
565
+ padWidth(cmd, helper) {
566
+ return Math.max(
567
+ helper.longestOptionTermLength(cmd, helper),
568
+ helper.longestGlobalOptionTermLength(cmd, helper),
569
+ helper.longestSubcommandTermLength(cmd, helper),
570
+ helper.longestArgumentTermLength(cmd, helper)
571
+ );
572
+ }
573
+ /**
574
+ * Wrap the given string to width characters per line, with lines after the first indented.
575
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
576
+ *
577
+ * @param {string} str
578
+ * @param {number} width
579
+ * @param {number} indent
580
+ * @param {number} [minColumnWidth=40]
581
+ * @return {string}
582
+ *
583
+ */
584
+ wrap(str, width, indent, minColumnWidth = 40) {
585
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
586
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
587
+ if (str.match(manualIndent)) return str;
588
+ const columnWidth = width - indent;
589
+ if (columnWidth < minColumnWidth) return str;
590
+ const leadingStr = str.slice(0, indent);
591
+ const columnText = str.slice(indent).replace("\r\n", "\n");
592
+ const indentString = " ".repeat(indent);
593
+ const zeroWidthSpace = "\u200B";
594
+ const breaks = `\\s${zeroWidthSpace}`;
595
+ const regex = new RegExp(
596
+ `
597
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
598
+ "g"
599
+ );
600
+ const lines = columnText.match(regex) || [];
601
+ return leadingStr + lines.map((line, i) => {
602
+ if (line === "\n") return "";
603
+ return (i > 0 ? indentString : "") + line.trimEnd();
604
+ }).join("\n");
605
+ }
606
+ };
607
+ exports.Help = Help2;
608
+ }
609
+ });
610
+
611
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js
612
+ var require_option = __commonJS({
613
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js"(exports) {
614
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
615
+ var Option2 = class {
616
+ /**
617
+ * Initialize a new `Option` with the given `flags` and `description`.
618
+ *
619
+ * @param {string} flags
620
+ * @param {string} [description]
621
+ */
622
+ constructor(flags, description) {
623
+ this.flags = flags;
624
+ this.description = description || "";
625
+ this.required = flags.includes("<");
626
+ this.optional = flags.includes("[");
627
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
628
+ this.mandatory = false;
629
+ const optionFlags = splitOptionFlags(flags);
630
+ this.short = optionFlags.shortFlag;
631
+ this.long = optionFlags.longFlag;
632
+ this.negate = false;
633
+ if (this.long) {
634
+ this.negate = this.long.startsWith("--no-");
635
+ }
636
+ this.defaultValue = void 0;
637
+ this.defaultValueDescription = void 0;
638
+ this.presetArg = void 0;
639
+ this.envVar = void 0;
640
+ this.parseArg = void 0;
641
+ this.hidden = false;
642
+ this.argChoices = void 0;
643
+ this.conflictsWith = [];
644
+ this.implied = void 0;
645
+ }
646
+ /**
647
+ * Set the default value, and optionally supply the description to be displayed in the help.
648
+ *
649
+ * @param {*} value
650
+ * @param {string} [description]
651
+ * @return {Option}
652
+ */
653
+ default(value, description) {
654
+ this.defaultValue = value;
655
+ this.defaultValueDescription = description;
656
+ return this;
657
+ }
658
+ /**
659
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
660
+ * The custom processing (parseArg) is called.
661
+ *
662
+ * @example
663
+ * new Option('--color').default('GREYSCALE').preset('RGB');
664
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
665
+ *
666
+ * @param {*} arg
667
+ * @return {Option}
668
+ */
669
+ preset(arg) {
670
+ this.presetArg = arg;
671
+ return this;
672
+ }
673
+ /**
674
+ * Add option name(s) that conflict with this option.
675
+ * An error will be displayed if conflicting options are found during parsing.
676
+ *
677
+ * @example
678
+ * new Option('--rgb').conflicts('cmyk');
679
+ * new Option('--js').conflicts(['ts', 'jsx']);
680
+ *
681
+ * @param {(string | string[])} names
682
+ * @return {Option}
683
+ */
684
+ conflicts(names) {
685
+ this.conflictsWith = this.conflictsWith.concat(names);
686
+ return this;
687
+ }
688
+ /**
689
+ * Specify implied option values for when this option is set and the implied options are not.
690
+ *
691
+ * The custom processing (parseArg) is not called on the implied values.
692
+ *
693
+ * @example
694
+ * program
695
+ * .addOption(new Option('--log', 'write logging information to file'))
696
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
697
+ *
698
+ * @param {object} impliedOptionValues
699
+ * @return {Option}
700
+ */
701
+ implies(impliedOptionValues) {
702
+ let newImplied = impliedOptionValues;
703
+ if (typeof impliedOptionValues === "string") {
704
+ newImplied = { [impliedOptionValues]: true };
705
+ }
706
+ this.implied = Object.assign(this.implied || {}, newImplied);
707
+ return this;
708
+ }
709
+ /**
710
+ * Set environment variable to check for option value.
711
+ *
712
+ * An environment variable is only used if when processed the current option value is
713
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
714
+ *
715
+ * @param {string} name
716
+ * @return {Option}
717
+ */
718
+ env(name) {
719
+ this.envVar = name;
720
+ return this;
721
+ }
722
+ /**
723
+ * Set the custom handler for processing CLI option arguments into option values.
724
+ *
725
+ * @param {Function} [fn]
726
+ * @return {Option}
727
+ */
728
+ argParser(fn) {
729
+ this.parseArg = fn;
730
+ return this;
731
+ }
732
+ /**
733
+ * Whether the option is mandatory and must have a value after parsing.
734
+ *
735
+ * @param {boolean} [mandatory=true]
736
+ * @return {Option}
737
+ */
738
+ makeOptionMandatory(mandatory = true) {
739
+ this.mandatory = !!mandatory;
740
+ return this;
741
+ }
742
+ /**
743
+ * Hide option in help.
744
+ *
745
+ * @param {boolean} [hide=true]
746
+ * @return {Option}
747
+ */
748
+ hideHelp(hide = true) {
749
+ this.hidden = !!hide;
750
+ return this;
751
+ }
752
+ /**
753
+ * @package
754
+ */
755
+ _concatValue(value, previous) {
756
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
757
+ return [value];
758
+ }
759
+ return previous.concat(value);
760
+ }
761
+ /**
762
+ * Only allow option value to be one of choices.
763
+ *
764
+ * @param {string[]} values
765
+ * @return {Option}
766
+ */
767
+ choices(values) {
768
+ this.argChoices = values.slice();
769
+ this.parseArg = (arg, previous) => {
770
+ if (!this.argChoices.includes(arg)) {
771
+ throw new InvalidArgumentError2(
772
+ `Allowed choices are ${this.argChoices.join(", ")}.`
773
+ );
774
+ }
775
+ if (this.variadic) {
776
+ return this._concatValue(arg, previous);
777
+ }
778
+ return arg;
779
+ };
780
+ return this;
781
+ }
782
+ /**
783
+ * Return option name.
784
+ *
785
+ * @return {string}
786
+ */
787
+ name() {
788
+ if (this.long) {
789
+ return this.long.replace(/^--/, "");
790
+ }
791
+ return this.short.replace(/^-/, "");
792
+ }
793
+ /**
794
+ * Return option name, in a camelcase format that can be used
795
+ * as a object attribute key.
796
+ *
797
+ * @return {string}
798
+ */
799
+ attributeName() {
800
+ return camelcase(this.name().replace(/^no-/, ""));
801
+ }
802
+ /**
803
+ * Check if `arg` matches the short or long flag.
804
+ *
805
+ * @param {string} arg
806
+ * @return {boolean}
807
+ * @package
808
+ */
809
+ is(arg) {
810
+ return this.short === arg || this.long === arg;
811
+ }
812
+ /**
813
+ * Return whether a boolean option.
814
+ *
815
+ * Options are one of boolean, negated, required argument, or optional argument.
816
+ *
817
+ * @return {boolean}
818
+ * @package
819
+ */
820
+ isBoolean() {
821
+ return !this.required && !this.optional && !this.negate;
822
+ }
823
+ };
824
+ var DualOptions = class {
825
+ /**
826
+ * @param {Option[]} options
827
+ */
828
+ constructor(options) {
829
+ this.positiveOptions = /* @__PURE__ */ new Map();
830
+ this.negativeOptions = /* @__PURE__ */ new Map();
831
+ this.dualOptions = /* @__PURE__ */ new Set();
832
+ options.forEach((option) => {
833
+ if (option.negate) {
834
+ this.negativeOptions.set(option.attributeName(), option);
835
+ } else {
836
+ this.positiveOptions.set(option.attributeName(), option);
837
+ }
838
+ });
839
+ this.negativeOptions.forEach((value, key2) => {
840
+ if (this.positiveOptions.has(key2)) {
841
+ this.dualOptions.add(key2);
842
+ }
843
+ });
844
+ }
845
+ /**
846
+ * Did the value come from the option, and not from possible matching dual option?
847
+ *
848
+ * @param {*} value
849
+ * @param {Option} option
850
+ * @returns {boolean}
851
+ */
852
+ valueFromOption(value, option) {
853
+ const optionKey = option.attributeName();
854
+ if (!this.dualOptions.has(optionKey)) return true;
855
+ const preset = this.negativeOptions.get(optionKey).presetArg;
856
+ const negativeValue = preset !== void 0 ? preset : false;
857
+ return option.negate === (negativeValue === value);
858
+ }
859
+ };
860
+ function camelcase(str) {
861
+ return str.split("-").reduce((str2, word) => {
862
+ return str2 + word[0].toUpperCase() + word.slice(1);
863
+ });
864
+ }
865
+ function splitOptionFlags(flags) {
866
+ let shortFlag;
867
+ let longFlag;
868
+ const flagParts = flags.split(/[ |,]+/);
869
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
870
+ shortFlag = flagParts.shift();
871
+ longFlag = flagParts.shift();
872
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
873
+ shortFlag = longFlag;
874
+ longFlag = void 0;
875
+ }
876
+ return { shortFlag, longFlag };
877
+ }
878
+ exports.Option = Option2;
879
+ exports.DualOptions = DualOptions;
880
+ }
881
+ });
882
+
883
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js
884
+ var require_suggestSimilar = __commonJS({
885
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
886
+ var maxDistance = 3;
887
+ function editDistance(a, b) {
888
+ if (Math.abs(a.length - b.length) > maxDistance)
889
+ return Math.max(a.length, b.length);
890
+ const d = [];
891
+ for (let i = 0; i <= a.length; i++) {
892
+ d[i] = [i];
893
+ }
894
+ for (let j = 0; j <= b.length; j++) {
895
+ d[0][j] = j;
896
+ }
897
+ for (let j = 1; j <= b.length; j++) {
898
+ for (let i = 1; i <= a.length; i++) {
899
+ let cost = 1;
900
+ if (a[i - 1] === b[j - 1]) {
901
+ cost = 0;
902
+ } else {
903
+ cost = 1;
904
+ }
905
+ d[i][j] = Math.min(
906
+ d[i - 1][j] + 1,
907
+ // deletion
908
+ d[i][j - 1] + 1,
909
+ // insertion
910
+ d[i - 1][j - 1] + cost
911
+ // substitution
912
+ );
913
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
914
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
915
+ }
916
+ }
917
+ }
918
+ return d[a.length][b.length];
919
+ }
920
+ function suggestSimilar(word, candidates) {
921
+ if (!candidates || candidates.length === 0) return "";
922
+ candidates = Array.from(new Set(candidates));
923
+ const searchingOptions = word.startsWith("--");
924
+ if (searchingOptions) {
925
+ word = word.slice(2);
926
+ candidates = candidates.map((candidate) => candidate.slice(2));
927
+ }
928
+ let similar = [];
929
+ let bestDistance = maxDistance;
930
+ const minSimilarity = 0.4;
931
+ candidates.forEach((candidate) => {
932
+ if (candidate.length <= 1) return;
933
+ const distance = editDistance(word, candidate);
934
+ const length = Math.max(word.length, candidate.length);
935
+ const similarity = (length - distance) / length;
936
+ if (similarity > minSimilarity) {
937
+ if (distance < bestDistance) {
938
+ bestDistance = distance;
939
+ similar = [candidate];
940
+ } else if (distance === bestDistance) {
941
+ similar.push(candidate);
942
+ }
943
+ }
944
+ });
945
+ similar.sort((a, b) => a.localeCompare(b));
946
+ if (searchingOptions) {
947
+ similar = similar.map((candidate) => `--${candidate}`);
948
+ }
949
+ if (similar.length > 1) {
950
+ return `
951
+ (Did you mean one of ${similar.join(", ")}?)`;
952
+ }
953
+ if (similar.length === 1) {
954
+ return `
955
+ (Did you mean ${similar[0]}?)`;
956
+ }
957
+ return "";
958
+ }
959
+ exports.suggestSimilar = suggestSimilar;
960
+ }
961
+ });
962
+
963
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js
964
+ var require_command = __commonJS({
965
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js"(exports) {
966
+ var EventEmitter = __require("node:events").EventEmitter;
967
+ var childProcess = __require("node:child_process");
968
+ var path = __require("node:path");
969
+ var fs = __require("node:fs");
970
+ var process3 = __require("node:process");
971
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
972
+ var { CommanderError: CommanderError2 } = require_error();
973
+ var { Help: Help2 } = require_help();
974
+ var { Option: Option2, DualOptions } = require_option();
975
+ var { suggestSimilar } = require_suggestSimilar();
976
+ var Command2 = class _Command extends EventEmitter {
977
+ /**
978
+ * Initialize a new `Command`.
979
+ *
980
+ * @param {string} [name]
981
+ */
982
+ constructor(name) {
983
+ super();
984
+ this.commands = [];
985
+ this.options = [];
986
+ this.parent = null;
987
+ this._allowUnknownOption = false;
988
+ this._allowExcessArguments = true;
989
+ this.registeredArguments = [];
990
+ this._args = this.registeredArguments;
991
+ this.args = [];
992
+ this.rawArgs = [];
993
+ this.processedArgs = [];
994
+ this._scriptPath = null;
995
+ this._name = name || "";
996
+ this._optionValues = {};
997
+ this._optionValueSources = {};
998
+ this._storeOptionsAsProperties = false;
999
+ this._actionHandler = null;
1000
+ this._executableHandler = false;
1001
+ this._executableFile = null;
1002
+ this._executableDir = null;
1003
+ this._defaultCommandName = null;
1004
+ this._exitCallback = null;
1005
+ this._aliases = [];
1006
+ this._combineFlagAndOptionalValue = true;
1007
+ this._description = "";
1008
+ this._summary = "";
1009
+ this._argsDescription = void 0;
1010
+ this._enablePositionalOptions = false;
1011
+ this._passThroughOptions = false;
1012
+ this._lifeCycleHooks = {};
1013
+ this._showHelpAfterError = false;
1014
+ this._showSuggestionAfterError = true;
1015
+ this._outputConfiguration = {
1016
+ writeOut: (str) => process3.stdout.write(str),
1017
+ writeErr: (str) => process3.stderr.write(str),
1018
+ getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : void 0,
1019
+ getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : void 0,
1020
+ outputError: (str, write) => write(str)
1021
+ };
1022
+ this._hidden = false;
1023
+ this._helpOption = void 0;
1024
+ this._addImplicitHelpCommand = void 0;
1025
+ this._helpCommand = void 0;
1026
+ this._helpConfiguration = {};
1027
+ }
1028
+ /**
1029
+ * Copy settings that are useful to have in common across root command and subcommands.
1030
+ *
1031
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1032
+ *
1033
+ * @param {Command} sourceCommand
1034
+ * @return {Command} `this` command for chaining
1035
+ */
1036
+ copyInheritedSettings(sourceCommand) {
1037
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1038
+ this._helpOption = sourceCommand._helpOption;
1039
+ this._helpCommand = sourceCommand._helpCommand;
1040
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1041
+ this._exitCallback = sourceCommand._exitCallback;
1042
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1043
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1044
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1045
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1046
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1047
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1048
+ return this;
1049
+ }
1050
+ /**
1051
+ * @returns {Command[]}
1052
+ * @private
1053
+ */
1054
+ _getCommandAndAncestors() {
1055
+ const result = [];
1056
+ for (let command = this; command; command = command.parent) {
1057
+ result.push(command);
1058
+ }
1059
+ return result;
1060
+ }
1061
+ /**
1062
+ * Define a command.
1063
+ *
1064
+ * There are two styles of command: pay attention to where to put the description.
1065
+ *
1066
+ * @example
1067
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1068
+ * program
1069
+ * .command('clone <source> [destination]')
1070
+ * .description('clone a repository into a newly created directory')
1071
+ * .action((source, destination) => {
1072
+ * console.log('clone command called');
1073
+ * });
1074
+ *
1075
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1076
+ * program
1077
+ * .command('start <service>', 'start named service')
1078
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1079
+ *
1080
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1081
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1082
+ * @param {object} [execOpts] - configuration options (for executable)
1083
+ * @return {Command} returns new command for action handler, or `this` for executable command
1084
+ */
1085
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1086
+ let desc = actionOptsOrExecDesc;
1087
+ let opts = execOpts;
1088
+ if (typeof desc === "object" && desc !== null) {
1089
+ opts = desc;
1090
+ desc = null;
1091
+ }
1092
+ opts = opts || {};
1093
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1094
+ const cmd = this.createCommand(name);
1095
+ if (desc) {
1096
+ cmd.description(desc);
1097
+ cmd._executableHandler = true;
1098
+ }
1099
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1100
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1101
+ cmd._executableFile = opts.executableFile || null;
1102
+ if (args) cmd.arguments(args);
1103
+ this._registerCommand(cmd);
1104
+ cmd.parent = this;
1105
+ cmd.copyInheritedSettings(this);
1106
+ if (desc) return this;
1107
+ return cmd;
1108
+ }
1109
+ /**
1110
+ * Factory routine to create a new unattached command.
1111
+ *
1112
+ * See .command() for creating an attached subcommand, which uses this routine to
1113
+ * create the command. You can override createCommand to customise subcommands.
1114
+ *
1115
+ * @param {string} [name]
1116
+ * @return {Command} new command
1117
+ */
1118
+ createCommand(name) {
1119
+ return new _Command(name);
1120
+ }
1121
+ /**
1122
+ * You can customise the help with a subclass of Help by overriding createHelp,
1123
+ * or by overriding Help properties using configureHelp().
1124
+ *
1125
+ * @return {Help}
1126
+ */
1127
+ createHelp() {
1128
+ return Object.assign(new Help2(), this.configureHelp());
1129
+ }
1130
+ /**
1131
+ * You can customise the help by overriding Help properties using configureHelp(),
1132
+ * or with a subclass of Help by overriding createHelp().
1133
+ *
1134
+ * @param {object} [configuration] - configuration options
1135
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1136
+ */
1137
+ configureHelp(configuration) {
1138
+ if (configuration === void 0) return this._helpConfiguration;
1139
+ this._helpConfiguration = configuration;
1140
+ return this;
1141
+ }
1142
+ /**
1143
+ * The default output goes to stdout and stderr. You can customise this for special
1144
+ * applications. You can also customise the display of errors by overriding outputError.
1145
+ *
1146
+ * The configuration properties are all functions:
1147
+ *
1148
+ * // functions to change where being written, stdout and stderr
1149
+ * writeOut(str)
1150
+ * writeErr(str)
1151
+ * // matching functions to specify width for wrapping help
1152
+ * getOutHelpWidth()
1153
+ * getErrHelpWidth()
1154
+ * // functions based on what is being written out
1155
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1156
+ *
1157
+ * @param {object} [configuration] - configuration options
1158
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1159
+ */
1160
+ configureOutput(configuration) {
1161
+ if (configuration === void 0) return this._outputConfiguration;
1162
+ Object.assign(this._outputConfiguration, configuration);
1163
+ return this;
1164
+ }
1165
+ /**
1166
+ * Display the help or a custom message after an error occurs.
1167
+ *
1168
+ * @param {(boolean|string)} [displayHelp]
1169
+ * @return {Command} `this` command for chaining
1170
+ */
1171
+ showHelpAfterError(displayHelp = true) {
1172
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1173
+ this._showHelpAfterError = displayHelp;
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1178
+ *
1179
+ * @param {boolean} [displaySuggestion]
1180
+ * @return {Command} `this` command for chaining
1181
+ */
1182
+ showSuggestionAfterError(displaySuggestion = true) {
1183
+ this._showSuggestionAfterError = !!displaySuggestion;
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Add a prepared subcommand.
1188
+ *
1189
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1190
+ *
1191
+ * @param {Command} cmd - new subcommand
1192
+ * @param {object} [opts] - configuration options
1193
+ * @return {Command} `this` command for chaining
1194
+ */
1195
+ addCommand(cmd, opts) {
1196
+ if (!cmd._name) {
1197
+ throw new Error(`Command passed to .addCommand() must have a name
1198
+ - specify the name in Command constructor or using .name()`);
1199
+ }
1200
+ opts = opts || {};
1201
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1202
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1203
+ this._registerCommand(cmd);
1204
+ cmd.parent = this;
1205
+ cmd._checkForBrokenPassThrough();
1206
+ return this;
1207
+ }
1208
+ /**
1209
+ * Factory routine to create a new unattached argument.
1210
+ *
1211
+ * See .argument() for creating an attached argument, which uses this routine to
1212
+ * create the argument. You can override createArgument to return a custom argument.
1213
+ *
1214
+ * @param {string} name
1215
+ * @param {string} [description]
1216
+ * @return {Argument} new argument
1217
+ */
1218
+ createArgument(name, description) {
1219
+ return new Argument2(name, description);
1220
+ }
1221
+ /**
1222
+ * Define argument syntax for command.
1223
+ *
1224
+ * The default is that the argument is required, and you can explicitly
1225
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1226
+ *
1227
+ * @example
1228
+ * program.argument('<input-file>');
1229
+ * program.argument('[output-file]');
1230
+ *
1231
+ * @param {string} name
1232
+ * @param {string} [description]
1233
+ * @param {(Function|*)} [fn] - custom argument processing function
1234
+ * @param {*} [defaultValue]
1235
+ * @return {Command} `this` command for chaining
1236
+ */
1237
+ argument(name, description, fn, defaultValue) {
1238
+ const argument = this.createArgument(name, description);
1239
+ if (typeof fn === "function") {
1240
+ argument.default(defaultValue).argParser(fn);
1241
+ } else {
1242
+ argument.default(fn);
1243
+ }
1244
+ this.addArgument(argument);
1245
+ return this;
1246
+ }
1247
+ /**
1248
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1249
+ *
1250
+ * See also .argument().
1251
+ *
1252
+ * @example
1253
+ * program.arguments('<cmd> [env]');
1254
+ *
1255
+ * @param {string} names
1256
+ * @return {Command} `this` command for chaining
1257
+ */
1258
+ arguments(names) {
1259
+ names.trim().split(/ +/).forEach((detail) => {
1260
+ this.argument(detail);
1261
+ });
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Define argument syntax for command, adding a prepared argument.
1266
+ *
1267
+ * @param {Argument} argument
1268
+ * @return {Command} `this` command for chaining
1269
+ */
1270
+ addArgument(argument) {
1271
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1272
+ if (previousArgument && previousArgument.variadic) {
1273
+ throw new Error(
1274
+ `only the last argument can be variadic '${previousArgument.name()}'`
1275
+ );
1276
+ }
1277
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1278
+ throw new Error(
1279
+ `a default value for a required argument is never used: '${argument.name()}'`
1280
+ );
1281
+ }
1282
+ this.registeredArguments.push(argument);
1283
+ return this;
1284
+ }
1285
+ /**
1286
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1287
+ *
1288
+ * @example
1289
+ * program.helpCommand('help [cmd]');
1290
+ * program.helpCommand('help [cmd]', 'show help');
1291
+ * program.helpCommand(false); // suppress default help command
1292
+ * program.helpCommand(true); // add help command even if no subcommands
1293
+ *
1294
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1295
+ * @param {string} [description] - custom description
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ helpCommand(enableOrNameAndArgs, description) {
1299
+ if (typeof enableOrNameAndArgs === "boolean") {
1300
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1301
+ return this;
1302
+ }
1303
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1304
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1305
+ const helpDescription = description ?? "display help for command";
1306
+ const helpCommand = this.createCommand(helpName);
1307
+ helpCommand.helpOption(false);
1308
+ if (helpArgs) helpCommand.arguments(helpArgs);
1309
+ if (helpDescription) helpCommand.description(helpDescription);
1310
+ this._addImplicitHelpCommand = true;
1311
+ this._helpCommand = helpCommand;
1312
+ return this;
1313
+ }
1314
+ /**
1315
+ * Add prepared custom help command.
1316
+ *
1317
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1318
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1319
+ * @return {Command} `this` command for chaining
1320
+ */
1321
+ addHelpCommand(helpCommand, deprecatedDescription) {
1322
+ if (typeof helpCommand !== "object") {
1323
+ this.helpCommand(helpCommand, deprecatedDescription);
1324
+ return this;
1325
+ }
1326
+ this._addImplicitHelpCommand = true;
1327
+ this._helpCommand = helpCommand;
1328
+ return this;
1329
+ }
1330
+ /**
1331
+ * Lazy create help command.
1332
+ *
1333
+ * @return {(Command|null)}
1334
+ * @package
1335
+ */
1336
+ _getHelpCommand() {
1337
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1338
+ if (hasImplicitHelpCommand) {
1339
+ if (this._helpCommand === void 0) {
1340
+ this.helpCommand(void 0, void 0);
1341
+ }
1342
+ return this._helpCommand;
1343
+ }
1344
+ return null;
1345
+ }
1346
+ /**
1347
+ * Add hook for life cycle event.
1348
+ *
1349
+ * @param {string} event
1350
+ * @param {Function} listener
1351
+ * @return {Command} `this` command for chaining
1352
+ */
1353
+ hook(event, listener) {
1354
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1355
+ if (!allowedValues.includes(event)) {
1356
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1357
+ Expecting one of '${allowedValues.join("', '")}'`);
1358
+ }
1359
+ if (this._lifeCycleHooks[event]) {
1360
+ this._lifeCycleHooks[event].push(listener);
1361
+ } else {
1362
+ this._lifeCycleHooks[event] = [listener];
1363
+ }
1364
+ return this;
1365
+ }
1366
+ /**
1367
+ * Register callback to use as replacement for calling process.exit.
1368
+ *
1369
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1370
+ * @return {Command} `this` command for chaining
1371
+ */
1372
+ exitOverride(fn) {
1373
+ if (fn) {
1374
+ this._exitCallback = fn;
1375
+ } else {
1376
+ this._exitCallback = (err) => {
1377
+ if (err.code !== "commander.executeSubCommandAsync") {
1378
+ throw err;
1379
+ } else {
1380
+ }
1381
+ };
1382
+ }
1383
+ return this;
1384
+ }
1385
+ /**
1386
+ * Call process.exit, and _exitCallback if defined.
1387
+ *
1388
+ * @param {number} exitCode exit code for using with process.exit
1389
+ * @param {string} code an id string representing the error
1390
+ * @param {string} message human-readable description of the error
1391
+ * @return never
1392
+ * @private
1393
+ */
1394
+ _exit(exitCode, code, message) {
1395
+ if (this._exitCallback) {
1396
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1397
+ }
1398
+ process3.exit(exitCode);
1399
+ }
1400
+ /**
1401
+ * Register callback `fn` for the command.
1402
+ *
1403
+ * @example
1404
+ * program
1405
+ * .command('serve')
1406
+ * .description('start service')
1407
+ * .action(function() {
1408
+ * // do work here
1409
+ * });
1410
+ *
1411
+ * @param {Function} fn
1412
+ * @return {Command} `this` command for chaining
1413
+ */
1414
+ action(fn) {
1415
+ const listener = (args) => {
1416
+ const expectedArgsCount = this.registeredArguments.length;
1417
+ const actionArgs = args.slice(0, expectedArgsCount);
1418
+ if (this._storeOptionsAsProperties) {
1419
+ actionArgs[expectedArgsCount] = this;
1420
+ } else {
1421
+ actionArgs[expectedArgsCount] = this.opts();
1422
+ }
1423
+ actionArgs.push(this);
1424
+ return fn.apply(this, actionArgs);
1425
+ };
1426
+ this._actionHandler = listener;
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Factory routine to create a new unattached option.
1431
+ *
1432
+ * See .option() for creating an attached option, which uses this routine to
1433
+ * create the option. You can override createOption to return a custom option.
1434
+ *
1435
+ * @param {string} flags
1436
+ * @param {string} [description]
1437
+ * @return {Option} new option
1438
+ */
1439
+ createOption(flags, description) {
1440
+ return new Option2(flags, description);
1441
+ }
1442
+ /**
1443
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1444
+ *
1445
+ * @param {(Option | Argument)} target
1446
+ * @param {string} value
1447
+ * @param {*} previous
1448
+ * @param {string} invalidArgumentMessage
1449
+ * @private
1450
+ */
1451
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1452
+ try {
1453
+ return target.parseArg(value, previous);
1454
+ } catch (err) {
1455
+ if (err.code === "commander.invalidArgument") {
1456
+ const message = `${invalidArgumentMessage} ${err.message}`;
1457
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1458
+ }
1459
+ throw err;
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Check for option flag conflicts.
1464
+ * Register option if no conflicts found, or throw on conflict.
1465
+ *
1466
+ * @param {Option} option
1467
+ * @private
1468
+ */
1469
+ _registerOption(option) {
1470
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1471
+ if (matchingOption) {
1472
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1473
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1474
+ - already used by option '${matchingOption.flags}'`);
1475
+ }
1476
+ this.options.push(option);
1477
+ }
1478
+ /**
1479
+ * Check for command name and alias conflicts with existing commands.
1480
+ * Register command if no conflicts found, or throw on conflict.
1481
+ *
1482
+ * @param {Command} command
1483
+ * @private
1484
+ */
1485
+ _registerCommand(command) {
1486
+ const knownBy = (cmd) => {
1487
+ return [cmd.name()].concat(cmd.aliases());
1488
+ };
1489
+ const alreadyUsed = knownBy(command).find(
1490
+ (name) => this._findCommand(name)
1491
+ );
1492
+ if (alreadyUsed) {
1493
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1494
+ const newCmd = knownBy(command).join("|");
1495
+ throw new Error(
1496
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1497
+ );
1498
+ }
1499
+ this.commands.push(command);
1500
+ }
1501
+ /**
1502
+ * Add an option.
1503
+ *
1504
+ * @param {Option} option
1505
+ * @return {Command} `this` command for chaining
1506
+ */
1507
+ addOption(option) {
1508
+ this._registerOption(option);
1509
+ const oname = option.name();
1510
+ const name = option.attributeName();
1511
+ if (option.negate) {
1512
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1513
+ if (!this._findOption(positiveLongFlag)) {
1514
+ this.setOptionValueWithSource(
1515
+ name,
1516
+ option.defaultValue === void 0 ? true : option.defaultValue,
1517
+ "default"
1518
+ );
1519
+ }
1520
+ } else if (option.defaultValue !== void 0) {
1521
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1522
+ }
1523
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1524
+ if (val == null && option.presetArg !== void 0) {
1525
+ val = option.presetArg;
1526
+ }
1527
+ const oldValue = this.getOptionValue(name);
1528
+ if (val !== null && option.parseArg) {
1529
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1530
+ } else if (val !== null && option.variadic) {
1531
+ val = option._concatValue(val, oldValue);
1532
+ }
1533
+ if (val == null) {
1534
+ if (option.negate) {
1535
+ val = false;
1536
+ } else if (option.isBoolean() || option.optional) {
1537
+ val = true;
1538
+ } else {
1539
+ val = "";
1540
+ }
1541
+ }
1542
+ this.setOptionValueWithSource(name, val, valueSource);
1543
+ };
1544
+ this.on("option:" + oname, (val) => {
1545
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1546
+ handleOptionValue(val, invalidValueMessage, "cli");
1547
+ });
1548
+ if (option.envVar) {
1549
+ this.on("optionEnv:" + oname, (val) => {
1550
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1551
+ handleOptionValue(val, invalidValueMessage, "env");
1552
+ });
1553
+ }
1554
+ return this;
1555
+ }
1556
+ /**
1557
+ * Internal implementation shared by .option() and .requiredOption()
1558
+ *
1559
+ * @return {Command} `this` command for chaining
1560
+ * @private
1561
+ */
1562
+ _optionEx(config, flags, description, fn, defaultValue) {
1563
+ if (typeof flags === "object" && flags instanceof Option2) {
1564
+ throw new Error(
1565
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1566
+ );
1567
+ }
1568
+ const option = this.createOption(flags, description);
1569
+ option.makeOptionMandatory(!!config.mandatory);
1570
+ if (typeof fn === "function") {
1571
+ option.default(defaultValue).argParser(fn);
1572
+ } else if (fn instanceof RegExp) {
1573
+ const regex = fn;
1574
+ fn = (val, def) => {
1575
+ const m = regex.exec(val);
1576
+ return m ? m[0] : def;
1577
+ };
1578
+ option.default(defaultValue).argParser(fn);
1579
+ } else {
1580
+ option.default(fn);
1581
+ }
1582
+ return this.addOption(option);
1583
+ }
1584
+ /**
1585
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1586
+ *
1587
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1588
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1589
+ *
1590
+ * See the README for more details, and see also addOption() and requiredOption().
1591
+ *
1592
+ * @example
1593
+ * program
1594
+ * .option('-p, --pepper', 'add pepper')
1595
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1596
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1597
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1598
+ *
1599
+ * @param {string} flags
1600
+ * @param {string} [description]
1601
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1602
+ * @param {*} [defaultValue]
1603
+ * @return {Command} `this` command for chaining
1604
+ */
1605
+ option(flags, description, parseArg, defaultValue) {
1606
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1607
+ }
1608
+ /**
1609
+ * Add a required option which must have a value after parsing. This usually means
1610
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1611
+ *
1612
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1613
+ *
1614
+ * @param {string} flags
1615
+ * @param {string} [description]
1616
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1617
+ * @param {*} [defaultValue]
1618
+ * @return {Command} `this` command for chaining
1619
+ */
1620
+ requiredOption(flags, description, parseArg, defaultValue) {
1621
+ return this._optionEx(
1622
+ { mandatory: true },
1623
+ flags,
1624
+ description,
1625
+ parseArg,
1626
+ defaultValue
1627
+ );
1628
+ }
1629
+ /**
1630
+ * Alter parsing of short flags with optional values.
1631
+ *
1632
+ * @example
1633
+ * // for `.option('-f,--flag [value]'):
1634
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1635
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1636
+ *
1637
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1638
+ * @return {Command} `this` command for chaining
1639
+ */
1640
+ combineFlagAndOptionalValue(combine = true) {
1641
+ this._combineFlagAndOptionalValue = !!combine;
1642
+ return this;
1643
+ }
1644
+ /**
1645
+ * Allow unknown options on the command line.
1646
+ *
1647
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1648
+ * @return {Command} `this` command for chaining
1649
+ */
1650
+ allowUnknownOption(allowUnknown = true) {
1651
+ this._allowUnknownOption = !!allowUnknown;
1652
+ return this;
1653
+ }
1654
+ /**
1655
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1656
+ *
1657
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1658
+ * @return {Command} `this` command for chaining
1659
+ */
1660
+ allowExcessArguments(allowExcess = true) {
1661
+ this._allowExcessArguments = !!allowExcess;
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1666
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1667
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1668
+ *
1669
+ * @param {boolean} [positional]
1670
+ * @return {Command} `this` command for chaining
1671
+ */
1672
+ enablePositionalOptions(positional = true) {
1673
+ this._enablePositionalOptions = !!positional;
1674
+ return this;
1675
+ }
1676
+ /**
1677
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1678
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1679
+ * positional options to have been enabled on the program (parent commands).
1680
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1681
+ *
1682
+ * @param {boolean} [passThrough] for unknown options.
1683
+ * @return {Command} `this` command for chaining
1684
+ */
1685
+ passThroughOptions(passThrough = true) {
1686
+ this._passThroughOptions = !!passThrough;
1687
+ this._checkForBrokenPassThrough();
1688
+ return this;
1689
+ }
1690
+ /**
1691
+ * @private
1692
+ */
1693
+ _checkForBrokenPassThrough() {
1694
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1695
+ throw new Error(
1696
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1697
+ );
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Whether to store option values as properties on command object,
1702
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1703
+ *
1704
+ * @param {boolean} [storeAsProperties=true]
1705
+ * @return {Command} `this` command for chaining
1706
+ */
1707
+ storeOptionsAsProperties(storeAsProperties = true) {
1708
+ if (this.options.length) {
1709
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1710
+ }
1711
+ if (Object.keys(this._optionValues).length) {
1712
+ throw new Error(
1713
+ "call .storeOptionsAsProperties() before setting option values"
1714
+ );
1715
+ }
1716
+ this._storeOptionsAsProperties = !!storeAsProperties;
1717
+ return this;
1718
+ }
1719
+ /**
1720
+ * Retrieve option value.
1721
+ *
1722
+ * @param {string} key
1723
+ * @return {object} value
1724
+ */
1725
+ getOptionValue(key2) {
1726
+ if (this._storeOptionsAsProperties) {
1727
+ return this[key2];
1728
+ }
1729
+ return this._optionValues[key2];
1730
+ }
1731
+ /**
1732
+ * Store option value.
1733
+ *
1734
+ * @param {string} key
1735
+ * @param {object} value
1736
+ * @return {Command} `this` command for chaining
1737
+ */
1738
+ setOptionValue(key2, value) {
1739
+ return this.setOptionValueWithSource(key2, value, void 0);
1740
+ }
1741
+ /**
1742
+ * Store option value and where the value came from.
1743
+ *
1744
+ * @param {string} key
1745
+ * @param {object} value
1746
+ * @param {string} source - expected values are default/config/env/cli/implied
1747
+ * @return {Command} `this` command for chaining
1748
+ */
1749
+ setOptionValueWithSource(key2, value, source) {
1750
+ if (this._storeOptionsAsProperties) {
1751
+ this[key2] = value;
1752
+ } else {
1753
+ this._optionValues[key2] = value;
1754
+ }
1755
+ this._optionValueSources[key2] = source;
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Get source of option value.
1760
+ * Expected values are default | config | env | cli | implied
1761
+ *
1762
+ * @param {string} key
1763
+ * @return {string}
1764
+ */
1765
+ getOptionValueSource(key2) {
1766
+ return this._optionValueSources[key2];
1767
+ }
1768
+ /**
1769
+ * Get source of option value. See also .optsWithGlobals().
1770
+ * Expected values are default | config | env | cli | implied
1771
+ *
1772
+ * @param {string} key
1773
+ * @return {string}
1774
+ */
1775
+ getOptionValueSourceWithGlobals(key2) {
1776
+ let source;
1777
+ this._getCommandAndAncestors().forEach((cmd) => {
1778
+ if (cmd.getOptionValueSource(key2) !== void 0) {
1779
+ source = cmd.getOptionValueSource(key2);
1780
+ }
1781
+ });
1782
+ return source;
1783
+ }
1784
+ /**
1785
+ * Get user arguments from implied or explicit arguments.
1786
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1787
+ *
1788
+ * @private
1789
+ */
1790
+ _prepareUserArgs(argv2, parseOptions) {
1791
+ if (argv2 !== void 0 && !Array.isArray(argv2)) {
1792
+ throw new Error("first parameter to parse must be array or undefined");
1793
+ }
1794
+ parseOptions = parseOptions || {};
1795
+ if (argv2 === void 0 && parseOptions.from === void 0) {
1796
+ if (process3.versions?.electron) {
1797
+ parseOptions.from = "electron";
1798
+ }
1799
+ const execArgv = process3.execArgv ?? [];
1800
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1801
+ parseOptions.from = "eval";
1802
+ }
1803
+ }
1804
+ if (argv2 === void 0) {
1805
+ argv2 = process3.argv;
1806
+ }
1807
+ this.rawArgs = argv2.slice();
1808
+ let userArgs;
1809
+ switch (parseOptions.from) {
1810
+ case void 0:
1811
+ case "node":
1812
+ this._scriptPath = argv2[1];
1813
+ userArgs = argv2.slice(2);
1814
+ break;
1815
+ case "electron":
1816
+ if (process3.defaultApp) {
1817
+ this._scriptPath = argv2[1];
1818
+ userArgs = argv2.slice(2);
1819
+ } else {
1820
+ userArgs = argv2.slice(1);
1821
+ }
1822
+ break;
1823
+ case "user":
1824
+ userArgs = argv2.slice(0);
1825
+ break;
1826
+ case "eval":
1827
+ userArgs = argv2.slice(1);
1828
+ break;
1829
+ default:
1830
+ throw new Error(
1831
+ `unexpected parse option { from: '${parseOptions.from}' }`
1832
+ );
1833
+ }
1834
+ if (!this._name && this._scriptPath)
1835
+ this.nameFromFilename(this._scriptPath);
1836
+ this._name = this._name || "program";
1837
+ return userArgs;
1838
+ }
1839
+ /**
1840
+ * Parse `argv`, setting options and invoking commands when defined.
1841
+ *
1842
+ * Use parseAsync instead of parse if any of your action handlers are async.
1843
+ *
1844
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1845
+ *
1846
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1847
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1848
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1849
+ * - `'user'`: just user arguments
1850
+ *
1851
+ * @example
1852
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1853
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1854
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1855
+ *
1856
+ * @param {string[]} [argv] - optional, defaults to process.argv
1857
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1858
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1859
+ * @return {Command} `this` command for chaining
1860
+ */
1861
+ parse(argv2, parseOptions) {
1862
+ const userArgs = this._prepareUserArgs(argv2, parseOptions);
1863
+ this._parseCommand([], userArgs);
1864
+ return this;
1865
+ }
1866
+ /**
1867
+ * Parse `argv`, setting options and invoking commands when defined.
1868
+ *
1869
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1870
+ *
1871
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1872
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1873
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1874
+ * - `'user'`: just user arguments
1875
+ *
1876
+ * @example
1877
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1878
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1879
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1880
+ *
1881
+ * @param {string[]} [argv]
1882
+ * @param {object} [parseOptions]
1883
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1884
+ * @return {Promise}
1885
+ */
1886
+ async parseAsync(argv2, parseOptions) {
1887
+ const userArgs = this._prepareUserArgs(argv2, parseOptions);
1888
+ await this._parseCommand([], userArgs);
1889
+ return this;
1890
+ }
1891
+ /**
1892
+ * Execute a sub-command executable.
1893
+ *
1894
+ * @private
1895
+ */
1896
+ _executeSubCommand(subcommand, args) {
1897
+ args = args.slice();
1898
+ let launchWithNode = false;
1899
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1900
+ function findFile(baseDir, baseName) {
1901
+ const localBin = path.resolve(baseDir, baseName);
1902
+ if (fs.existsSync(localBin)) return localBin;
1903
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1904
+ const foundExt = sourceExt.find(
1905
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1906
+ );
1907
+ if (foundExt) return `${localBin}${foundExt}`;
1908
+ return void 0;
1909
+ }
1910
+ this._checkForMissingMandatoryOptions();
1911
+ this._checkForConflictingOptions();
1912
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1913
+ let executableDir = this._executableDir || "";
1914
+ if (this._scriptPath) {
1915
+ let resolvedScriptPath;
1916
+ try {
1917
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1918
+ } catch (err) {
1919
+ resolvedScriptPath = this._scriptPath;
1920
+ }
1921
+ executableDir = path.resolve(
1922
+ path.dirname(resolvedScriptPath),
1923
+ executableDir
1924
+ );
1925
+ }
1926
+ if (executableDir) {
1927
+ let localFile = findFile(executableDir, executableFile);
1928
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1929
+ const legacyName = path.basename(
1930
+ this._scriptPath,
1931
+ path.extname(this._scriptPath)
1932
+ );
1933
+ if (legacyName !== this._name) {
1934
+ localFile = findFile(
1935
+ executableDir,
1936
+ `${legacyName}-${subcommand._name}`
1937
+ );
1938
+ }
1939
+ }
1940
+ executableFile = localFile || executableFile;
1941
+ }
1942
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1943
+ let proc;
1944
+ if (process3.platform !== "win32") {
1945
+ if (launchWithNode) {
1946
+ args.unshift(executableFile);
1947
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1948
+ proc = childProcess.spawn(process3.argv[0], args, { stdio: "inherit" });
1949
+ } else {
1950
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1951
+ }
1952
+ } else {
1953
+ args.unshift(executableFile);
1954
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1955
+ proc = childProcess.spawn(process3.execPath, args, { stdio: "inherit" });
1956
+ }
1957
+ if (!proc.killed) {
1958
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1959
+ signals.forEach((signal) => {
1960
+ process3.on(signal, () => {
1961
+ if (proc.killed === false && proc.exitCode === null) {
1962
+ proc.kill(signal);
1963
+ }
1964
+ });
1965
+ });
1966
+ }
1967
+ const exitCallback = this._exitCallback;
1968
+ proc.on("close", (code) => {
1969
+ code = code ?? 1;
1970
+ if (!exitCallback) {
1971
+ process3.exit(code);
1972
+ } else {
1973
+ exitCallback(
1974
+ new CommanderError2(
1975
+ code,
1976
+ "commander.executeSubCommandAsync",
1977
+ "(close)"
1978
+ )
1979
+ );
1980
+ }
1981
+ });
1982
+ proc.on("error", (err) => {
1983
+ if (err.code === "ENOENT") {
1984
+ 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";
1985
+ const executableMissing = `'${executableFile}' does not exist
1986
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1987
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1988
+ - ${executableDirMessage}`;
1989
+ throw new Error(executableMissing);
1990
+ } else if (err.code === "EACCES") {
1991
+ throw new Error(`'${executableFile}' not executable`);
1992
+ }
1993
+ if (!exitCallback) {
1994
+ process3.exit(1);
1995
+ } else {
1996
+ const wrappedError = new CommanderError2(
1997
+ 1,
1998
+ "commander.executeSubCommandAsync",
1999
+ "(error)"
2000
+ );
2001
+ wrappedError.nestedError = err;
2002
+ exitCallback(wrappedError);
2003
+ }
2004
+ });
2005
+ this.runningCommand = proc;
2006
+ }
2007
+ /**
2008
+ * @private
2009
+ */
2010
+ _dispatchSubcommand(commandName, operands, unknown) {
2011
+ const subCommand = this._findCommand(commandName);
2012
+ if (!subCommand) this.help({ error: true });
2013
+ let promiseChain;
2014
+ promiseChain = this._chainOrCallSubCommandHook(
2015
+ promiseChain,
2016
+ subCommand,
2017
+ "preSubcommand"
2018
+ );
2019
+ promiseChain = this._chainOrCall(promiseChain, () => {
2020
+ if (subCommand._executableHandler) {
2021
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2022
+ } else {
2023
+ return subCommand._parseCommand(operands, unknown);
2024
+ }
2025
+ });
2026
+ return promiseChain;
2027
+ }
2028
+ /**
2029
+ * Invoke help directly if possible, or dispatch if necessary.
2030
+ * e.g. help foo
2031
+ *
2032
+ * @private
2033
+ */
2034
+ _dispatchHelpCommand(subcommandName) {
2035
+ if (!subcommandName) {
2036
+ this.help();
2037
+ }
2038
+ const subCommand = this._findCommand(subcommandName);
2039
+ if (subCommand && !subCommand._executableHandler) {
2040
+ subCommand.help();
2041
+ }
2042
+ return this._dispatchSubcommand(
2043
+ subcommandName,
2044
+ [],
2045
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2046
+ );
2047
+ }
2048
+ /**
2049
+ * Check this.args against expected this.registeredArguments.
2050
+ *
2051
+ * @private
2052
+ */
2053
+ _checkNumberOfArguments() {
2054
+ this.registeredArguments.forEach((arg, i) => {
2055
+ if (arg.required && this.args[i] == null) {
2056
+ this.missingArgument(arg.name());
2057
+ }
2058
+ });
2059
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2060
+ return;
2061
+ }
2062
+ if (this.args.length > this.registeredArguments.length) {
2063
+ this._excessArguments(this.args);
2064
+ }
2065
+ }
2066
+ /**
2067
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _processArguments() {
2072
+ const myParseArg = (argument, value, previous) => {
2073
+ let parsedValue = value;
2074
+ if (value !== null && argument.parseArg) {
2075
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2076
+ parsedValue = this._callParseArg(
2077
+ argument,
2078
+ value,
2079
+ previous,
2080
+ invalidValueMessage
2081
+ );
2082
+ }
2083
+ return parsedValue;
2084
+ };
2085
+ this._checkNumberOfArguments();
2086
+ const processedArgs = [];
2087
+ this.registeredArguments.forEach((declaredArg, index) => {
2088
+ let value = declaredArg.defaultValue;
2089
+ if (declaredArg.variadic) {
2090
+ if (index < this.args.length) {
2091
+ value = this.args.slice(index);
2092
+ if (declaredArg.parseArg) {
2093
+ value = value.reduce((processed, v) => {
2094
+ return myParseArg(declaredArg, v, processed);
2095
+ }, declaredArg.defaultValue);
2096
+ }
2097
+ } else if (value === void 0) {
2098
+ value = [];
2099
+ }
2100
+ } else if (index < this.args.length) {
2101
+ value = this.args[index];
2102
+ if (declaredArg.parseArg) {
2103
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2104
+ }
2105
+ }
2106
+ processedArgs[index] = value;
2107
+ });
2108
+ this.processedArgs = processedArgs;
2109
+ }
2110
+ /**
2111
+ * Once we have a promise we chain, but call synchronously until then.
2112
+ *
2113
+ * @param {(Promise|undefined)} promise
2114
+ * @param {Function} fn
2115
+ * @return {(Promise|undefined)}
2116
+ * @private
2117
+ */
2118
+ _chainOrCall(promise, fn) {
2119
+ if (promise && promise.then && typeof promise.then === "function") {
2120
+ return promise.then(() => fn());
2121
+ }
2122
+ return fn();
2123
+ }
2124
+ /**
2125
+ *
2126
+ * @param {(Promise|undefined)} promise
2127
+ * @param {string} event
2128
+ * @return {(Promise|undefined)}
2129
+ * @private
2130
+ */
2131
+ _chainOrCallHooks(promise, event) {
2132
+ let result = promise;
2133
+ const hooks = [];
2134
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2135
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2136
+ hooks.push({ hookedCommand, callback });
2137
+ });
2138
+ });
2139
+ if (event === "postAction") {
2140
+ hooks.reverse();
2141
+ }
2142
+ hooks.forEach((hookDetail) => {
2143
+ result = this._chainOrCall(result, () => {
2144
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2145
+ });
2146
+ });
2147
+ return result;
2148
+ }
2149
+ /**
2150
+ *
2151
+ * @param {(Promise|undefined)} promise
2152
+ * @param {Command} subCommand
2153
+ * @param {string} event
2154
+ * @return {(Promise|undefined)}
2155
+ * @private
2156
+ */
2157
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2158
+ let result = promise;
2159
+ if (this._lifeCycleHooks[event] !== void 0) {
2160
+ this._lifeCycleHooks[event].forEach((hook) => {
2161
+ result = this._chainOrCall(result, () => {
2162
+ return hook(this, subCommand);
2163
+ });
2164
+ });
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /**
2169
+ * Process arguments in context of this command.
2170
+ * Returns action result, in case it is a promise.
2171
+ *
2172
+ * @private
2173
+ */
2174
+ _parseCommand(operands, unknown) {
2175
+ const parsed = this.parseOptions(unknown);
2176
+ this._parseOptionsEnv();
2177
+ this._parseOptionsImplied();
2178
+ operands = operands.concat(parsed.operands);
2179
+ unknown = parsed.unknown;
2180
+ this.args = operands.concat(unknown);
2181
+ if (operands && this._findCommand(operands[0])) {
2182
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2183
+ }
2184
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2185
+ return this._dispatchHelpCommand(operands[1]);
2186
+ }
2187
+ if (this._defaultCommandName) {
2188
+ this._outputHelpIfRequested(unknown);
2189
+ return this._dispatchSubcommand(
2190
+ this._defaultCommandName,
2191
+ operands,
2192
+ unknown
2193
+ );
2194
+ }
2195
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2196
+ this.help({ error: true });
2197
+ }
2198
+ this._outputHelpIfRequested(parsed.unknown);
2199
+ this._checkForMissingMandatoryOptions();
2200
+ this._checkForConflictingOptions();
2201
+ const checkForUnknownOptions = () => {
2202
+ if (parsed.unknown.length > 0) {
2203
+ this.unknownOption(parsed.unknown[0]);
2204
+ }
2205
+ };
2206
+ const commandEvent = `command:${this.name()}`;
2207
+ if (this._actionHandler) {
2208
+ checkForUnknownOptions();
2209
+ this._processArguments();
2210
+ let promiseChain;
2211
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2212
+ promiseChain = this._chainOrCall(
2213
+ promiseChain,
2214
+ () => this._actionHandler(this.processedArgs)
2215
+ );
2216
+ if (this.parent) {
2217
+ promiseChain = this._chainOrCall(promiseChain, () => {
2218
+ this.parent.emit(commandEvent, operands, unknown);
2219
+ });
2220
+ }
2221
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2222
+ return promiseChain;
2223
+ }
2224
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2225
+ checkForUnknownOptions();
2226
+ this._processArguments();
2227
+ this.parent.emit(commandEvent, operands, unknown);
2228
+ } else if (operands.length) {
2229
+ if (this._findCommand("*")) {
2230
+ return this._dispatchSubcommand("*", operands, unknown);
2231
+ }
2232
+ if (this.listenerCount("command:*")) {
2233
+ this.emit("command:*", operands, unknown);
2234
+ } else if (this.commands.length) {
2235
+ this.unknownCommand();
2236
+ } else {
2237
+ checkForUnknownOptions();
2238
+ this._processArguments();
2239
+ }
2240
+ } else if (this.commands.length) {
2241
+ checkForUnknownOptions();
2242
+ this.help({ error: true });
2243
+ } else {
2244
+ checkForUnknownOptions();
2245
+ this._processArguments();
2246
+ }
2247
+ }
2248
+ /**
2249
+ * Find matching command.
2250
+ *
2251
+ * @private
2252
+ * @return {Command | undefined}
2253
+ */
2254
+ _findCommand(name) {
2255
+ if (!name) return void 0;
2256
+ return this.commands.find(
2257
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2258
+ );
2259
+ }
2260
+ /**
2261
+ * Return an option matching `arg` if any.
2262
+ *
2263
+ * @param {string} arg
2264
+ * @return {Option}
2265
+ * @package
2266
+ */
2267
+ _findOption(arg) {
2268
+ return this.options.find((option) => option.is(arg));
2269
+ }
2270
+ /**
2271
+ * Display an error message if a mandatory option does not have a value.
2272
+ * Called after checking for help flags in leaf subcommand.
2273
+ *
2274
+ * @private
2275
+ */
2276
+ _checkForMissingMandatoryOptions() {
2277
+ this._getCommandAndAncestors().forEach((cmd) => {
2278
+ cmd.options.forEach((anOption) => {
2279
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2280
+ cmd.missingMandatoryOptionValue(anOption);
2281
+ }
2282
+ });
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Display an error message if conflicting options are used together in this.
2287
+ *
2288
+ * @private
2289
+ */
2290
+ _checkForConflictingLocalOptions() {
2291
+ const definedNonDefaultOptions = this.options.filter((option) => {
2292
+ const optionKey = option.attributeName();
2293
+ if (this.getOptionValue(optionKey) === void 0) {
2294
+ return false;
2295
+ }
2296
+ return this.getOptionValueSource(optionKey) !== "default";
2297
+ });
2298
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2299
+ (option) => option.conflictsWith.length > 0
2300
+ );
2301
+ optionsWithConflicting.forEach((option) => {
2302
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2303
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2304
+ );
2305
+ if (conflictingAndDefined) {
2306
+ this._conflictingOption(option, conflictingAndDefined);
2307
+ }
2308
+ });
2309
+ }
2310
+ /**
2311
+ * Display an error message if conflicting options are used together.
2312
+ * Called after checking for help flags in leaf subcommand.
2313
+ *
2314
+ * @private
2315
+ */
2316
+ _checkForConflictingOptions() {
2317
+ this._getCommandAndAncestors().forEach((cmd) => {
2318
+ cmd._checkForConflictingLocalOptions();
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Parse options from `argv` removing known options,
2323
+ * and return argv split into operands and unknown arguments.
2324
+ *
2325
+ * Examples:
2326
+ *
2327
+ * argv => operands, unknown
2328
+ * --known kkk op => [op], []
2329
+ * op --known kkk => [op], []
2330
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2331
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2332
+ *
2333
+ * @param {string[]} argv
2334
+ * @return {{operands: string[], unknown: string[]}}
2335
+ */
2336
+ parseOptions(argv2) {
2337
+ const operands = [];
2338
+ const unknown = [];
2339
+ let dest = operands;
2340
+ const args = argv2.slice();
2341
+ function maybeOption(arg) {
2342
+ return arg.length > 1 && arg[0] === "-";
2343
+ }
2344
+ let activeVariadicOption = null;
2345
+ while (args.length) {
2346
+ const arg = args.shift();
2347
+ if (arg === "--") {
2348
+ if (dest === unknown) dest.push(arg);
2349
+ dest.push(...args);
2350
+ break;
2351
+ }
2352
+ if (activeVariadicOption && !maybeOption(arg)) {
2353
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2354
+ continue;
2355
+ }
2356
+ activeVariadicOption = null;
2357
+ if (maybeOption(arg)) {
2358
+ const option = this._findOption(arg);
2359
+ if (option) {
2360
+ if (option.required) {
2361
+ const value = args.shift();
2362
+ if (value === void 0) this.optionMissingArgument(option);
2363
+ this.emit(`option:${option.name()}`, value);
2364
+ } else if (option.optional) {
2365
+ let value = null;
2366
+ if (args.length > 0 && !maybeOption(args[0])) {
2367
+ value = args.shift();
2368
+ }
2369
+ this.emit(`option:${option.name()}`, value);
2370
+ } else {
2371
+ this.emit(`option:${option.name()}`);
2372
+ }
2373
+ activeVariadicOption = option.variadic ? option : null;
2374
+ continue;
2375
+ }
2376
+ }
2377
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2378
+ const option = this._findOption(`-${arg[1]}`);
2379
+ if (option) {
2380
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2381
+ this.emit(`option:${option.name()}`, arg.slice(2));
2382
+ } else {
2383
+ this.emit(`option:${option.name()}`);
2384
+ args.unshift(`-${arg.slice(2)}`);
2385
+ }
2386
+ continue;
2387
+ }
2388
+ }
2389
+ if (/^--[^=]+=/.test(arg)) {
2390
+ const index = arg.indexOf("=");
2391
+ const option = this._findOption(arg.slice(0, index));
2392
+ if (option && (option.required || option.optional)) {
2393
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2394
+ continue;
2395
+ }
2396
+ }
2397
+ if (maybeOption(arg)) {
2398
+ dest = unknown;
2399
+ }
2400
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2401
+ if (this._findCommand(arg)) {
2402
+ operands.push(arg);
2403
+ if (args.length > 0) unknown.push(...args);
2404
+ break;
2405
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2406
+ operands.push(arg);
2407
+ if (args.length > 0) operands.push(...args);
2408
+ break;
2409
+ } else if (this._defaultCommandName) {
2410
+ unknown.push(arg);
2411
+ if (args.length > 0) unknown.push(...args);
2412
+ break;
2413
+ }
2414
+ }
2415
+ if (this._passThroughOptions) {
2416
+ dest.push(arg);
2417
+ if (args.length > 0) dest.push(...args);
2418
+ break;
2419
+ }
2420
+ dest.push(arg);
2421
+ }
2422
+ return { operands, unknown };
2423
+ }
2424
+ /**
2425
+ * Return an object containing local option values as key-value pairs.
2426
+ *
2427
+ * @return {object}
2428
+ */
2429
+ opts() {
2430
+ if (this._storeOptionsAsProperties) {
2431
+ const result = {};
2432
+ const len = this.options.length;
2433
+ for (let i = 0; i < len; i++) {
2434
+ const key2 = this.options[i].attributeName();
2435
+ result[key2] = key2 === this._versionOptionName ? this._version : this[key2];
2436
+ }
2437
+ return result;
2438
+ }
2439
+ return this._optionValues;
2440
+ }
2441
+ /**
2442
+ * Return an object containing merged local and global option values as key-value pairs.
2443
+ *
2444
+ * @return {object}
2445
+ */
2446
+ optsWithGlobals() {
2447
+ return this._getCommandAndAncestors().reduce(
2448
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2449
+ {}
2450
+ );
2451
+ }
2452
+ /**
2453
+ * Display error message and exit (or call exitOverride).
2454
+ *
2455
+ * @param {string} message
2456
+ * @param {object} [errorOptions]
2457
+ * @param {string} [errorOptions.code] - an id string representing the error
2458
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2459
+ */
2460
+ error(message, errorOptions) {
2461
+ this._outputConfiguration.outputError(
2462
+ `${message}
2463
+ `,
2464
+ this._outputConfiguration.writeErr
2465
+ );
2466
+ if (typeof this._showHelpAfterError === "string") {
2467
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2468
+ `);
2469
+ } else if (this._showHelpAfterError) {
2470
+ this._outputConfiguration.writeErr("\n");
2471
+ this.outputHelp({ error: true });
2472
+ }
2473
+ const config = errorOptions || {};
2474
+ const exitCode = config.exitCode || 1;
2475
+ const code = config.code || "commander.error";
2476
+ this._exit(exitCode, code, message);
2477
+ }
2478
+ /**
2479
+ * Apply any option related environment variables, if option does
2480
+ * not have a value from cli or client code.
2481
+ *
2482
+ * @private
2483
+ */
2484
+ _parseOptionsEnv() {
2485
+ this.options.forEach((option) => {
2486
+ if (option.envVar && option.envVar in process3.env) {
2487
+ const optionKey = option.attributeName();
2488
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2489
+ this.getOptionValueSource(optionKey)
2490
+ )) {
2491
+ if (option.required || option.optional) {
2492
+ this.emit(`optionEnv:${option.name()}`, process3.env[option.envVar]);
2493
+ } else {
2494
+ this.emit(`optionEnv:${option.name()}`);
2495
+ }
2496
+ }
2497
+ }
2498
+ });
2499
+ }
2500
+ /**
2501
+ * Apply any implied option values, if option is undefined or default value.
2502
+ *
2503
+ * @private
2504
+ */
2505
+ _parseOptionsImplied() {
2506
+ const dualHelper = new DualOptions(this.options);
2507
+ const hasCustomOptionValue = (optionKey) => {
2508
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2509
+ };
2510
+ this.options.filter(
2511
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2512
+ this.getOptionValue(option.attributeName()),
2513
+ option
2514
+ )
2515
+ ).forEach((option) => {
2516
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2517
+ this.setOptionValueWithSource(
2518
+ impliedKey,
2519
+ option.implied[impliedKey],
2520
+ "implied"
2521
+ );
2522
+ });
2523
+ });
2524
+ }
2525
+ /**
2526
+ * Argument `name` is missing.
2527
+ *
2528
+ * @param {string} name
2529
+ * @private
2530
+ */
2531
+ missingArgument(name) {
2532
+ const message = `error: missing required argument '${name}'`;
2533
+ this.error(message, { code: "commander.missingArgument" });
2534
+ }
2535
+ /**
2536
+ * `Option` is missing an argument.
2537
+ *
2538
+ * @param {Option} option
2539
+ * @private
2540
+ */
2541
+ optionMissingArgument(option) {
2542
+ const message = `error: option '${option.flags}' argument missing`;
2543
+ this.error(message, { code: "commander.optionMissingArgument" });
2544
+ }
2545
+ /**
2546
+ * `Option` does not have a value, and is a mandatory option.
2547
+ *
2548
+ * @param {Option} option
2549
+ * @private
2550
+ */
2551
+ missingMandatoryOptionValue(option) {
2552
+ const message = `error: required option '${option.flags}' not specified`;
2553
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2554
+ }
2555
+ /**
2556
+ * `Option` conflicts with another option.
2557
+ *
2558
+ * @param {Option} option
2559
+ * @param {Option} conflictingOption
2560
+ * @private
2561
+ */
2562
+ _conflictingOption(option, conflictingOption) {
2563
+ const findBestOptionFromValue = (option2) => {
2564
+ const optionKey = option2.attributeName();
2565
+ const optionValue = this.getOptionValue(optionKey);
2566
+ const negativeOption = this.options.find(
2567
+ (target) => target.negate && optionKey === target.attributeName()
2568
+ );
2569
+ const positiveOption = this.options.find(
2570
+ (target) => !target.negate && optionKey === target.attributeName()
2571
+ );
2572
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2573
+ return negativeOption;
2574
+ }
2575
+ return positiveOption || option2;
2576
+ };
2577
+ const getErrorMessage = (option2) => {
2578
+ const bestOption = findBestOptionFromValue(option2);
2579
+ const optionKey = bestOption.attributeName();
2580
+ const source = this.getOptionValueSource(optionKey);
2581
+ if (source === "env") {
2582
+ return `environment variable '${bestOption.envVar}'`;
2583
+ }
2584
+ return `option '${bestOption.flags}'`;
2585
+ };
2586
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2587
+ this.error(message, { code: "commander.conflictingOption" });
2588
+ }
2589
+ /**
2590
+ * Unknown option `flag`.
2591
+ *
2592
+ * @param {string} flag
2593
+ * @private
2594
+ */
2595
+ unknownOption(flag) {
2596
+ if (this._allowUnknownOption) return;
2597
+ let suggestion = "";
2598
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2599
+ let candidateFlags = [];
2600
+ let command = this;
2601
+ do {
2602
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2603
+ candidateFlags = candidateFlags.concat(moreFlags);
2604
+ command = command.parent;
2605
+ } while (command && !command._enablePositionalOptions);
2606
+ suggestion = suggestSimilar(flag, candidateFlags);
2607
+ }
2608
+ const message = `error: unknown option '${flag}'${suggestion}`;
2609
+ this.error(message, { code: "commander.unknownOption" });
2610
+ }
2611
+ /**
2612
+ * Excess arguments, more than expected.
2613
+ *
2614
+ * @param {string[]} receivedArgs
2615
+ * @private
2616
+ */
2617
+ _excessArguments(receivedArgs) {
2618
+ if (this._allowExcessArguments) return;
2619
+ const expected = this.registeredArguments.length;
2620
+ const s = expected === 1 ? "" : "s";
2621
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2622
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2623
+ this.error(message, { code: "commander.excessArguments" });
2624
+ }
2625
+ /**
2626
+ * Unknown command.
2627
+ *
2628
+ * @private
2629
+ */
2630
+ unknownCommand() {
2631
+ const unknownName = this.args[0];
2632
+ let suggestion = "";
2633
+ if (this._showSuggestionAfterError) {
2634
+ const candidateNames = [];
2635
+ this.createHelp().visibleCommands(this).forEach((command) => {
2636
+ candidateNames.push(command.name());
2637
+ if (command.alias()) candidateNames.push(command.alias());
2638
+ });
2639
+ suggestion = suggestSimilar(unknownName, candidateNames);
2640
+ }
2641
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2642
+ this.error(message, { code: "commander.unknownCommand" });
2643
+ }
2644
+ /**
2645
+ * Get or set the program version.
2646
+ *
2647
+ * This method auto-registers the "-V, --version" option which will print the version number.
2648
+ *
2649
+ * You can optionally supply the flags and description to override the defaults.
2650
+ *
2651
+ * @param {string} [str]
2652
+ * @param {string} [flags]
2653
+ * @param {string} [description]
2654
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2655
+ */
2656
+ version(str, flags, description) {
2657
+ if (str === void 0) return this._version;
2658
+ this._version = str;
2659
+ flags = flags || "-V, --version";
2660
+ description = description || "output the version number";
2661
+ const versionOption = this.createOption(flags, description);
2662
+ this._versionOptionName = versionOption.attributeName();
2663
+ this._registerOption(versionOption);
2664
+ this.on("option:" + versionOption.name(), () => {
2665
+ this._outputConfiguration.writeOut(`${str}
2666
+ `);
2667
+ this._exit(0, "commander.version", str);
2668
+ });
2669
+ return this;
2670
+ }
2671
+ /**
2672
+ * Set the description.
2673
+ *
2674
+ * @param {string} [str]
2675
+ * @param {object} [argsDescription]
2676
+ * @return {(string|Command)}
2677
+ */
2678
+ description(str, argsDescription) {
2679
+ if (str === void 0 && argsDescription === void 0)
2680
+ return this._description;
2681
+ this._description = str;
2682
+ if (argsDescription) {
2683
+ this._argsDescription = argsDescription;
2684
+ }
2685
+ return this;
2686
+ }
2687
+ /**
2688
+ * Set the summary. Used when listed as subcommand of parent.
2689
+ *
2690
+ * @param {string} [str]
2691
+ * @return {(string|Command)}
2692
+ */
2693
+ summary(str) {
2694
+ if (str === void 0) return this._summary;
2695
+ this._summary = str;
2696
+ return this;
2697
+ }
2698
+ /**
2699
+ * Set an alias for the command.
2700
+ *
2701
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2702
+ *
2703
+ * @param {string} [alias]
2704
+ * @return {(string|Command)}
2705
+ */
2706
+ alias(alias) {
2707
+ if (alias === void 0) return this._aliases[0];
2708
+ let command = this;
2709
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2710
+ command = this.commands[this.commands.length - 1];
2711
+ }
2712
+ if (alias === command._name)
2713
+ throw new Error("Command alias can't be the same as its name");
2714
+ const matchingCommand = this.parent?._findCommand(alias);
2715
+ if (matchingCommand) {
2716
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2717
+ throw new Error(
2718
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2719
+ );
2720
+ }
2721
+ command._aliases.push(alias);
2722
+ return this;
2723
+ }
2724
+ /**
2725
+ * Set aliases for the command.
2726
+ *
2727
+ * Only the first alias is shown in the auto-generated help.
2728
+ *
2729
+ * @param {string[]} [aliases]
2730
+ * @return {(string[]|Command)}
2731
+ */
2732
+ aliases(aliases) {
2733
+ if (aliases === void 0) return this._aliases;
2734
+ aliases.forEach((alias) => this.alias(alias));
2735
+ return this;
2736
+ }
2737
+ /**
2738
+ * Set / get the command usage `str`.
2739
+ *
2740
+ * @param {string} [str]
2741
+ * @return {(string|Command)}
2742
+ */
2743
+ usage(str) {
2744
+ if (str === void 0) {
2745
+ if (this._usage) return this._usage;
2746
+ const args = this.registeredArguments.map((arg) => {
2747
+ return humanReadableArgName(arg);
2748
+ });
2749
+ return [].concat(
2750
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2751
+ this.commands.length ? "[command]" : [],
2752
+ this.registeredArguments.length ? args : []
2753
+ ).join(" ");
2754
+ }
2755
+ this._usage = str;
2756
+ return this;
2757
+ }
2758
+ /**
2759
+ * Get or set the name of the command.
2760
+ *
2761
+ * @param {string} [str]
2762
+ * @return {(string|Command)}
2763
+ */
2764
+ name(str) {
2765
+ if (str === void 0) return this._name;
2766
+ this._name = str;
2767
+ return this;
2768
+ }
2769
+ /**
2770
+ * Set the name of the command from script filename, such as process.argv[1],
2771
+ * or require.main.filename, or __filename.
2772
+ *
2773
+ * (Used internally and public although not documented in README.)
2774
+ *
2775
+ * @example
2776
+ * program.nameFromFilename(require.main.filename);
2777
+ *
2778
+ * @param {string} filename
2779
+ * @return {Command}
2780
+ */
2781
+ nameFromFilename(filename) {
2782
+ this._name = path.basename(filename, path.extname(filename));
2783
+ return this;
2784
+ }
2785
+ /**
2786
+ * Get or set the directory for searching for executable subcommands of this command.
2787
+ *
2788
+ * @example
2789
+ * program.executableDir(__dirname);
2790
+ * // or
2791
+ * program.executableDir('subcommands');
2792
+ *
2793
+ * @param {string} [path]
2794
+ * @return {(string|null|Command)}
2795
+ */
2796
+ executableDir(path2) {
2797
+ if (path2 === void 0) return this._executableDir;
2798
+ this._executableDir = path2;
2799
+ return this;
2800
+ }
2801
+ /**
2802
+ * Return program help documentation.
2803
+ *
2804
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2805
+ * @return {string}
2806
+ */
2807
+ helpInformation(contextOptions) {
2808
+ const helper = this.createHelp();
2809
+ if (helper.helpWidth === void 0) {
2810
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2811
+ }
2812
+ return helper.formatHelp(this, helper);
2813
+ }
2814
+ /**
2815
+ * @private
2816
+ */
2817
+ _getHelpContext(contextOptions) {
2818
+ contextOptions = contextOptions || {};
2819
+ const context = { error: !!contextOptions.error };
2820
+ let write;
2821
+ if (context.error) {
2822
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2823
+ } else {
2824
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2825
+ }
2826
+ context.write = contextOptions.write || write;
2827
+ context.command = this;
2828
+ return context;
2829
+ }
2830
+ /**
2831
+ * Output help information for this command.
2832
+ *
2833
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2834
+ *
2835
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2836
+ */
2837
+ outputHelp(contextOptions) {
2838
+ let deprecatedCallback;
2839
+ if (typeof contextOptions === "function") {
2840
+ deprecatedCallback = contextOptions;
2841
+ contextOptions = void 0;
2842
+ }
2843
+ const context = this._getHelpContext(contextOptions);
2844
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2845
+ this.emit("beforeHelp", context);
2846
+ let helpInformation = this.helpInformation(context);
2847
+ if (deprecatedCallback) {
2848
+ helpInformation = deprecatedCallback(helpInformation);
2849
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2850
+ throw new Error("outputHelp callback must return a string or a Buffer");
2851
+ }
2852
+ }
2853
+ context.write(helpInformation);
2854
+ if (this._getHelpOption()?.long) {
2855
+ this.emit(this._getHelpOption().long);
2856
+ }
2857
+ this.emit("afterHelp", context);
2858
+ this._getCommandAndAncestors().forEach(
2859
+ (command) => command.emit("afterAllHelp", context)
2860
+ );
2861
+ }
2862
+ /**
2863
+ * You can pass in flags and a description to customise the built-in help option.
2864
+ * Pass in false to disable the built-in help option.
2865
+ *
2866
+ * @example
2867
+ * program.helpOption('-?, --help' 'show help'); // customise
2868
+ * program.helpOption(false); // disable
2869
+ *
2870
+ * @param {(string | boolean)} flags
2871
+ * @param {string} [description]
2872
+ * @return {Command} `this` command for chaining
2873
+ */
2874
+ helpOption(flags, description) {
2875
+ if (typeof flags === "boolean") {
2876
+ if (flags) {
2877
+ this._helpOption = this._helpOption ?? void 0;
2878
+ } else {
2879
+ this._helpOption = null;
2880
+ }
2881
+ return this;
2882
+ }
2883
+ flags = flags ?? "-h, --help";
2884
+ description = description ?? "display help for command";
2885
+ this._helpOption = this.createOption(flags, description);
2886
+ return this;
2887
+ }
2888
+ /**
2889
+ * Lazy create help option.
2890
+ * Returns null if has been disabled with .helpOption(false).
2891
+ *
2892
+ * @returns {(Option | null)} the help option
2893
+ * @package
2894
+ */
2895
+ _getHelpOption() {
2896
+ if (this._helpOption === void 0) {
2897
+ this.helpOption(void 0, void 0);
2898
+ }
2899
+ return this._helpOption;
2900
+ }
2901
+ /**
2902
+ * Supply your own option to use for the built-in help option.
2903
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2904
+ *
2905
+ * @param {Option} option
2906
+ * @return {Command} `this` command for chaining
2907
+ */
2908
+ addHelpOption(option) {
2909
+ this._helpOption = option;
2910
+ return this;
2911
+ }
2912
+ /**
2913
+ * Output help information and exit.
2914
+ *
2915
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2916
+ *
2917
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2918
+ */
2919
+ help(contextOptions) {
2920
+ this.outputHelp(contextOptions);
2921
+ let exitCode = process3.exitCode || 0;
2922
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2923
+ exitCode = 1;
2924
+ }
2925
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2926
+ }
2927
+ /**
2928
+ * Add additional text to be displayed with the built-in help.
2929
+ *
2930
+ * Position is 'before' or 'after' to affect just this command,
2931
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2932
+ *
2933
+ * @param {string} position - before or after built-in help
2934
+ * @param {(string | Function)} text - string to add, or a function returning a string
2935
+ * @return {Command} `this` command for chaining
2936
+ */
2937
+ addHelpText(position, text) {
2938
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2939
+ if (!allowedValues.includes(position)) {
2940
+ throw new Error(`Unexpected value for position to addHelpText.
2941
+ Expecting one of '${allowedValues.join("', '")}'`);
2942
+ }
2943
+ const helpEvent = `${position}Help`;
2944
+ this.on(helpEvent, (context) => {
2945
+ let helpStr;
2946
+ if (typeof text === "function") {
2947
+ helpStr = text({ error: context.error, command: context.command });
2948
+ } else {
2949
+ helpStr = text;
2950
+ }
2951
+ if (helpStr) {
2952
+ context.write(`${helpStr}
2953
+ `);
2954
+ }
2955
+ });
2956
+ return this;
2957
+ }
2958
+ /**
2959
+ * Output help information if help flags specified
2960
+ *
2961
+ * @param {Array} args - array of options to search for help flags
2962
+ * @private
2963
+ */
2964
+ _outputHelpIfRequested(args) {
2965
+ const helpOption = this._getHelpOption();
2966
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2967
+ if (helpRequested) {
2968
+ this.outputHelp();
2969
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2970
+ }
2971
+ }
2972
+ };
2973
+ function incrementNodeInspectorPort(args) {
2974
+ return args.map((arg) => {
2975
+ if (!arg.startsWith("--inspect")) {
2976
+ return arg;
2977
+ }
2978
+ let debugOption;
2979
+ let debugHost = "127.0.0.1";
2980
+ let debugPort = "9229";
2981
+ let match;
2982
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2983
+ debugOption = match[1];
2984
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2985
+ debugOption = match[1];
2986
+ if (/^\d+$/.test(match[3])) {
2987
+ debugPort = match[3];
2988
+ } else {
2989
+ debugHost = match[3];
2990
+ }
2991
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2992
+ debugOption = match[1];
2993
+ debugHost = match[3];
2994
+ debugPort = match[4];
2995
+ }
2996
+ if (debugOption && debugPort !== "0") {
2997
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2998
+ }
2999
+ return arg;
3000
+ });
3001
+ }
3002
+ exports.Command = Command2;
3003
+ }
3004
+ });
3005
+
3006
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js
3007
+ var require_commander = __commonJS({
3008
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js"(exports) {
3009
+ var { Argument: Argument2 } = require_argument();
3010
+ var { Command: Command2 } = require_command();
3011
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3012
+ var { Help: Help2 } = require_help();
3013
+ var { Option: Option2 } = require_option();
3014
+ exports.program = new Command2();
3015
+ exports.createCommand = (name) => new Command2(name);
3016
+ exports.createOption = (flags, description) => new Option2(flags, description);
3017
+ exports.createArgument = (name, description) => new Argument2(name, description);
3018
+ exports.Command = Command2;
3019
+ exports.Option = Option2;
3020
+ exports.Argument = Argument2;
3021
+ exports.Help = Help2;
3022
+ exports.CommanderError = CommanderError2;
3023
+ exports.InvalidArgumentError = InvalidArgumentError2;
3024
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3025
+ }
3026
+ });
3027
+
3028
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
3029
+ var import_index = __toESM(require_commander(), 1);
3030
+ var {
3031
+ program,
3032
+ createCommand,
3033
+ createArgument,
3034
+ createOption,
3035
+ CommanderError,
3036
+ InvalidArgumentError,
3037
+ InvalidOptionArgumentError,
3038
+ // deprecated old name
3039
+ Command,
3040
+ Argument,
3041
+ Option,
3042
+ Help
3043
+ } = import_index.default;
3044
+
3045
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
3046
+ var ANSI_BACKGROUND_OFFSET = 10;
3047
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
3048
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
3049
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
3050
+ var styles = {
3051
+ modifier: {
3052
+ reset: [0, 0],
3053
+ // 21 isn't widely supported and 22 does the same thing
3054
+ bold: [1, 22],
3055
+ dim: [2, 22],
3056
+ italic: [3, 23],
3057
+ underline: [4, 24],
3058
+ overline: [53, 55],
3059
+ inverse: [7, 27],
3060
+ hidden: [8, 28],
3061
+ strikethrough: [9, 29]
3062
+ },
3063
+ color: {
3064
+ black: [30, 39],
3065
+ red: [31, 39],
3066
+ green: [32, 39],
3067
+ yellow: [33, 39],
3068
+ blue: [34, 39],
3069
+ magenta: [35, 39],
3070
+ cyan: [36, 39],
3071
+ white: [37, 39],
3072
+ // Bright color
3073
+ blackBright: [90, 39],
3074
+ gray: [90, 39],
3075
+ // Alias of `blackBright`
3076
+ grey: [90, 39],
3077
+ // Alias of `blackBright`
3078
+ redBright: [91, 39],
3079
+ greenBright: [92, 39],
3080
+ yellowBright: [93, 39],
3081
+ blueBright: [94, 39],
3082
+ magentaBright: [95, 39],
3083
+ cyanBright: [96, 39],
3084
+ whiteBright: [97, 39]
3085
+ },
3086
+ bgColor: {
3087
+ bgBlack: [40, 49],
3088
+ bgRed: [41, 49],
3089
+ bgGreen: [42, 49],
3090
+ bgYellow: [43, 49],
3091
+ bgBlue: [44, 49],
3092
+ bgMagenta: [45, 49],
3093
+ bgCyan: [46, 49],
3094
+ bgWhite: [47, 49],
3095
+ // Bright color
3096
+ bgBlackBright: [100, 49],
3097
+ bgGray: [100, 49],
3098
+ // Alias of `bgBlackBright`
3099
+ bgGrey: [100, 49],
3100
+ // Alias of `bgBlackBright`
3101
+ bgRedBright: [101, 49],
3102
+ bgGreenBright: [102, 49],
3103
+ bgYellowBright: [103, 49],
3104
+ bgBlueBright: [104, 49],
3105
+ bgMagentaBright: [105, 49],
3106
+ bgCyanBright: [106, 49],
3107
+ bgWhiteBright: [107, 49]
3108
+ }
3109
+ };
3110
+ var modifierNames = Object.keys(styles.modifier);
3111
+ var foregroundColorNames = Object.keys(styles.color);
3112
+ var backgroundColorNames = Object.keys(styles.bgColor);
3113
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
3114
+ function assembleStyles() {
3115
+ const codes = /* @__PURE__ */ new Map();
3116
+ for (const [groupName, group] of Object.entries(styles)) {
3117
+ for (const [styleName, style] of Object.entries(group)) {
3118
+ styles[styleName] = {
3119
+ open: `\x1B[${style[0]}m`,
3120
+ close: `\x1B[${style[1]}m`
3121
+ };
3122
+ group[styleName] = styles[styleName];
3123
+ codes.set(style[0], style[1]);
3124
+ }
3125
+ Object.defineProperty(styles, groupName, {
3126
+ value: group,
3127
+ enumerable: false
3128
+ });
3129
+ }
3130
+ Object.defineProperty(styles, "codes", {
3131
+ value: codes,
3132
+ enumerable: false
3133
+ });
3134
+ styles.color.close = "\x1B[39m";
3135
+ styles.bgColor.close = "\x1B[49m";
3136
+ styles.color.ansi = wrapAnsi16();
3137
+ styles.color.ansi256 = wrapAnsi256();
3138
+ styles.color.ansi16m = wrapAnsi16m();
3139
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
3140
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
3141
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
3142
+ Object.defineProperties(styles, {
3143
+ rgbToAnsi256: {
3144
+ value(red, green, blue) {
3145
+ if (red === green && green === blue) {
3146
+ if (red < 8) {
3147
+ return 16;
3148
+ }
3149
+ if (red > 248) {
3150
+ return 231;
3151
+ }
3152
+ return Math.round((red - 8) / 247 * 24) + 232;
3153
+ }
3154
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
3155
+ },
3156
+ enumerable: false
3157
+ },
3158
+ hexToRgb: {
3159
+ value(hex) {
3160
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
3161
+ if (!matches) {
3162
+ return [0, 0, 0];
3163
+ }
3164
+ let [colorString] = matches;
3165
+ if (colorString.length === 3) {
3166
+ colorString = [...colorString].map((character) => character + character).join("");
3167
+ }
3168
+ const integer = Number.parseInt(colorString, 16);
3169
+ return [
3170
+ /* eslint-disable no-bitwise */
3171
+ integer >> 16 & 255,
3172
+ integer >> 8 & 255,
3173
+ integer & 255
3174
+ /* eslint-enable no-bitwise */
3175
+ ];
3176
+ },
3177
+ enumerable: false
3178
+ },
3179
+ hexToAnsi256: {
3180
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
3181
+ enumerable: false
3182
+ },
3183
+ ansi256ToAnsi: {
3184
+ value(code) {
3185
+ if (code < 8) {
3186
+ return 30 + code;
3187
+ }
3188
+ if (code < 16) {
3189
+ return 90 + (code - 8);
3190
+ }
3191
+ let red;
3192
+ let green;
3193
+ let blue;
3194
+ if (code >= 232) {
3195
+ red = ((code - 232) * 10 + 8) / 255;
3196
+ green = red;
3197
+ blue = red;
3198
+ } else {
3199
+ code -= 16;
3200
+ const remainder = code % 36;
3201
+ red = Math.floor(code / 36) / 5;
3202
+ green = Math.floor(remainder / 6) / 5;
3203
+ blue = remainder % 6 / 5;
3204
+ }
3205
+ const value = Math.max(red, green, blue) * 2;
3206
+ if (value === 0) {
3207
+ return 30;
3208
+ }
3209
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
3210
+ if (value === 2) {
3211
+ result += 60;
3212
+ }
3213
+ return result;
3214
+ },
3215
+ enumerable: false
3216
+ },
3217
+ rgbToAnsi: {
3218
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
3219
+ enumerable: false
3220
+ },
3221
+ hexToAnsi: {
3222
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
3223
+ enumerable: false
3224
+ }
3225
+ });
3226
+ return styles;
3227
+ }
3228
+ var ansiStyles = assembleStyles();
3229
+ var ansi_styles_default = ansiStyles;
3230
+
3231
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
3232
+ import process2 from "node:process";
3233
+ import os from "node:os";
3234
+ import tty from "node:tty";
3235
+ function hasFlag(flag, argv2 = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
3236
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3237
+ const position = argv2.indexOf(prefix + flag);
3238
+ const terminatorPosition = argv2.indexOf("--");
3239
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3240
+ }
3241
+ var { env } = process2;
3242
+ var flagForceColor;
3243
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
3244
+ flagForceColor = 0;
3245
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
3246
+ flagForceColor = 1;
3247
+ }
3248
+ function envForceColor() {
3249
+ if ("FORCE_COLOR" in env) {
3250
+ if (env.FORCE_COLOR === "true") {
3251
+ return 1;
3252
+ }
3253
+ if (env.FORCE_COLOR === "false") {
3254
+ return 0;
3255
+ }
3256
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
3257
+ }
3258
+ }
3259
+ function translateLevel(level) {
3260
+ if (level === 0) {
3261
+ return false;
3262
+ }
3263
+ return {
3264
+ level,
3265
+ hasBasic: true,
3266
+ has256: level >= 2,
3267
+ has16m: level >= 3
3268
+ };
3269
+ }
3270
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
3271
+ const noFlagForceColor = envForceColor();
3272
+ if (noFlagForceColor !== void 0) {
3273
+ flagForceColor = noFlagForceColor;
3274
+ }
3275
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
3276
+ if (forceColor === 0) {
3277
+ return 0;
3278
+ }
3279
+ if (sniffFlags) {
3280
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
3281
+ return 3;
3282
+ }
3283
+ if (hasFlag("color=256")) {
3284
+ return 2;
3285
+ }
3286
+ }
3287
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
3288
+ return 1;
3289
+ }
3290
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
3291
+ return 0;
3292
+ }
3293
+ const min = forceColor || 0;
3294
+ if (env.TERM === "dumb") {
3295
+ return min;
3296
+ }
3297
+ if (process2.platform === "win32") {
3298
+ const osRelease = os.release().split(".");
3299
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
3300
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
3301
+ }
3302
+ return 1;
3303
+ }
3304
+ if ("CI" in env) {
3305
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key2) => key2 in env)) {
3306
+ return 3;
3307
+ }
3308
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
3309
+ return 1;
3310
+ }
3311
+ return min;
3312
+ }
3313
+ if ("TEAMCITY_VERSION" in env) {
3314
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3315
+ }
3316
+ if (env.COLORTERM === "truecolor") {
3317
+ return 3;
3318
+ }
3319
+ if (env.TERM === "xterm-kitty") {
3320
+ return 3;
3321
+ }
3322
+ if (env.TERM === "xterm-ghostty") {
3323
+ return 3;
3324
+ }
3325
+ if (env.TERM === "wezterm") {
3326
+ return 3;
3327
+ }
3328
+ if ("TERM_PROGRAM" in env) {
3329
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3330
+ switch (env.TERM_PROGRAM) {
3331
+ case "iTerm.app": {
3332
+ return version >= 3 ? 3 : 2;
3333
+ }
3334
+ case "Apple_Terminal": {
3335
+ return 2;
3336
+ }
3337
+ }
3338
+ }
3339
+ if (/-256(color)?$/i.test(env.TERM)) {
3340
+ return 2;
3341
+ }
3342
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
3343
+ return 1;
3344
+ }
3345
+ if ("COLORTERM" in env) {
3346
+ return 1;
3347
+ }
3348
+ return min;
3349
+ }
3350
+ function createSupportsColor(stream, options = {}) {
3351
+ const level = _supportsColor(stream, {
3352
+ streamIsTTY: stream && stream.isTTY,
3353
+ ...options
3354
+ });
3355
+ return translateLevel(level);
3356
+ }
3357
+ var supportsColor = {
3358
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
3359
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
3360
+ };
3361
+ var supports_color_default = supportsColor;
3362
+
3363
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
3364
+ function stringReplaceAll(string, substring, replacer) {
3365
+ let index = string.indexOf(substring);
3366
+ if (index === -1) {
3367
+ return string;
3368
+ }
3369
+ const substringLength = substring.length;
3370
+ let endIndex = 0;
3371
+ let returnValue = "";
3372
+ do {
3373
+ returnValue += string.slice(endIndex, index) + substring + replacer;
3374
+ endIndex = index + substringLength;
3375
+ index = string.indexOf(substring, endIndex);
3376
+ } while (index !== -1);
3377
+ returnValue += string.slice(endIndex);
3378
+ return returnValue;
3379
+ }
3380
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
3381
+ let endIndex = 0;
3382
+ let returnValue = "";
3383
+ do {
3384
+ const gotCR = string[index - 1] === "\r";
3385
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3386
+ endIndex = index + 1;
3387
+ index = string.indexOf("\n", endIndex);
3388
+ } while (index !== -1);
3389
+ returnValue += string.slice(endIndex);
3390
+ return returnValue;
3391
+ }
3392
+
3393
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
3394
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
3395
+ var GENERATOR = Symbol("GENERATOR");
3396
+ var STYLER = Symbol("STYLER");
3397
+ var IS_EMPTY = Symbol("IS_EMPTY");
3398
+ var levelMapping = [
3399
+ "ansi",
3400
+ "ansi",
3401
+ "ansi256",
3402
+ "ansi16m"
3403
+ ];
3404
+ var styles2 = /* @__PURE__ */ Object.create(null);
3405
+ var applyOptions = (object, options = {}) => {
3406
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
3407
+ throw new Error("The `level` option should be an integer from 0 to 3");
3408
+ }
3409
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
3410
+ object.level = options.level === void 0 ? colorLevel : options.level;
3411
+ };
3412
+ var chalkFactory = (options) => {
3413
+ const chalk2 = (...strings) => strings.join(" ");
3414
+ applyOptions(chalk2, options);
3415
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
3416
+ return chalk2;
3417
+ };
3418
+ function createChalk(options) {
3419
+ return chalkFactory(options);
3420
+ }
3421
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
3422
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
3423
+ styles2[styleName] = {
3424
+ get() {
3425
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
3426
+ Object.defineProperty(this, styleName, { value: builder });
3427
+ return builder;
3428
+ }
3429
+ };
3430
+ }
3431
+ styles2.visible = {
3432
+ get() {
3433
+ const builder = createBuilder(this, this[STYLER], true);
3434
+ Object.defineProperty(this, "visible", { value: builder });
3435
+ return builder;
3436
+ }
3437
+ };
3438
+ var getModelAnsi = (model, level, type, ...arguments_) => {
3439
+ if (model === "rgb") {
3440
+ if (level === "ansi16m") {
3441
+ return ansi_styles_default[type].ansi16m(...arguments_);
3442
+ }
3443
+ if (level === "ansi256") {
3444
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
3445
+ }
3446
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
3447
+ }
3448
+ if (model === "hex") {
3449
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
3450
+ }
3451
+ return ansi_styles_default[type][model](...arguments_);
3452
+ };
3453
+ var usedModels = ["rgb", "hex", "ansi256"];
3454
+ for (const model of usedModels) {
3455
+ styles2[model] = {
3456
+ get() {
3457
+ const { level } = this;
3458
+ return function(...arguments_) {
3459
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
3460
+ return createBuilder(this, styler, this[IS_EMPTY]);
3461
+ };
3462
+ }
3463
+ };
3464
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3465
+ styles2[bgModel] = {
3466
+ get() {
3467
+ const { level } = this;
3468
+ return function(...arguments_) {
3469
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
3470
+ return createBuilder(this, styler, this[IS_EMPTY]);
3471
+ };
3472
+ }
3473
+ };
3474
+ }
3475
+ var proto = Object.defineProperties(() => {
3476
+ }, {
3477
+ ...styles2,
3478
+ level: {
3479
+ enumerable: true,
3480
+ get() {
3481
+ return this[GENERATOR].level;
3482
+ },
3483
+ set(level) {
3484
+ this[GENERATOR].level = level;
3485
+ }
3486
+ }
3487
+ });
3488
+ var createStyler = (open, close, parent) => {
3489
+ let openAll;
3490
+ let closeAll;
3491
+ if (parent === void 0) {
3492
+ openAll = open;
3493
+ closeAll = close;
3494
+ } else {
3495
+ openAll = parent.openAll + open;
3496
+ closeAll = close + parent.closeAll;
3497
+ }
3498
+ return {
3499
+ open,
3500
+ close,
3501
+ openAll,
3502
+ closeAll,
3503
+ parent
3504
+ };
3505
+ };
3506
+ var createBuilder = (self, _styler, _isEmpty) => {
3507
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3508
+ Object.setPrototypeOf(builder, proto);
3509
+ builder[GENERATOR] = self;
3510
+ builder[STYLER] = _styler;
3511
+ builder[IS_EMPTY] = _isEmpty;
3512
+ return builder;
3513
+ };
3514
+ var applyStyle = (self, string) => {
3515
+ if (self.level <= 0 || !string) {
3516
+ return self[IS_EMPTY] ? "" : string;
3517
+ }
3518
+ let styler = self[STYLER];
3519
+ if (styler === void 0) {
3520
+ return string;
3521
+ }
3522
+ const { openAll, closeAll } = styler;
3523
+ if (string.includes("\x1B")) {
3524
+ while (styler !== void 0) {
3525
+ string = stringReplaceAll(string, styler.close, styler.open);
3526
+ styler = styler.parent;
3527
+ }
3528
+ }
3529
+ const lfIndex = string.indexOf("\n");
3530
+ if (lfIndex !== -1) {
3531
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3532
+ }
3533
+ return openAll + string + closeAll;
3534
+ };
3535
+ Object.defineProperties(createChalk.prototype, styles2);
3536
+ var chalk = createChalk();
3537
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
3538
+ var source_default = chalk;
3539
+
3540
+ // packages/core/src/config.ts
3541
+ import { homedir } from "node:os";
3542
+ import { join } from "node:path";
3543
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
3544
+ var DIR = join(homedir(), ".oriro");
3545
+ var FILE = join(DIR, "config.json");
3546
+ function readConfig() {
3547
+ if (!existsSync(FILE)) return {};
3548
+ try {
3549
+ return JSON.parse(readFileSync(FILE, "utf8"));
3550
+ } catch {
3551
+ return {};
3552
+ }
3553
+ }
3554
+ function writeConfig(cfg) {
3555
+ mkdirSync(DIR, { recursive: true });
3556
+ writeFileSync(FILE, JSON.stringify(cfg, null, 2), "utf8");
3557
+ try {
3558
+ chmodSync(FILE, 384);
3559
+ } catch {
3560
+ }
3561
+ }
3562
+
3563
+ // packages/core/src/byok.ts
3564
+ import { hostname, userInfo } from "node:os";
3565
+ import { randomBytes, createCipheriv, createDecipheriv, scryptSync } from "node:crypto";
3566
+
3567
+ // packages/core/src/providers.ts
3568
+ var P = (p) => p;
3569
+ var PROVIDERS = {
3570
+ // ── Frontier / first-party ───────────────────────────────────────────────
3571
+ openai: P({
3572
+ id: "openai",
3573
+ label: "OpenAI",
3574
+ baseUrl: "https://api.openai.com/v1",
3575
+ auth: "bearer",
3576
+ envVar: "ORIRO_BYOK_OPENAI",
3577
+ keyHint: "sk-...",
3578
+ models: ["gpt-4.1", "gpt-4.1-mini", "gpt-4o", "gpt-4o-mini", "o3", "o4-mini", "o1"]
3579
+ }),
3580
+ anthropic: P({
3581
+ id: "anthropic",
3582
+ label: "Anthropic Claude",
3583
+ aliases: ["claude"],
3584
+ baseUrl: "https://api.anthropic.com/v1",
3585
+ auth: "x-api-key",
3586
+ envVar: "ORIRO_BYOK_ANTHROPIC",
3587
+ keyHint: "sk-ant-...",
3588
+ models: ["claude-opus-4-1", "claude-sonnet-4-5", "claude-3-7-sonnet", "claude-3-5-haiku"]
3589
+ }),
3590
+ google: P({
3591
+ id: "google",
3592
+ label: "Google Gemini",
3593
+ aliases: ["gemini"],
3594
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
3595
+ auth: "query",
3596
+ envVar: "ORIRO_BYOK_GOOGLE",
3597
+ keyHint: "AIza...",
3598
+ models: ["gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.0-flash", "gemini-1.5-pro"]
3599
+ }),
3600
+ xai: P({
3601
+ id: "xai",
3602
+ label: "xAI Grok",
3603
+ aliases: ["grok"],
3604
+ baseUrl: "https://api.x.ai/v1",
3605
+ auth: "bearer",
3606
+ envVar: "ORIRO_BYOK_XAI",
3607
+ keyHint: "xai-...",
3608
+ models: ["grok-4", "grok-3", "grok-3-mini", "grok-2"]
3609
+ }),
3610
+ mistral: P({
3611
+ id: "mistral",
3612
+ label: "Mistral AI",
3613
+ baseUrl: "https://api.mistral.ai/v1",
3614
+ auth: "bearer",
3615
+ envVar: "ORIRO_BYOK_MISTRAL",
3616
+ models: ["mistral-large-latest", "mistral-small-latest", "codestral-latest", "pixtral-large-latest"]
3617
+ }),
3618
+ deepseek: P({
3619
+ id: "deepseek",
3620
+ label: "DeepSeek",
3621
+ baseUrl: "https://api.deepseek.com/v1",
3622
+ auth: "bearer",
3623
+ envVar: "ORIRO_BYOK_DEEPSEEK",
3624
+ models: ["deepseek-chat", "deepseek-reasoner"]
3625
+ }),
3626
+ cohere: P({
3627
+ id: "cohere",
3628
+ label: "Cohere",
3629
+ baseUrl: "https://api.cohere.com/v2",
3630
+ auth: "bearer",
3631
+ envVar: "ORIRO_BYOK_COHERE",
3632
+ models: ["command-a-03-2025", "command-r-plus", "command-r"]
3633
+ }),
3634
+ ai21: P({
3635
+ id: "ai21",
3636
+ label: "AI21 Labs",
3637
+ baseUrl: "https://api.ai21.com/studio/v1",
3638
+ auth: "bearer",
3639
+ envVar: "ORIRO_BYOK_AI21",
3640
+ models: ["jamba-1.5-large", "jamba-1.5-mini"]
3641
+ }),
3642
+ reka: P({
3643
+ id: "reka",
3644
+ label: "Reka",
3645
+ baseUrl: "https://api.reka.ai/v1",
3646
+ auth: "bearer",
3647
+ envVar: "ORIRO_BYOK_REKA",
3648
+ models: ["reka-core", "reka-flash", "reka-edge"]
3649
+ }),
3650
+ // ── Fast-inference / open-weight hosts (OpenAI-compatible) ───────────────
3651
+ groq: P({
3652
+ id: "groq",
3653
+ label: "Groq",
3654
+ baseUrl: "https://api.groq.com/openai/v1",
3655
+ auth: "bearer",
3656
+ envVar: "ORIRO_BYOK_GROQ",
3657
+ keyHint: "gsk_...",
3658
+ models: ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768", "qwen-2.5-32b"]
3659
+ }),
3660
+ cerebras: P({
3661
+ id: "cerebras",
3662
+ label: "Cerebras",
3663
+ baseUrl: "https://api.cerebras.ai/v1",
3664
+ auth: "bearer",
3665
+ envVar: "ORIRO_BYOK_CEREBRAS",
3666
+ models: ["llama-3.3-70b", "llama-3.1-8b", "qwen-3-32b"]
3667
+ }),
3668
+ together: P({
3669
+ id: "together",
3670
+ label: "Together AI",
3671
+ baseUrl: "https://api.together.xyz/v1",
3672
+ auth: "bearer",
3673
+ envVar: "ORIRO_BYOK_TOGETHER",
3674
+ models: ["meta-llama/Llama-3.3-70B-Instruct-Turbo", "deepseek-ai/DeepSeek-V3", "Qwen/Qwen2.5-72B-Instruct-Turbo"]
3675
+ }),
3676
+ fireworks: P({
3677
+ id: "fireworks",
3678
+ label: "Fireworks AI",
3679
+ baseUrl: "https://api.fireworks.ai/inference/v1",
3680
+ auth: "bearer",
3681
+ envVar: "ORIRO_BYOK_FIREWORKS",
3682
+ models: ["accounts/fireworks/models/llama-v3p3-70b-instruct", "accounts/fireworks/models/deepseek-v3"]
3683
+ }),
3684
+ deepinfra: P({
3685
+ id: "deepinfra",
3686
+ label: "DeepInfra",
3687
+ baseUrl: "https://api.deepinfra.com/v1/openai",
3688
+ auth: "bearer",
3689
+ envVar: "ORIRO_BYOK_DEEPINFRA",
3690
+ models: ["meta-llama/Llama-3.3-70B-Instruct", "deepseek-ai/DeepSeek-V3"]
3691
+ }),
3692
+ sambanova: P({
3693
+ id: "sambanova",
3694
+ label: "SambaNova",
3695
+ baseUrl: "https://api.sambanova.ai/v1",
3696
+ auth: "bearer",
3697
+ envVar: "ORIRO_BYOK_SAMBANOVA",
3698
+ models: ["Meta-Llama-3.3-70B-Instruct", "Llama-3.1-405B-Instruct"]
3699
+ }),
3700
+ hyperbolic: P({
3701
+ id: "hyperbolic",
3702
+ label: "Hyperbolic",
3703
+ baseUrl: "https://api.hyperbolic.xyz/v1",
3704
+ auth: "bearer",
3705
+ envVar: "ORIRO_BYOK_HYPERBOLIC",
3706
+ models: ["meta-llama/Llama-3.3-70B-Instruct", "deepseek-ai/DeepSeek-V3"]
3707
+ }),
3708
+ novita: P({
3709
+ id: "novita",
3710
+ label: "Novita AI",
3711
+ baseUrl: "https://api.novita.ai/v3/openai",
3712
+ auth: "bearer",
3713
+ envVar: "ORIRO_BYOK_NOVITA",
3714
+ models: ["meta-llama/llama-3.3-70b-instruct", "deepseek/deepseek-v3"]
3715
+ }),
3716
+ nebius: P({
3717
+ id: "nebius",
3718
+ label: "Nebius AI Studio",
3719
+ baseUrl: "https://api.studio.nebius.ai/v1",
3720
+ auth: "bearer",
3721
+ envVar: "ORIRO_BYOK_NEBIUS",
3722
+ models: ["meta-llama/Llama-3.3-70B-Instruct", "Qwen/Qwen2.5-72B-Instruct"]
3723
+ }),
3724
+ perplexity: P({
3725
+ id: "perplexity",
3726
+ label: "Perplexity",
3727
+ baseUrl: "https://api.perplexity.ai",
3728
+ auth: "bearer",
3729
+ envVar: "ORIRO_BYOK_PERPLEXITY",
3730
+ keyHint: "pplx-...",
3731
+ models: ["sonar", "sonar-pro", "sonar-reasoning", "sonar-reasoning-pro"]
3732
+ }),
3733
+ moonshot: P({
3734
+ id: "moonshot",
3735
+ label: "Moonshot (Kimi)",
3736
+ baseUrl: "https://api.moonshot.ai/v1",
3737
+ auth: "bearer",
3738
+ envVar: "ORIRO_BYOK_MOONSHOT",
3739
+ models: ["kimi-k2", "moonshot-v1-128k"]
3740
+ }),
3741
+ zhipu: P({
3742
+ id: "zhipu",
3743
+ label: "Zhipu GLM",
3744
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
3745
+ auth: "bearer",
3746
+ envVar: "ORIRO_BYOK_ZHIPU",
3747
+ models: ["glm-4.6", "glm-4-plus", "glm-4-flash"]
3748
+ }),
3749
+ qwen: P({
3750
+ id: "qwen",
3751
+ label: "Alibaba Qwen (DashScope)",
3752
+ baseUrl: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
3753
+ auth: "bearer",
3754
+ envVar: "ORIRO_BYOK_QWEN",
3755
+ models: ["qwen-max", "qwen-plus", "qwen2.5-72b-instruct", "qwq-32b"]
3756
+ }),
3757
+ // ── Enterprise clouds ────────────────────────────────────────────────────
3758
+ azure: P({
3759
+ id: "azure",
3760
+ label: "Azure OpenAI",
3761
+ aliases: ["azure-openai"],
3762
+ baseUrl: "https://<resource>.openai.azure.com/openai",
3763
+ auth: "header",
3764
+ authHeader: "api-key",
3765
+ envVar: "ORIRO_BYOK_AZURE",
3766
+ models: ["gpt-4o", "gpt-4.1", "o3"]
3767
+ }),
3768
+ bedrock: P({
3769
+ id: "bedrock",
3770
+ label: "AWS Bedrock",
3771
+ baseUrl: "https://bedrock-runtime.<region>.amazonaws.com",
3772
+ auth: "header",
3773
+ envVar: "ORIRO_BYOK_BEDROCK",
3774
+ models: ["anthropic.claude-sonnet-4-5", "meta.llama3-3-70b-instruct", "amazon.nova-pro-v1"]
3775
+ }),
3776
+ vertex: P({
3777
+ id: "vertex",
3778
+ label: "Google Vertex AI",
3779
+ baseUrl: "https://<region>-aiplatform.googleapis.com/v1",
3780
+ auth: "bearer",
3781
+ envVar: "ORIRO_BYOK_VERTEX",
3782
+ models: ["gemini-2.5-pro", "gemini-2.5-flash", "claude-sonnet-4-5@vertex"]
3783
+ }),
3784
+ nvidia: P({
3785
+ id: "nvidia",
3786
+ label: "NVIDIA NIM",
3787
+ baseUrl: "https://integrate.api.nvidia.com/v1",
3788
+ auth: "bearer",
3789
+ envVar: "ORIRO_BYOK_NVIDIA",
3790
+ models: ["meta/llama-3.3-70b-instruct", "deepseek-ai/deepseek-r1", "nvidia/llama-3.1-nemotron-70b-instruct"]
3791
+ }),
3792
+ watsonx: P({
3793
+ id: "watsonx",
3794
+ label: "IBM watsonx",
3795
+ baseUrl: "https://<region>.ml.cloud.ibm.com/ml/v1",
3796
+ auth: "bearer",
3797
+ envVar: "ORIRO_BYOK_WATSONX",
3798
+ models: ["ibm/granite-3-8b-instruct", "meta-llama/llama-3-3-70b-instruct"]
3799
+ }),
3800
+ // ── Aggregators / universal routers (reach hundreds of models) ───────────
3801
+ openrouter: P({
3802
+ id: "openrouter",
3803
+ label: "OpenRouter (universal \u2014 300+ models)",
3804
+ router: true,
3805
+ baseUrl: "https://openrouter.ai/api/v1",
3806
+ auth: "bearer",
3807
+ envVar: "ORIRO_BYOK_OPENROUTER",
3808
+ keyHint: "sk-or-...",
3809
+ models: ["openai/gpt-4.1", "anthropic/claude-sonnet-4.5", "google/gemini-2.5-pro", "deepseek/deepseek-chat", "meta-llama/llama-3.3-70b-instruct", "<any vendor>/<any model>"]
3810
+ }),
3811
+ requesty: P({ id: "requesty", label: "Requesty Router", router: true, baseUrl: "https://router.requesty.ai/v1", auth: "bearer", envVar: "ORIRO_BYOK_REQUESTY", models: ["<vendor>/<model>"] }),
3812
+ glama: P({ id: "glama", label: "Glama Gateway", router: true, baseUrl: "https://glama.ai/api/gateway/openai/v1", auth: "bearer", envVar: "ORIRO_BYOK_GLAMA", models: ["<vendor>/<model>"] }),
3813
+ unify: P({ id: "unify", label: "Unify", router: true, baseUrl: "https://api.unify.ai/v0", auth: "bearer", envVar: "ORIRO_BYOK_UNIFY", models: ["<model>@<provider>"] }),
3814
+ portkey: P({ id: "portkey", label: "Portkey Gateway", router: true, baseUrl: "https://api.portkey.ai/v1", auth: "header", authHeader: "x-portkey-api-key", envVar: "ORIRO_BYOK_PORTKEY", models: ["<vendor>/<model>"] }),
3815
+ litellm: P({ id: "litellm", label: "LiteLLM Proxy (self-host)", router: true, baseUrl: "http://localhost:4000", auth: "bearer", envVar: "ORIRO_BYOK_LITELLM", models: ["<vendor>/<model>"] }),
3816
+ // ── Local runtimes (no key — point at the machine's own server) ──────────
3817
+ ollama: P({
3818
+ id: "ollama",
3819
+ label: "Ollama (local)",
3820
+ local: true,
3821
+ baseUrl: "http://localhost:11434/v1",
3822
+ auth: "none",
3823
+ envVar: "ORIRO_BYOK_OLLAMA",
3824
+ models: ["llama3.3", "qwen2.5", "deepseek-r1", "phi4", "mistral", "gemma3"]
3825
+ }),
3826
+ lmstudio: P({ id: "lmstudio", label: "LM Studio (local)", local: true, baseUrl: "http://localhost:1234/v1", auth: "none", envVar: "ORIRO_BYOK_LMSTUDIO", models: ["<loaded-model>"] }),
3827
+ llamacpp: P({ id: "llamacpp", label: "llama.cpp server (local)", local: true, baseUrl: "http://localhost:8080/v1", auth: "none", envVar: "ORIRO_BYOK_LLAMACPP", models: ["<gguf-model>"] }),
3828
+ vllm: P({ id: "vllm", label: "vLLM (local/self-host)", local: true, baseUrl: "http://localhost:8000/v1", auth: "none", envVar: "ORIRO_BYOK_VLLM", models: ["<served-model>"] }),
3829
+ jan: P({ id: "jan", label: "Jan (local)", local: true, baseUrl: "http://localhost:1337/v1", auth: "none", envVar: "ORIRO_BYOK_JAN", models: ["<loaded-model>"] })
3830
+ };
3831
+ function getProvider(idOrAlias) {
3832
+ const k = idOrAlias.toLowerCase();
3833
+ if (PROVIDERS[k]) return PROVIDERS[k];
3834
+ return Object.values(PROVIDERS).find((p) => p.aliases?.includes(k));
3835
+ }
3836
+ function listProviders() {
3837
+ return Object.values(PROVIDERS);
3838
+ }
3839
+
3840
+ // packages/core/src/byok.ts
3841
+ var SALT = "oriro-cli-v1";
3842
+ function key() {
3843
+ return scryptSync(`${hostname()}:${userInfo().username}:${SALT}`, SALT, 32);
3844
+ }
3845
+ function encrypt(plain) {
3846
+ const iv = randomBytes(12);
3847
+ const c = createCipheriv("aes-256-gcm", key(), iv);
3848
+ const enc = Buffer.concat([c.update(plain, "utf8"), c.final()]);
3849
+ return `${iv.toString("base64")}:${c.getAuthTag().toString("base64")}:${enc.toString("base64")}`;
3850
+ }
3851
+ function decrypt(blob) {
3852
+ try {
3853
+ const [iv, tag, enc] = blob.split(":").map((b) => Buffer.from(b, "base64"));
3854
+ const d = createDecipheriv("aes-256-gcm", key(), iv);
3855
+ d.setAuthTag(tag);
3856
+ return Buffer.concat([d.update(enc), d.final()]).toString("utf8");
3857
+ } catch {
3858
+ return null;
3859
+ }
3860
+ }
3861
+ function setByok(provider, plainKey, modelId) {
3862
+ const id = getProvider(provider)?.id ?? provider.toLowerCase();
3863
+ const cfg = readConfig();
3864
+ cfg.byok = { ...cfg.byok ?? {}, [id]: encrypt(plainKey) };
3865
+ cfg.preferred_provider = id;
3866
+ if (modelId) cfg.preferred_model_id = modelId;
3867
+ writeConfig(cfg);
3868
+ }
3869
+ function getByok(provider) {
3870
+ const info = getProvider(provider);
3871
+ const id = info?.id ?? provider.toLowerCase();
3872
+ const env2 = process.env[info?.envVar ?? `ORIRO_BYOK_${id.toUpperCase()}`];
3873
+ if (env2) return env2;
3874
+ const blob = readConfig().byok?.[id];
3875
+ return blob ? decrypt(blob) : null;
3876
+ }
3877
+ function anyByokActive() {
3878
+ const cfg = readConfig();
3879
+ if (cfg.byok && Object.values(cfg.byok).some(Boolean)) return true;
3880
+ return listProviders().some((p) => !!process.env[p.envVar]);
3881
+ }
3882
+ function clearByok(provider) {
3883
+ const cfg = readConfig();
3884
+ if (provider) {
3885
+ const id = getProvider(provider)?.id ?? provider.toLowerCase();
3886
+ if (cfg.byok) delete cfg.byok[id];
3887
+ if (cfg.preferred_provider === id) {
3888
+ delete cfg.preferred_provider;
3889
+ delete cfg.preferred_model_id;
3890
+ }
3891
+ } else {
3892
+ delete cfg.byok;
3893
+ delete cfg.preferred_provider;
3894
+ delete cfg.preferred_model_id;
3895
+ }
3896
+ writeConfig(cfg);
3897
+ }
3898
+ function linkedProviders() {
3899
+ const cfg = readConfig();
3900
+ const fromCfg = cfg.byok ? Object.keys(cfg.byok).filter((k) => !!cfg.byok[k]) : [];
3901
+ const fromEnv = listProviders().filter((p) => !!process.env[p.envVar]).map((p) => p.id);
3902
+ return Array.from(/* @__PURE__ */ new Set([...fromCfg, ...fromEnv]));
3903
+ }
3904
+ function useByok(provider, modelId) {
3905
+ const id = getProvider(provider)?.id ?? provider.toLowerCase();
3906
+ if (!linkedProviders().includes(id)) return false;
3907
+ const cfg = readConfig();
3908
+ cfg.preferred_provider = id;
3909
+ if (modelId) cfg.preferred_model_id = modelId;
3910
+ writeConfig(cfg);
3911
+ return true;
3912
+ }
3913
+ function activeProvider() {
3914
+ const cfg = readConfig();
3915
+ return { provider: cfg.preferred_provider ?? null, model: cfg.preferred_model_id ?? null };
3916
+ }
3917
+
3918
+ // packages/core/src/guardian.ts
3919
+ var PATTERNS = [
3920
+ // Credit card: 13-16 digits in 4-groups (formatted) — precise to avoid nuking
3921
+ // ordinary long numbers in code.
3922
+ /\b(?:\d{4}[ -]?){3}\d{1,4}\b/g,
3923
+ // US SSN
3924
+ /\b\d{3}-\d{2}-\d{4}\b/g,
3925
+ // password / secret / token / api-key assignments (key: value | key=value)
3926
+ /\b(?:pass(?:word)?|secret|token|api[_-]?key)\s*[:=]\s*\S+/gi,
3927
+ // Common key formats
3928
+ /\bsk-ant-[A-Za-z0-9_-]{16,}\b/g,
3929
+ /\bsk-[A-Za-z0-9]{20,}\b/g,
3930
+ /\bAIza[A-Za-z0-9_-]{20,}\b/g,
3931
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
3932
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g
3933
+ ];
3934
+ function stripPII(text) {
3935
+ let redacted = false;
3936
+ let out = text;
3937
+ for (const re of PATTERNS) {
3938
+ out = out.replace(re, () => {
3939
+ redacted = true;
3940
+ return "[REDACTED]";
3941
+ });
3942
+ }
3943
+ return { text: out, redacted };
3944
+ }
3945
+ function guardMessages(messages) {
3946
+ let any = false;
3947
+ for (const m of messages) {
3948
+ const g = stripPII(m.content);
3949
+ if (g.redacted) {
3950
+ m.content = g.text;
3951
+ any = true;
3952
+ }
3953
+ }
3954
+ return any;
3955
+ }
3956
+ var INJECTION_PATTERNS = [
3957
+ /ignore (all |previous |prior )?instructions/i,
3958
+ /you are now (a |an )?different/i,
3959
+ /print (your )?system prompt/i,
3960
+ /forget (everything|all) (you|above)/i,
3961
+ /\[INST\]|<<SYS>>/
3962
+ ];
3963
+ var HIDDEN_RANGES = [
3964
+ [8203, 8207],
3965
+ // zero-width space … RTL/LTR marks
3966
+ [8234, 8238],
3967
+ // bidi embedding/override
3968
+ [8288, 8292],
3969
+ // word-joiner … invisible separators
3970
+ [65279, 65279]
3971
+ // BOM / zero-width no-break space
3972
+ ];
3973
+ function hasHiddenUnicode(s) {
3974
+ for (const ch of s) {
3975
+ const c = ch.codePointAt(0) ?? 0;
3976
+ for (const [lo, hi] of HIDDEN_RANGES) if (c >= lo && c <= hi) return true;
3977
+ }
3978
+ return false;
3979
+ }
3980
+ function stripHiddenUnicode(s) {
3981
+ let stripped = false;
3982
+ let out = "";
3983
+ for (const ch of s) {
3984
+ const c = ch.codePointAt(0) ?? 0;
3985
+ if (HIDDEN_RANGES.some(([lo, hi]) => c >= lo && c <= hi)) {
3986
+ stripped = true;
3987
+ continue;
3988
+ }
3989
+ out += ch;
3990
+ }
3991
+ return { text: out, stripped };
3992
+ }
3993
+ function firstInjection(text) {
3994
+ for (const re of INJECTION_PATTERNS) {
3995
+ const m = re.exec(text);
3996
+ if (m) return m[0].slice(0, 80);
3997
+ }
3998
+ return null;
3999
+ }
4000
+ function scanFileInput(textContent) {
4001
+ const slice = (textContent || "").slice(0, 10240);
4002
+ const hit = firstInjection(slice);
4003
+ if (hit) return { safe: false, threat: `injection:${hit}` };
4004
+ if (hasHiddenUnicode(slice)) return { safe: false, threat: "hidden_unicode" };
4005
+ return { safe: true };
4006
+ }
4007
+ function scoreInteractionPair(prompt, response) {
4008
+ const flags = [];
4009
+ const resp = response || "";
4010
+ if (/BUILD MODE —|CONVERSATION DISCIPLINE:|=== RELEVANT SKILLS ===|=== Active skills/.test(resp)) flags.push("system_prompt_leak");
4011
+ if (firstInjection(resp)) flags.push("injection_echo");
4012
+ if (prompt && prompt.trim().length > 0 && resp.trim().length === 0) flags.push("empty_response");
4013
+ const score = flags.length === 0 ? 1 : Math.max(0, 1 - flags.length * 0.5);
4014
+ return { safe: flags.length === 0, score, flags };
4015
+ }
4016
+
4017
+ // packages/core/src/runtime.ts
4018
+ var CONTEXT_BY_TIER = {
4019
+ "8gb": 32768,
4020
+ // 32K — hard ceiling; 64K crashes 8GB per research
4021
+ "16gb": 65536,
4022
+ // 64K
4023
+ "32gb": 131072
4024
+ // 128K — full SSA capacity
4025
+ };
4026
+ var DEFAULT_CONTEXT_WINDOW = CONTEXT_BY_TIER["8gb"];
4027
+ function estimateTokens(text) {
4028
+ return Math.ceil(text.length / 4);
4029
+ }
4030
+
4031
+ // packages/core/src/client.ts
4032
+ var API_BASE = (process.env.ORIRO_API_BASE || "https://oriro.ai").replace(/\/$/, "");
4033
+ function byokHeaders(override, apiKey) {
4034
+ const h = {};
4035
+ for (const id of linkedProviders()) {
4036
+ const k = getByok(id);
4037
+ if (k) h[`x-oriro-byok-${id}`] = k;
4038
+ }
4039
+ if (override) {
4040
+ for (const [id, k] of Object.entries(override)) if (k) h[`x-oriro-byok-${id}`] = k;
4041
+ }
4042
+ const act = activeProvider();
4043
+ if (act.provider) {
4044
+ h["x-oriro-provider"] = act.provider;
4045
+ if (act.model) h["x-oriro-model"] = act.model;
4046
+ }
4047
+ const key2 = apiKey ?? process.env.ORIRO_API_KEY;
4048
+ if (key2) h["authorization"] = `Bearer ${key2}`;
4049
+ return h;
4050
+ }
4051
+ async function chatStream(messages, opts = {}) {
4052
+ guardMessages(messages);
4053
+ const body = {
4054
+ model: opts.model && opts.model !== "auto" ? opts.model : void 0,
4055
+ messages,
4056
+ stream: true,
4057
+ oriro: {
4058
+ skill_ids: opts.skillIds ?? [],
4059
+ agent_ids: opts.agentIds ?? [],
4060
+ // Active tier so the worker/runtime reports context-fill against it.
4061
+ context_window: opts.contextWindow ?? DEFAULT_CONTEXT_WINDOW
4062
+ }
4063
+ };
4064
+ const res = await fetch(`${API_BASE}/v1/chat/completions`, {
4065
+ method: "POST",
4066
+ headers: { "content-type": "application/json", ...byokHeaders(opts.byok, opts.apiKey) },
4067
+ body: JSON.stringify(body)
4068
+ });
4069
+ if (!res.ok || !res.body) {
4070
+ const detail = await res.text().catch(() => "");
4071
+ throw new Error(`ORIRO API ${res.status}: ${detail.slice(0, 200)}`);
4072
+ }
4073
+ const meta = {
4074
+ byok_active: anyByokActive() || Object.values(opts.byok ?? {}).some(Boolean),
4075
+ model: opts.model ?? null,
4076
+ skill_ids_used: [],
4077
+ context_fill: null
4078
+ };
4079
+ const ctype = (res.headers.get("content-type") || "").toLowerCase();
4080
+ if (!ctype.includes("text/event-stream")) {
4081
+ const raw = await res.text().catch(() => "");
4082
+ let j;
4083
+ try {
4084
+ j = JSON.parse(raw);
4085
+ } catch {
4086
+ throw new Error(
4087
+ `ORIRO API returned a non-SSE response (content-type: ${ctype || "unknown"}): ${raw.slice(0, 200)}`
4088
+ );
4089
+ }
4090
+ const text = j?.choices?.[0]?.message?.content ?? j?.choices?.[0]?.delta?.content ?? "";
4091
+ if (j?.oriro) {
4092
+ if (typeof j.oriro.byok_active === "boolean") meta.byok_active = j.oriro.byok_active;
4093
+ if (Array.isArray(j.oriro.skill_ids_used)) meta.skill_ids_used = j.oriro.skill_ids_used;
4094
+ if (j.oriro.model) meta.model = j.oriro.model;
4095
+ if (j.oriro.context_fill) meta.context_fill = j.oriro.context_fill;
4096
+ }
4097
+ if (j?.context_fill) meta.context_fill = j.context_fill;
4098
+ if (!text) {
4099
+ throw new Error(
4100
+ `ORIRO API returned JSON without a completion (content-type: ${ctype || "unknown"}): ${raw.slice(0, 200)}`
4101
+ );
4102
+ }
4103
+ opts.onChunk?.(text);
4104
+ return { text, meta };
4105
+ }
4106
+ let full = "";
4107
+ const dec = new TextDecoder();
4108
+ let buf = "";
4109
+ const reader = res.body.getReader();
4110
+ for (; ; ) {
4111
+ const { value, done } = await reader.read();
4112
+ if (done) break;
4113
+ buf += dec.decode(value, { stream: true });
4114
+ const events = buf.split(/\r?\n\r?\n/);
4115
+ buf = events.pop() ?? "";
4116
+ for (const evt of events) {
4117
+ const data = evt.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("\n");
4118
+ if (!data || data === "[DONE]") continue;
4119
+ try {
4120
+ const j = JSON.parse(data);
4121
+ const delta = j.choices?.[0]?.delta?.content ?? j.choices?.[0]?.message?.content ?? "";
4122
+ if (delta) {
4123
+ full += delta;
4124
+ opts.onChunk?.(delta);
4125
+ }
4126
+ if (j.oriro) {
4127
+ if (typeof j.oriro.byok_active === "boolean") meta.byok_active = j.oriro.byok_active;
4128
+ if (Array.isArray(j.oriro.skill_ids_used)) meta.skill_ids_used = j.oriro.skill_ids_used;
4129
+ if (j.oriro.model) meta.model = j.oriro.model;
4130
+ if (j.oriro.context_fill) meta.context_fill = j.oriro.context_fill;
4131
+ }
4132
+ if (j.context_fill) meta.context_fill = j.context_fill;
4133
+ } catch {
4134
+ }
4135
+ }
4136
+ }
4137
+ return { text: full, meta };
4138
+ }
4139
+ async function summarizeConversation(req, opts = {}) {
4140
+ const res = await fetch(`${API_BASE.replace(/\/v1$/, "")}/api/chat/summarize`, {
4141
+ method: "POST",
4142
+ headers: { "content-type": "application/json", ...byokHeaders(opts.byok, opts.apiKey) },
4143
+ body: JSON.stringify(req)
4144
+ });
4145
+ if (!res.ok) {
4146
+ const detail = await res.text().catch(() => "");
4147
+ throw new Error(`ORIRO summarize ${res.status}: ${detail.slice(0, 200)}`);
4148
+ }
4149
+ return res.json();
4150
+ }
4151
+
4152
+ // packages/core/src/auth.ts
4153
+ var AUTH_BASE = API_BASE.replace(/\/v1$/, "");
4154
+ async function postJson(path, body) {
4155
+ const res = await fetch(`${AUTH_BASE}${path}`, {
4156
+ method: "POST",
4157
+ headers: { "content-type": "application/json" },
4158
+ body: JSON.stringify(body)
4159
+ });
4160
+ let j = {};
4161
+ try {
4162
+ j = await res.json();
4163
+ } catch {
4164
+ }
4165
+ return { status: res.status, body: j };
4166
+ }
4167
+ async function requestOtp(email) {
4168
+ const { status, body } = await postJson("/api/auth/email-otp/request", { email });
4169
+ if (status >= 400) return { sent: false, error: body?.error ?? `http_${status}`, message: body?.message };
4170
+ return { sent: body?.sent === true, dev_code: body?.dev_code };
4171
+ }
4172
+ async function verifyOtp(email, code) {
4173
+ const { status, body } = await postJson("/api/auth/email-otp/verify", { email, code });
4174
+ if (status >= 400 || !body?.success) {
4175
+ return { success: false, error: body?.error ?? `http_${status}`, message: body?.message };
4176
+ }
4177
+ return {
4178
+ success: true,
4179
+ user: body.user,
4180
+ session_token: body.session_token,
4181
+ is_new: body.is_new
4182
+ };
4183
+ }
4184
+
4185
+ // packages/core/src/router.ts
4186
+ function resolveModel(choice) {
4187
+ return choice && ["avila", "gauss", "auto"].includes(choice) ? choice : "auto";
4188
+ }
4189
+
4190
+ // packages/core/src/share.ts
4191
+ import { homedir as homedir2 } from "node:os";
4192
+ import { join as join2 } from "node:path";
4193
+ import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs";
4194
+ var DIR2 = join2(homedir2(), ".oriro");
4195
+ var QUEUE = join2(DIR2, "share-queue.jsonl");
4196
+ function recordInteraction(prompt, response) {
4197
+ const { score, flags } = scoreInteractionPair(prompt, response);
4198
+ const poisoned = score < 0.5;
4199
+ const cfg = readConfig();
4200
+ if (cfg.share_interactions === false) return { recorded: false, score, flags, poisoned };
4201
+ try {
4202
+ mkdirSync2(DIR2, { recursive: true });
4203
+ appendFileSync(QUEUE, JSON.stringify({
4204
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
4205
+ prompt: stripPII(prompt).text,
4206
+ response: stripPII(response).text,
4207
+ score,
4208
+ flags,
4209
+ poisoned
4210
+ }) + "\n", "utf8");
4211
+ return { recorded: true, score, flags, poisoned };
4212
+ } catch {
4213
+ return { recorded: false, score, flags, poisoned };
4214
+ }
4215
+ }
4216
+
4217
+ // packages/cli/src/ui/splash.ts
4218
+ var VERSION = "1.0.0";
4219
+ function printSplash() {
4220
+ const W = ["O", "R", "I", "R", "O"];
4221
+ const cols = ["#39FF6E", "#2BD47F", "#3B8BFF", "#6B5FFF", "#A855F7"];
4222
+ const mark = W.map((c, i) => source_default.hex(cols[i]).bold(c)).join(" ");
4223
+ const div = source_default.dim("\u2500".repeat(54));
4224
+ const k = (s) => source_default.dim(s);
4225
+ const v = (s) => source_default.white(s);
4226
+ console.log();
4227
+ console.log(" " + mark + " " + source_default.dim.bold("TERMINAL INTELLIGENCE"));
4228
+ console.log();
4229
+ console.log(" " + source_default.hex("#39FF6E")("\u25C6") + source_default.bold(" ORIRO AI") + source_default.dim(` v${VERSION} \xB7 MIT \xB7 oriro.ai`));
4230
+ console.log(" " + div);
4231
+ console.log(` ${k("Models")} ${v("Avila + Gauss")} ${k("Security")} ${v("Guardian V3 \u2713")}`);
4232
+ console.log(` ${k("Context")} ${v("128K (YaRN)")} ${k("Telemetry")} ${v("none \xB7 local only")}`);
4233
+ console.log(` ${k("Training")} ${v("2.2M pairs \xB7 nightly")} ${k("Routing")} ${v("auto \u2192 @avila @gauss")}`);
4234
+ console.log(" " + div);
4235
+ console.log(" " + source_default.dim("/help /model avila /model gauss /skill list /skill add /status /byok /clear /exit"));
4236
+ console.log();
4237
+ }
4238
+
4239
+ // packages/cli/src/ui/stream.ts
4240
+ async function streamResponse(messages, model, skills, agents) {
4241
+ const label = model === "auto" ? "oriro" : model;
4242
+ process.stdout.write(source_default.dim(`
4243
+ ${label} \u203A `));
4244
+ const r = await chatStream(messages, {
4245
+ model,
4246
+ skillIds: skills,
4247
+ agentIds: agents,
4248
+ onChunk: (t) => process.stdout.write(t)
4249
+ });
4250
+ process.stdout.write("\n");
4251
+ return r;
4252
+ }
4253
+
4254
+ // packages/cli/src/ui/health.ts
4255
+ var CONTEXT_HEALTH_THRESHOLD = 102400;
4256
+ async function trackContextHealth(sess, userText, reply) {
4257
+ sess.tokensUsed += estimateTokens(userText) + estimateTokens(reply);
4258
+ if (sess.healthShown || sess.tokensUsed < CONTEXT_HEALTH_THRESHOLD) return;
4259
+ sess.healthShown = true;
4260
+ console.log(source_default.yellow(
4261
+ "\nThis session is getting long \u2014 start a fresh one to keep the best results. Here's a summary of everything so far.\n"
4262
+ ));
4263
+ try {
4264
+ const r = await summarizeConversation({ messages: sess.messages, model: sess.model });
4265
+ console.log(source_default.dim("\u2014 session summary \u2014"));
4266
+ console.log(`${r.summary}
4267
+ `);
4268
+ } catch (e) {
4269
+ console.error(source_default.dim(`(summary unavailable: ${e.message})`));
4270
+ }
4271
+ }
4272
+
4273
+ // packages/connectors/src/catalog.ts
4274
+ async function fetchConnectors() {
4275
+ const r = await fetch(`${API_BASE}/api/connectors`);
4276
+ if (!r.ok) throw new Error(`/api/connectors \u2192 ${r.status}`);
4277
+ const j = await r.json();
4278
+ return j.connectors ?? j ?? [];
4279
+ }
4280
+ function findConnector(cons, name) {
4281
+ const k = name.toLowerCase();
4282
+ return cons.find((c) => (c.slug ?? "").toLowerCase() === k || (c.name ?? "").toLowerCase() === k);
4283
+ }
4284
+
4285
+ // packages/connectors/src/connect.ts
4286
+ function published(c) {
4287
+ return c.is_published === true || c.is_published === 1;
4288
+ }
4289
+ async function handleConnect(name) {
4290
+ let cons;
4291
+ try {
4292
+ cons = await fetchConnectors();
4293
+ } catch (e) {
4294
+ console.log(source_default.red(`[connect] ${e.message}`));
4295
+ return;
4296
+ }
4297
+ if (!name) {
4298
+ console.log(source_default.bold(`
4299
+ ${cons.length} connectors:`));
4300
+ cons.slice(0, 40).forEach((c2) => console.log(` ${c2.name ?? c2.slug}${published(c2) ? "" : source_default.dim(" (coming soon)")}`));
4301
+ if (cons.length > 40) console.log(source_default.dim(` \u2026and ${cons.length - 40} more`));
4302
+ return;
4303
+ }
4304
+ const c = findConnector(cons, name);
4305
+ if (!c) {
4306
+ console.log(source_default.dim(`connector "${name}" not found \u2014 /connect to list`));
4307
+ return;
4308
+ }
4309
+ console.log(source_default.bold(`
4310
+ ${c.name ?? c.slug}`));
4311
+ if (c.description) console.log(" " + c.description);
4312
+ console.log(` status: ${published(c) ? source_default.green("available") : source_default.yellow("coming soon")}`);
4313
+ console.log(` auth: ${c.auth_type ?? "oauth"}${c.mcp_url ? source_default.dim(" \xB7 MCP " + c.mcp_url) : ""}`);
4314
+ console.log(source_default.dim(` usage: mention "${c.slug ?? c.name}" in a prompt; authorize at oriro.ai/connect`));
4315
+ }
4316
+
4317
+ // packages/skills/src/catalog.ts
4318
+ async function fetchSkills() {
4319
+ const r = await fetch(`${API_BASE}/api/skills`);
4320
+ if (!r.ok) throw new Error(`/api/skills \u2192 ${r.status}`);
4321
+ const j = await r.json();
4322
+ return j.skills ?? j ?? [];
4323
+ }
4324
+ function searchSkills(skills, query) {
4325
+ const q = query.toLowerCase();
4326
+ return skills.filter((s) => `${s.name ?? ""} ${s.id ?? ""} ${s.description ?? ""} ${s.category ?? ""}`.toLowerCase().includes(q));
4327
+ }
4328
+
4329
+ // packages/cli/src/commands/slash.ts
4330
+ async function handleSlash(sess, line) {
4331
+ const [cmd, ...rest] = line.trim().split(/\s+/);
4332
+ switch (cmd) {
4333
+ case "/help":
4334
+ console.log(source_default.bold("\nORIRO commands"));
4335
+ console.log(" /model avila|gauss|auto switch model / restore auto-routing");
4336
+ console.log(" /skill list|add <n>|remove <n> manage session skills");
4337
+ console.log(" /status model, routing, skills, Guardian");
4338
+ console.log(" /config show ~/.oriro/config.json");
4339
+ console.log(" /byok --gemini|--claude|--openai KEY use your own key (optional)");
4340
+ console.log(" /byok off remove BYOK, revert to native models");
4341
+ console.log(" /connect <name> connector status + usage");
4342
+ console.log(" @file.ts inject a file into your prompt");
4343
+ console.log(" /clear reset screen + history");
4344
+ console.log(" /exit quit\n");
4345
+ return;
4346
+ case "/model": {
4347
+ const m = (rest[0] || "").toLowerCase();
4348
+ if (!["avila", "gauss", "auto"].includes(m)) {
4349
+ console.log(source_default.dim("usage: /model avila|gauss|auto"));
4350
+ return;
4351
+ }
4352
+ sess.model = m;
4353
+ const cfg = readConfig();
4354
+ cfg.preferred_model = sess.model;
4355
+ writeConfig(cfg);
4356
+ const tag = m === "avila" ? "Avila \u2014 Human Intelligence" : m === "gauss" ? "Gauss \u2014 Technical Intelligence" : "auto-routing";
4357
+ console.log(source_default.green(`\u2713 ${m === "auto" ? "restored" : "switched to"} ${tag}`));
4358
+ return;
4359
+ }
4360
+ case "/skill": {
4361
+ const sub = rest[0];
4362
+ if (sub === "list") {
4363
+ try {
4364
+ const skills = await fetchSkills();
4365
+ console.log(source_default.bold(`
4366
+ ${skills.length} skills:`));
4367
+ skills.slice(0, 60).forEach((s) => console.log(" " + (s.name || s.id)));
4368
+ if (skills.length > 60) console.log(source_default.dim(` \u2026and ${skills.length - 60} more`));
4369
+ } catch (e) {
4370
+ console.log(source_default.red(`[skill list] ${e.message}`));
4371
+ }
4372
+ } else if (sub === "add" && rest[1]) {
4373
+ if (!sess.skills.includes(rest[1])) sess.skills.push(rest[1]);
4374
+ console.log(source_default.green(`\u2713 skill enabled: ${rest[1]}`));
4375
+ } else if (sub === "remove" && rest[1]) {
4376
+ sess.skills = sess.skills.filter((s) => s !== rest[1]);
4377
+ console.log(source_default.green(`\u2713 skill removed: ${rest[1]}`));
4378
+ } else {
4379
+ console.log(source_default.dim("usage: /skill list | /skill add <name> | /skill remove <name>"));
4380
+ }
4381
+ return;
4382
+ }
4383
+ case "/status":
4384
+ console.log(source_default.bold("\nstatus"));
4385
+ console.log(` model: ${sess.model}`);
4386
+ console.log(` routing: ${sess.model === "auto" ? "auto \u2192 @avila @gauss (worker-routed)" : "forced " + sess.model}`);
4387
+ console.log(` skills: ${sess.skills.length ? sess.skills.join(", ") : "none"}`);
4388
+ console.log(` Guardian: V3 \u2713 (local)`);
4389
+ if (anyByokActive()) console.log(" byok: active (unlimited)");
4390
+ console.log();
4391
+ return;
4392
+ case "/config":
4393
+ console.log(JSON.stringify({ ...readConfig(), byok: anyByokActive() ? "<encrypted>" : void 0 }, null, 2));
4394
+ return;
4395
+ case "/byok": {
4396
+ if (rest[0] === "off") {
4397
+ clearByok();
4398
+ console.log(source_default.green("\u2713 BYOK removed \u2014 back to ORIRO native models"));
4399
+ return;
4400
+ }
4401
+ const map = { "--gemini": "gemini", "--claude": "claude", "--openai": "openai" };
4402
+ const prov = map[rest[0]];
4403
+ if (!prov || !rest[1]) {
4404
+ console.log(source_default.dim("usage: /byok --gemini|--claude|--openai KEY | /byok off"));
4405
+ return;
4406
+ }
4407
+ setByok(prov, rest[1]);
4408
+ console.log(source_default.green(`\u2713 ${prov[0].toUpperCase() + prov.slice(1)} key saved. Guardian V3 active.`));
4409
+ return;
4410
+ }
4411
+ case "/connect":
4412
+ await handleConnect(rest[0]);
4413
+ return;
4414
+ case "/clear":
4415
+ console.clear();
4416
+ sess.messages = [];
4417
+ printSplash();
4418
+ return;
4419
+ case "/exit":
4420
+ case "/quit":
4421
+ console.log(source_default.dim("bye."));
4422
+ process.exit(0);
4423
+ default:
4424
+ console.log(source_default.dim(`unknown command ${cmd} \u2014 try /help`));
4425
+ }
4426
+ }
4427
+
4428
+ // packages/cli/src/input/fileref.ts
4429
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
4430
+ import { resolve } from "node:path";
4431
+ function injectFiles(input) {
4432
+ return input.replace(/@(\S+)/g, (m, fn) => {
4433
+ const p = resolve(process.cwd(), fn);
4434
+ if (!existsSync2(p)) {
4435
+ console.log(source_default.dim(`[file not found: ${fn}]`));
4436
+ return m;
4437
+ }
4438
+ try {
4439
+ return `
4440
+
4441
+ --- ${fn} ---
4442
+ ${readFileSync2(p, "utf8")}
4443
+ --- end ${fn} ---
4444
+ `;
4445
+ } catch {
4446
+ return m;
4447
+ }
4448
+ });
4449
+ }
4450
+
4451
+ // packages/cli/src/commands/settings.ts
4452
+ function runSettings(opts = {}) {
4453
+ const cfg = readConfig();
4454
+ if (opts.noShare) {
4455
+ cfg.share_interactions = false;
4456
+ writeConfig(cfg);
4457
+ console.log(source_default.green("\u2713 opted OUT of nightly sharing. Nothing leaves this machine."));
4458
+ return;
4459
+ }
4460
+ if (opts.share) {
4461
+ cfg.share_interactions = true;
4462
+ writeConfig(cfg);
4463
+ console.log(source_default.green("\u2713 opted IN to nightly sharing (Guardian-screened, anonymized)."));
4464
+ return;
4465
+ }
4466
+ const sharing = cfg.share_interactions !== false;
4467
+ if (opts.json) {
4468
+ console.log(JSON.stringify({
4469
+ account: cfg.oauth_email ?? null,
4470
+ preferred_model: cfg.preferred_model ?? "auto",
4471
+ share_interactions: sharing,
4472
+ first_run_done: cfg.first_run_done === true
4473
+ }));
4474
+ return;
4475
+ }
4476
+ console.log(source_default.bold("\nORIRO settings"));
4477
+ console.log(` account: ${cfg.oauth_email ?? source_default.dim("(not signed in \u2014 oriro login)")}`);
4478
+ console.log(` preferred model: ${cfg.preferred_model ?? "auto"}`);
4479
+ console.log(` nightly sharing: ${sharing ? source_default.cyan("on") : source_default.yellow("off")} ${source_default.dim("(toggle: oriro settings --no-share | --share)")}`);
4480
+ console.log(source_default.dim(" ORIRO is free forever \u2014 no token limits, no metering, no quota.\n"));
4481
+ }
4482
+ function showFirstRunOnce() {
4483
+ const cfg = readConfig();
4484
+ if (cfg.first_run_done === true) return;
4485
+ console.error(source_default.dim(
4486
+ "ORIRO CLI shares anonymous usage patterns nightly to improve models.\nRun 'oriro settings --no-share' anytime to opt out.\n"
4487
+ ));
4488
+ cfg.first_run_done = true;
4489
+ writeConfig(cfg);
4490
+ }
4491
+
4492
+ // packages/cli/src/commands/run.ts
4493
+ async function runOneShot(promptText, opts = {}) {
4494
+ showFirstRunOnce();
4495
+ let piped = "";
4496
+ if (!process.stdin.isTTY) {
4497
+ piped = await new Promise((res) => {
4498
+ let d = "";
4499
+ process.stdin.on("data", (c) => d += c);
4500
+ process.stdin.on("end", () => res(d));
4501
+ });
4502
+ }
4503
+ const raw = injectFiles(promptText) + (piped ? `
4504
+
4505
+ --- input ---
4506
+ ${piped}
4507
+ ` : "");
4508
+ const sani = stripHiddenUnicode(raw);
4509
+ if (sani.stripped) console.error(source_default.dim("[Guardian] hidden unicode removed"));
4510
+ const inj = scanFileInput(sani.text);
4511
+ if (!inj.safe) {
4512
+ console.error(source_default.yellow(`[Guardian] blocked (${inj.threat}) \u2014 not sent.`));
4513
+ process.exit(2);
4514
+ }
4515
+ const g = stripPII(sani.text);
4516
+ if (g.redacted) console.error(source_default.dim("[Guardian V3] sensitive data removed before sending"));
4517
+ const model = resolveModel(opts.model || readConfig().preferred_model);
4518
+ let reply;
4519
+ let meta;
4520
+ try {
4521
+ ({ text: reply, meta } = await chatStream([{ role: "user", content: g.text }], {
4522
+ model,
4523
+ onChunk: opts.json ? void 0 : (c) => process.stdout.write(c)
4524
+ }));
4525
+ } catch (e) {
4526
+ console.error(source_default.red(`[seam] ${e.message}`));
4527
+ process.exit(1);
4528
+ }
4529
+ recordInteraction(g.text, reply);
4530
+ if (opts.json) {
4531
+ process.stdout.write(JSON.stringify({
4532
+ response: reply,
4533
+ model: meta.model || model,
4534
+ skill_ids_used: meta.skill_ids_used,
4535
+ routing: model
4536
+ }) + "\n");
4537
+ } else {
4538
+ process.stdout.write("\n");
4539
+ }
4540
+ }
4541
+
4542
+ // packages/cli/src/commands/login.ts
4543
+ import readline from "node:readline";
4544
+ function ask(question, opts = {}) {
4545
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
4546
+ return new Promise((resolve2) => {
4547
+ rl.question(source_default.cyan(question), (answer) => {
4548
+ rl.close();
4549
+ resolve2(answer.trim());
4550
+ });
4551
+ if (opts.mask) {
4552
+ const r = rl;
4553
+ r._writeToOutput = (s) => {
4554
+ if (s.includes(question)) r.output.write(s);
4555
+ };
4556
+ }
4557
+ });
4558
+ }
4559
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4560
+ async function runLogin() {
4561
+ console.log(source_default.bold("\nORIRO sign-in") + source_default.dim(" (optional \u2014 ORIRO is free without it)"));
4562
+ const email = (await ask("email: ")).toLowerCase();
4563
+ if (!EMAIL_RE.test(email)) {
4564
+ console.error(source_default.red("not a valid email address."));
4565
+ process.exit(1);
4566
+ }
4567
+ const req = await requestOtp(email).catch((e) => ({ sent: false, error: e.message }));
4568
+ if (!req.sent) {
4569
+ console.error(source_default.red(`couldn't send a code: ${req.message || req.error || "unknown error"}`));
4570
+ process.exit(1);
4571
+ }
4572
+ if (req.dev_code) console.log(source_default.dim(`(dev) code: ${req.dev_code}`));
4573
+ console.log(source_default.dim("a 6-digit code was emailed to you (valid 10 min)."));
4574
+ const code = (await ask("code: ")).replace(/\s/g, "");
4575
+ if (!/^\d{6}$/.test(code)) {
4576
+ console.error(source_default.red("codes are 6 digits."));
4577
+ process.exit(1);
4578
+ }
4579
+ const v = await verifyOtp(email, code).catch((e) => ({ success: false, error: e.message }));
4580
+ if (!v.success) {
4581
+ console.error(source_default.red(`sign-in failed: ${v.message || v.error || "invalid or expired code"}`));
4582
+ process.exit(1);
4583
+ }
4584
+ const cfg = readConfig();
4585
+ cfg.oauth_email = v.user?.email ?? email;
4586
+ writeConfig(cfg);
4587
+ console.log(source_default.green(`\u2713 signed in as ${cfg.oauth_email}${v.is_new ? " (new account)" : ""}.`));
4588
+ console.log(source_default.dim(" sign out any time: oriro logout\n"));
4589
+ }
4590
+ function runLogout() {
4591
+ const cfg = readConfig();
4592
+ if (!cfg.oauth_email) {
4593
+ console.log(source_default.dim("not signed in."));
4594
+ return;
4595
+ }
4596
+ const who = cfg.oauth_email;
4597
+ delete cfg.oauth_email;
4598
+ writeConfig(cfg);
4599
+ console.log(source_default.green(`\u2713 signed out ${who}. (ORIRO stays free and usable.)`));
4600
+ }
4601
+
4602
+ // packages/cli/src/commands/skills.ts
4603
+ async function runSkills(query, opts = {}) {
4604
+ let skills;
4605
+ try {
4606
+ skills = await fetchSkills();
4607
+ } catch (e) {
4608
+ console.error(source_default.red(`couldn't load skills: ${e.message}`));
4609
+ process.exit(1);
4610
+ }
4611
+ const filtered = query && query.trim() ? searchSkills(skills, query.trim()) : skills;
4612
+ if (opts.json) {
4613
+ process.stdout.write(JSON.stringify(
4614
+ filtered.map((s) => ({ id: s.id, name: s.name, category: s.category, description: s.description }))
4615
+ ) + "\n");
4616
+ return;
4617
+ }
4618
+ const header = query && query.trim() ? `${filtered.length} skill${filtered.length === 1 ? "" : "s"} matching "${query.trim()}" (of ${skills.length})` : `${skills.length} ORIRO skills`;
4619
+ console.log(source_default.bold(`
4620
+ ${header}`));
4621
+ if (filtered.length === 0) {
4622
+ console.log(source_default.dim(" (none)\n"));
4623
+ return;
4624
+ }
4625
+ const byCat = /* @__PURE__ */ new Map();
4626
+ for (const s of filtered) {
4627
+ const cat = s.category || "general";
4628
+ (byCat.get(cat) ?? byCat.set(cat, []).get(cat)).push(s);
4629
+ }
4630
+ for (const cat of [...byCat.keys()].sort()) {
4631
+ console.log(source_default.magenta(`
4632
+ ${cat}`));
4633
+ for (const s of byCat.get(cat)) {
4634
+ const name = s.name || s.id || "(unnamed)";
4635
+ const desc = s.description ? source_default.dim(` \u2014 ${s.description.slice(0, 70)}`) : "";
4636
+ console.log(` ${source_default.cyan(name)}${desc}`);
4637
+ }
4638
+ }
4639
+ console.log(source_default.dim("\n These run server-side; the worker injects the relevant ones per request.\n"));
4640
+ }
4641
+
4642
+ // packages/cli/src/commands/build.ts
4643
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync2 } from "node:fs";
4644
+ import { join as join3, dirname } from "node:path";
4645
+ var BUILD_DIR = join3(process.cwd(), "oriro-build");
4646
+ var BUILD_SYSTEM = 'You are Gauss, ORIRO technical intelligence. BUILD what the user asks for: output a complete, working result (code/files), not a plan. Use smart professional defaults. When producing multiple files, precede each with a line "// FILE: <relative/path>" so they can be written to disk.';
4647
+ async function runBuild(description, opts = {}) {
4648
+ showFirstRunOnce();
4649
+ const raw = injectFiles(description);
4650
+ const sani = stripHiddenUnicode(raw);
4651
+ if (sani.stripped) console.error(source_default.dim("[Guardian] hidden unicode removed"));
4652
+ const inj = scanFileInput(sani.text);
4653
+ if (!inj.safe) {
4654
+ console.error(source_default.yellow(`[Guardian] blocked (${inj.threat}) \u2014 not sent.`));
4655
+ process.exit(2);
4656
+ }
4657
+ const g = stripPII(sani.text);
4658
+ if (g.redacted) console.error(source_default.dim("[Guardian V3] sensitive data removed before sending"));
4659
+ console.error(source_default.dim("Gauss \u203A building\u2026"));
4660
+ let reply = "";
4661
+ try {
4662
+ const r = await chatStream(
4663
+ [{ role: "system", content: BUILD_SYSTEM }, { role: "user", content: g.text }],
4664
+ { model: opts.model || "gauss", onChunk: (ch) => process.stderr.write(ch) }
4665
+ );
4666
+ reply = r.text;
4667
+ } catch (e) {
4668
+ console.error(source_default.red(`
4669
+ build seam error: ${e.message}`));
4670
+ console.error(source_default.dim("(ORIRO models join at graduation; the build seam is wired + Guardian-screened now.)"));
4671
+ process.exit(1);
4672
+ }
4673
+ process.stderr.write("\n");
4674
+ mkdirSync3(BUILD_DIR, { recursive: true });
4675
+ const written = writeBuildFiles(reply);
4676
+ recordInteraction(g.text, reply);
4677
+ console.log(source_default.green(`\u2713 build written to ./oriro-build/ (${written.length} file${written.length === 1 ? "" : "s"})`));
4678
+ for (const f of written) console.log(` ${f}`);
4679
+ console.log(source_default.dim(" (deploy target \u2014 CF Pages URL / agent id \u2014 lands with the build-deploy seam.)"));
4680
+ }
4681
+ function writeBuildFiles(output) {
4682
+ const text = output ?? "";
4683
+ const marker = /(^|\n)\/\/ FILE:\s*(.+?)\s*\n/g;
4684
+ const matches = [...text.matchAll(marker)];
4685
+ if (matches.length === 0) {
4686
+ writeFileSync2(join3(BUILD_DIR, "output.md"), text || "(empty \u2014 model seam returned no content yet)", "utf8");
4687
+ return ["output.md"];
4688
+ }
4689
+ const written = [];
4690
+ for (let i = 0; i < matches.length; i++) {
4691
+ const m = matches[i];
4692
+ const rel = sanitizeRel(m[2]);
4693
+ const start = (m.index ?? 0) + m[0].length;
4694
+ const end = i + 1 < matches.length ? matches[i + 1].index ?? text.length : text.length;
4695
+ const body = text.slice(start, end).trim();
4696
+ const full = join3(BUILD_DIR, rel);
4697
+ mkdirSync3(dirname(full), { recursive: true });
4698
+ writeFileSync2(full, `${body}
4699
+ `, "utf8");
4700
+ written.push(rel);
4701
+ }
4702
+ return written;
4703
+ }
4704
+ function sanitizeRel(p) {
4705
+ const cleaned = p.replace(/\\/g, "/").replace(/^\/+/, "").split("/").filter((s) => s && s !== "..").join("/");
4706
+ return cleaned || "output.md";
4707
+ }
4708
+
4709
+ // packages/cli/src/input/readline.ts
4710
+ import readline2 from "node:readline";
4711
+ import { basename } from "node:path";
4712
+ function runInputLoop(onSubmit) {
4713
+ const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
4714
+ let multi = false;
4715
+ const buf = [];
4716
+ const prompt = () => {
4717
+ rl.setPrompt(source_default.dim(`~/${basename(process.cwd())} \u203A `));
4718
+ rl.prompt();
4719
+ };
4720
+ const flush = async () => {
4721
+ const t = buf.join("\n");
4722
+ buf.length = 0;
4723
+ if (t.trim()) await onSubmit(t);
4724
+ };
4725
+ prompt();
4726
+ rl.on("line", async (raw) => {
4727
+ const line = raw.replace(/\r$/, "");
4728
+ if (line.trim() === '"""') {
4729
+ if (multi) {
4730
+ multi = false;
4731
+ await flush();
4732
+ } else {
4733
+ multi = true;
4734
+ }
4735
+ prompt();
4736
+ return;
4737
+ }
4738
+ if (multi) {
4739
+ if (line === "") {
4740
+ multi = false;
4741
+ await flush();
4742
+ } else {
4743
+ buf.push(line);
4744
+ }
4745
+ prompt();
4746
+ return;
4747
+ }
4748
+ const t = line.trim();
4749
+ if (t) await onSubmit(t);
4750
+ prompt();
4751
+ });
4752
+ rl.on("close", () => {
4753
+ console.log(source_default.dim("\nbye."));
4754
+ process.exit(0);
4755
+ });
4756
+ }
4757
+
4758
+ // packages/cli/src/session.ts
4759
+ function newSession(model, skills = []) {
4760
+ return { model, skills, agents: [], messages: [], tokensUsed: 0, healthShown: false };
4761
+ }
4762
+
4763
+ // packages/cli/src/index.ts
4764
+ var VERSION2 = "1.0.0";
4765
+ async function sendChat(sess, text) {
4766
+ const sani = stripHiddenUnicode(text);
4767
+ const inj = scanFileInput(sani.text);
4768
+ if (!inj.safe) {
4769
+ console.error(source_default.yellow(`[Guardian] blocked (${inj.threat}) \u2014 not sent to the model.`));
4770
+ return;
4771
+ }
4772
+ const g = stripPII(sani.text);
4773
+ if (g.redacted) console.error(source_default.dim("[Guardian V3] sensitive data removed before sending"));
4774
+ sess.messages.push({ role: "user", content: g.text });
4775
+ let reply;
4776
+ try {
4777
+ ({ text: reply } = await streamResponse(sess.messages, sess.model, sess.skills, sess.agents));
4778
+ } catch (e) {
4779
+ console.error(source_default.red(`
4780
+ [seam] ${e.message}`));
4781
+ sess.messages.pop();
4782
+ return;
4783
+ }
4784
+ sess.messages.push({ role: "assistant", content: reply });
4785
+ recordInteraction(g.text, reply);
4786
+ await trackContextHealth(sess, g.text, reply);
4787
+ }
4788
+ function startRepl(model) {
4789
+ showFirstRunOnce();
4790
+ const cfg = readConfig();
4791
+ const sess = newSession(resolveModel(model || cfg.preferred_model), cfg.enabled_skills ?? []);
4792
+ printSplash();
4793
+ runInputLoop(async (raw) => {
4794
+ const t = raw.trim();
4795
+ if (t.startsWith("/")) await handleSlash(sess, t);
4796
+ else await sendChat(sess, injectFiles(t));
4797
+ });
4798
+ }
4799
+ program.name("oriro").description("ORIRO \u2014 free on-device AI terminal \xB7 Avila + Gauss \xB7 128K (YaRN)").version(VERSION2);
4800
+ program.command("run <prompt>").description("one-shot: stream a response and exit (pipe-friendly)").option("--json", "structured JSON output").option("--model <m>", "avila | gauss | auto").action((prompt, opts) => runOneShot(prompt, { json: opts.json, model: opts.model }));
4801
+ program.command("chat [prompt]").description("chat with ORIRO \u2014 interactive REPL, or one-shot if a prompt is given (free Avila/Gauss by default; your BYOK route if active)").option("--model <m>", "avila | gauss | auto").action((prompt, opts) => {
4802
+ if (prompt && prompt.trim()) return runOneShot(prompt, { model: opts.model });
4803
+ startRepl(opts.model);
4804
+ });
4805
+ program.command("byok").description("bring your own key \u2014 link MANY providers/routers at once, switch any time (optional; ORIRO is free without it)").argument("[action]", "list | set | use | status | clear", "list").argument("[provider]", "provider id (see `oriro byok list`)").argument("[key]", "API key (for set) \u2014 or model id (for use)").argument("[model]", "optional model id for set (free-form; e.g. openai/gpt-4.1 for openrouter)").action((action, provider, keyArg, model) => {
4806
+ if (action === "set") {
4807
+ if (!provider || !keyArg) {
4808
+ console.error(source_default.red("usage: oriro byok set <provider> <key> [model]"));
4809
+ process.exit(1);
4810
+ }
4811
+ const info = getProvider(provider);
4812
+ if (!info) {
4813
+ console.error(source_default.red(`unknown provider "${provider}". Run: oriro byok list`));
4814
+ process.exit(1);
4815
+ }
4816
+ setByok(info.id, keyArg, model);
4817
+ console.log(source_default.green(`\u2713 linked ${info.label}${model ? ` \xB7 model ${model}` : ""} \u2014 now the active route. (ORIRO stays free; BYOK is optional.)`));
4818
+ return;
4819
+ }
4820
+ if (action === "use") {
4821
+ if (!provider) {
4822
+ console.error(source_default.red("usage: oriro byok use <provider> [model]"));
4823
+ process.exit(1);
4824
+ }
4825
+ const info = getProvider(provider);
4826
+ if (!info) {
4827
+ console.error(source_default.red(`unknown provider "${provider}". Run: oriro byok list`));
4828
+ process.exit(1);
4829
+ }
4830
+ if (useByok(
4831
+ info.id,
4832
+ keyArg
4833
+ /* model in this slot for `use` */
4834
+ )) {
4835
+ console.log(source_default.green(`\u2713 now routing to ${info.label}${keyArg ? ` \xB7 model ${keyArg}` : ""}.`));
4836
+ } else {
4837
+ console.error(source_default.red(`${info.label} isn't linked yet. Link it first: oriro byok set ${info.id} <key> [model]`));
4838
+ process.exit(1);
4839
+ }
4840
+ return;
4841
+ }
4842
+ if (action === "status") {
4843
+ const linked2 = linkedProviders();
4844
+ const { provider: active2, model: activeModel } = activeProvider();
4845
+ console.log(source_default.bold("\nActive route: ") + (active2 ? source_default.cyan(`${active2}${activeModel ? ` \xB7 ${activeModel}` : ""}`) : source_default.green("ORIRO Avila + Gauss (free)")));
4846
+ console.log(source_default.bold("Linked keys: ") + (linked2.length ? linked2.map((id) => source_default.cyan(id)).join(", ") : source_default.dim("none")));
4847
+ console.log(source_default.dim(" switch any time: oriro byok use <provider> [model]\n"));
4848
+ return;
4849
+ }
4850
+ if (action === "clear") {
4851
+ if (provider) {
4852
+ const info = getProvider(provider);
4853
+ clearByok(info?.id ?? provider);
4854
+ console.log(source_default.green(`\u2713 unlinked ${info?.label ?? provider}. Other keys kept.`));
4855
+ } else {
4856
+ clearByok();
4857
+ console.log(source_default.green("\u2713 all BYOK keys cleared \u2014 back to ORIRO Avila + Gauss (free)."));
4858
+ }
4859
+ return;
4860
+ }
4861
+ const linked = new Set(linkedProviders());
4862
+ const { provider: active } = activeProvider();
4863
+ console.log(source_default.bold("\nBYOK providers \u2014 link as many as you like with ") + source_default.cyan("oriro byok set <provider> <key> [model]"));
4864
+ console.log(source_default.dim("then switch between them with ") + source_default.cyan("oriro byok use <provider>") + source_default.dim(" (ORIRO Avila + Gauss are free & default)\n"));
4865
+ for (const p of listProviders()) {
4866
+ const tag = p.router ? source_default.magenta(" [router]") : p.local ? source_default.blue(" [local]") : "";
4867
+ const mark = p.id === active ? source_default.green(" \u25CF active") : linked.has(p.id) ? source_default.green(" \u2713 linked") : "";
4868
+ console.log(` ${source_default.cyan(p.id.padEnd(12))}${p.label}${tag}${mark}`);
4869
+ console.log(` ${" ".repeat(14)}${source_default.dim(p.models.slice(0, 4).join(", "))}`);
4870
+ }
4871
+ console.log(source_default.dim("\n Routers (OpenRouter, Requesty, Glama, Unify, Portkey, LiteLLM) reach hundreds of models via vendor/model slugs."));
4872
+ console.log(source_default.dim(" The model field is free-form \u2014 name any model the provider offers. Multiple keys coexist; switch with `byok use`.\n"));
4873
+ });
4874
+ program.command("login").description("optional passwordless sign-in (email code) \u2014 ORIRO works without it").action(() => runLogin());
4875
+ program.command("logout").description("sign out (clears oauth_email; ORIRO stays free and usable)").action(() => runLogout());
4876
+ program.command("skills [query]").description("list the baked ORIRO skills (optionally filter by a query)").option("--json", "machine-readable output").action((query, opts) => runSkills(query, opts));
4877
+ program.command("settings").description("view settings, or --no-share to opt out of nightly anonymous sharing").option("--share", "opt IN to nightly anonymous sharing").option("--no-share", "opt OUT of nightly anonymous sharing").option("--json", "machine-readable output").action((opts) => {
4878
+ const explicitShare = process.argv.slice(2).includes("--share");
4879
+ runSettings({ noShare: opts.share === false, share: explicitShare, json: opts.json });
4880
+ });
4881
+ program.command("build <description>").description("technical build via Gauss + the seam \u2192 writes ./oriro-build/").option("--model <m>", "avila | gauss | auto (default gauss)").action((description, opts) => runBuild(description, opts));
4882
+ var argv = process.argv.slice(2);
4883
+ var wantsCommander = argv.includes("run") || argv.includes("byok") || argv.includes("chat") || argv.includes("login") || argv.includes("logout") || argv.includes("skills") || argv.includes("settings") || argv.includes("build") || argv.some((a) => ["--version", "-V", "--help", "-h"].includes(a));
4884
+ if (wantsCommander) {
4885
+ program.parse(process.argv);
4886
+ } else {
4887
+ const i = argv.indexOf("--model");
4888
+ startRepl(i >= 0 ? argv[i + 1] : void 0);
4889
+ }