webtty 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,36 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- var __create = Object.create;
4
- var __getProtoOf = Object.getPrototypeOf;
5
3
  var __defProp = Object.defineProperty;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- function __accessProp(key) {
9
- return this[key];
10
- }
11
- var __toESMCache_node;
12
- var __toESMCache_esm;
13
- var __toESM = (mod, isNodeMode, target) => {
14
- var canCache = mod != null && typeof mod === "object";
15
- if (canCache) {
16
- var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
- var cached = cache.get(mod);
18
- if (cached)
19
- return cached;
20
- }
21
- target = mod != null ? __create(__getProtoOf(mod)) : {};
22
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
- for (let key of __getOwnPropNames(mod))
24
- if (!__hasOwnProp.call(to, key))
25
- __defProp(to, key, {
26
- get: __accessProp.bind(mod, key),
27
- enumerable: true
28
- });
29
- if (canCache)
30
- cache.set(mod, to);
31
- return to;
32
- };
33
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
34
4
  var __returnValue = (v) => v;
35
5
  function __exportSetter(name, newValue) {
36
6
  this[name] = __returnValue.bind(null, newValue);
@@ -47,2128 +17,135 @@ var __export = (target, all) => {
47
17
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
48
18
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
49
19
 
50
- // node_modules/commander/lib/error.js
51
- var require_error = __commonJS((exports) => {
52
- class CommanderError extends Error {
53
- constructor(exitCode, code, message) {
54
- super(message);
55
- Error.captureStackTrace(this, this.constructor);
56
- this.name = this.constructor.name;
57
- this.code = code;
58
- this.exitCode = exitCode;
59
- this.nestedError = undefined;
60
- }
61
- }
62
-
63
- class InvalidArgumentError extends CommanderError {
64
- constructor(message) {
65
- super(1, "commander.invalidArgument", message);
66
- Error.captureStackTrace(this, this.constructor);
67
- this.name = this.constructor.name;
68
- }
69
- }
70
- exports.CommanderError = CommanderError;
71
- exports.InvalidArgumentError = InvalidArgumentError;
72
- });
73
-
74
- // node_modules/commander/lib/argument.js
75
- var require_argument = __commonJS((exports) => {
76
- var { InvalidArgumentError } = require_error();
77
-
78
- class Argument {
79
- constructor(name, description) {
80
- this.description = description || "";
81
- this.variadic = false;
82
- this.parseArg = undefined;
83
- this.defaultValue = undefined;
84
- this.defaultValueDescription = undefined;
85
- this.argChoices = undefined;
86
- switch (name[0]) {
87
- case "<":
88
- this.required = true;
89
- this._name = name.slice(1, -1);
90
- break;
91
- case "[":
92
- this.required = false;
93
- this._name = name.slice(1, -1);
94
- break;
95
- default:
96
- this.required = true;
97
- this._name = name;
98
- break;
99
- }
100
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
101
- this.variadic = true;
102
- this._name = this._name.slice(0, -3);
103
- }
104
- }
105
- name() {
106
- return this._name;
107
- }
108
- _concatValue(value, previous) {
109
- if (previous === this.defaultValue || !Array.isArray(previous)) {
110
- return [value];
111
- }
112
- return previous.concat(value);
113
- }
114
- default(value, description) {
115
- this.defaultValue = value;
116
- this.defaultValueDescription = description;
117
- return this;
118
- }
119
- argParser(fn) {
120
- this.parseArg = fn;
121
- return this;
122
- }
123
- choices(values) {
124
- this.argChoices = values.slice();
125
- this.parseArg = (arg, previous) => {
126
- if (!this.argChoices.includes(arg)) {
127
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
128
- }
129
- if (this.variadic) {
130
- return this._concatValue(arg, previous);
131
- }
132
- return arg;
133
- };
134
- return this;
135
- }
136
- argRequired() {
137
- this.required = true;
138
- return this;
139
- }
140
- argOptional() {
141
- this.required = false;
142
- return this;
143
- }
144
- }
145
- function humanReadableArgName(arg) {
146
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
147
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
148
- }
149
- exports.Argument = Argument;
150
- exports.humanReadableArgName = humanReadableArgName;
151
- });
152
-
153
- // node_modules/commander/lib/help.js
154
- var require_help = __commonJS((exports) => {
155
- var { humanReadableArgName } = require_argument();
156
-
157
- class Help {
158
- constructor() {
159
- this.helpWidth = undefined;
160
- this.minWidthToWrap = 40;
161
- this.sortSubcommands = false;
162
- this.sortOptions = false;
163
- this.showGlobalOptions = false;
164
- }
165
- prepareContext(contextOptions) {
166
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
167
- }
168
- visibleCommands(cmd) {
169
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
170
- const helpCommand = cmd._getHelpCommand();
171
- if (helpCommand && !helpCommand._hidden) {
172
- visibleCommands.push(helpCommand);
173
- }
174
- if (this.sortSubcommands) {
175
- visibleCommands.sort((a, b) => {
176
- return a.name().localeCompare(b.name());
177
- });
178
- }
179
- return visibleCommands;
180
- }
181
- compareOptions(a, b) {
182
- const getSortKey = (option) => {
183
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
184
- };
185
- return getSortKey(a).localeCompare(getSortKey(b));
186
- }
187
- visibleOptions(cmd) {
188
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
189
- const helpOption = cmd._getHelpOption();
190
- if (helpOption && !helpOption.hidden) {
191
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
192
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
193
- if (!removeShort && !removeLong) {
194
- visibleOptions.push(helpOption);
195
- } else if (helpOption.long && !removeLong) {
196
- visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
197
- } else if (helpOption.short && !removeShort) {
198
- visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
199
- }
200
- }
201
- if (this.sortOptions) {
202
- visibleOptions.sort(this.compareOptions);
203
- }
204
- return visibleOptions;
205
- }
206
- visibleGlobalOptions(cmd) {
207
- if (!this.showGlobalOptions)
208
- return [];
209
- const globalOptions = [];
210
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
211
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
212
- globalOptions.push(...visibleOptions);
213
- }
214
- if (this.sortOptions) {
215
- globalOptions.sort(this.compareOptions);
216
- }
217
- return globalOptions;
218
- }
219
- visibleArguments(cmd) {
220
- if (cmd._argsDescription) {
221
- cmd.registeredArguments.forEach((argument) => {
222
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
223
- });
224
- }
225
- if (cmd.registeredArguments.find((argument) => argument.description)) {
226
- return cmd.registeredArguments;
227
- }
228
- return [];
229
- }
230
- subcommandTerm(cmd) {
231
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
232
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
233
- }
234
- optionTerm(option) {
235
- return option.flags;
236
- }
237
- argumentTerm(argument) {
238
- return argument.name();
239
- }
240
- longestSubcommandTermLength(cmd, helper) {
241
- return helper.visibleCommands(cmd).reduce((max, command) => {
242
- return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
243
- }, 0);
244
- }
245
- longestOptionTermLength(cmd, helper) {
246
- return helper.visibleOptions(cmd).reduce((max, option) => {
247
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
248
- }, 0);
249
- }
250
- longestGlobalOptionTermLength(cmd, helper) {
251
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
252
- return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
253
- }, 0);
254
- }
255
- longestArgumentTermLength(cmd, helper) {
256
- return helper.visibleArguments(cmd).reduce((max, argument) => {
257
- return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
258
- }, 0);
259
- }
260
- commandUsage(cmd) {
261
- let cmdName = cmd._name;
262
- if (cmd._aliases[0]) {
263
- cmdName = cmdName + "|" + cmd._aliases[0];
264
- }
265
- let ancestorCmdNames = "";
266
- for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
267
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
268
- }
269
- return ancestorCmdNames + cmdName + " " + cmd.usage();
270
- }
271
- commandDescription(cmd) {
272
- return cmd.description();
273
- }
274
- subcommandDescription(cmd) {
275
- return cmd.summary() || cmd.description();
276
- }
277
- optionDescription(option) {
278
- const extraInfo = [];
279
- if (option.argChoices) {
280
- extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
281
- }
282
- if (option.defaultValue !== undefined) {
283
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
284
- if (showDefault) {
285
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
286
- }
287
- }
288
- if (option.presetArg !== undefined && option.optional) {
289
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
290
- }
291
- if (option.envVar !== undefined) {
292
- extraInfo.push(`env: ${option.envVar}`);
293
- }
294
- if (extraInfo.length > 0) {
295
- const extraDescription = `(${extraInfo.join(", ")})`;
296
- if (option.description) {
297
- return `${option.description} ${extraDescription}`;
298
- }
299
- return extraDescription;
300
- }
301
- return option.description;
302
- }
303
- argumentDescription(argument) {
304
- const extraInfo = [];
305
- if (argument.argChoices) {
306
- extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
307
- }
308
- if (argument.defaultValue !== undefined) {
309
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
310
- }
311
- if (extraInfo.length > 0) {
312
- const extraDescription = `(${extraInfo.join(", ")})`;
313
- if (argument.description) {
314
- return `${argument.description} ${extraDescription}`;
315
- }
316
- return extraDescription;
317
- }
318
- return argument.description;
319
- }
320
- formatItemList(heading, items, helper) {
321
- if (items.length === 0)
322
- return [];
323
- return [helper.styleTitle(heading), ...items, ""];
324
- }
325
- groupItems(unsortedItems, visibleItems, getGroup) {
326
- const result = new Map;
327
- unsortedItems.forEach((item) => {
328
- const group = getGroup(item);
329
- if (!result.has(group))
330
- result.set(group, []);
331
- });
332
- visibleItems.forEach((item) => {
333
- const group = getGroup(item);
334
- if (!result.has(group)) {
335
- result.set(group, []);
336
- }
337
- result.get(group).push(item);
338
- });
339
- return result;
340
- }
341
- formatHelp(cmd, helper) {
342
- const termWidth = helper.padWidth(cmd, helper);
343
- const helpWidth = helper.helpWidth ?? 80;
344
- function callFormatItem(term, description) {
345
- return helper.formatItem(term, termWidth, description, helper);
346
- }
347
- let output = [
348
- `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
349
- ""
350
- ];
351
- const commandDescription = helper.commandDescription(cmd);
352
- if (commandDescription.length > 0) {
353
- output = output.concat([
354
- helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
355
- ""
356
- ]);
357
- }
358
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
359
- return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
360
- });
361
- output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
362
- const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
363
- optionGroups.forEach((options, group) => {
364
- const optionList = options.map((option) => {
365
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
366
- });
367
- output = output.concat(this.formatItemList(group, optionList, helper));
368
- });
369
- if (helper.showGlobalOptions) {
370
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
371
- return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
372
- });
373
- output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
374
- }
375
- const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
376
- commandGroups.forEach((commands, group) => {
377
- const commandList = commands.map((sub) => {
378
- return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
379
- });
380
- output = output.concat(this.formatItemList(group, commandList, helper));
381
- });
382
- return output.join(`
383
- `);
384
- }
385
- displayWidth(str) {
386
- return stripColor(str).length;
387
- }
388
- styleTitle(str) {
389
- return str;
390
- }
391
- styleUsage(str) {
392
- return str.split(" ").map((word) => {
393
- if (word === "[options]")
394
- return this.styleOptionText(word);
395
- if (word === "[command]")
396
- return this.styleSubcommandText(word);
397
- if (word[0] === "[" || word[0] === "<")
398
- return this.styleArgumentText(word);
399
- return this.styleCommandText(word);
400
- }).join(" ");
401
- }
402
- styleCommandDescription(str) {
403
- return this.styleDescriptionText(str);
404
- }
405
- styleOptionDescription(str) {
406
- return this.styleDescriptionText(str);
407
- }
408
- styleSubcommandDescription(str) {
409
- return this.styleDescriptionText(str);
410
- }
411
- styleArgumentDescription(str) {
412
- return this.styleDescriptionText(str);
413
- }
414
- styleDescriptionText(str) {
415
- return str;
416
- }
417
- styleOptionTerm(str) {
418
- return this.styleOptionText(str);
419
- }
420
- styleSubcommandTerm(str) {
421
- return str.split(" ").map((word) => {
422
- if (word === "[options]")
423
- return this.styleOptionText(word);
424
- if (word[0] === "[" || word[0] === "<")
425
- return this.styleArgumentText(word);
426
- return this.styleSubcommandText(word);
427
- }).join(" ");
428
- }
429
- styleArgumentTerm(str) {
430
- return this.styleArgumentText(str);
431
- }
432
- styleOptionText(str) {
433
- return str;
434
- }
435
- styleArgumentText(str) {
436
- return str;
437
- }
438
- styleSubcommandText(str) {
439
- return str;
440
- }
441
- styleCommandText(str) {
442
- return str;
443
- }
444
- padWidth(cmd, helper) {
445
- return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
446
- }
447
- preformatted(str) {
448
- return /\n[^\S\r\n]/.test(str);
449
- }
450
- formatItem(term, termWidth, description, helper) {
451
- const itemIndent = 2;
452
- const itemIndentStr = " ".repeat(itemIndent);
453
- if (!description)
454
- return itemIndentStr + term;
455
- const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
456
- const spacerWidth = 2;
457
- const helpWidth = this.helpWidth ?? 80;
458
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
459
- let formattedDescription;
460
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
461
- formattedDescription = description;
462
- } else {
463
- const wrappedDescription = helper.boxWrap(description, remainingWidth);
464
- formattedDescription = wrappedDescription.replace(/\n/g, `
465
- ` + " ".repeat(termWidth + spacerWidth));
466
- }
467
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
468
- ${itemIndentStr}`);
469
- }
470
- boxWrap(str, width) {
471
- if (width < this.minWidthToWrap)
472
- return str;
473
- const rawLines = str.split(/\r\n|\n/);
474
- const chunkPattern = /[\s]*[^\s]+/g;
475
- const wrappedLines = [];
476
- rawLines.forEach((line) => {
477
- const chunks = line.match(chunkPattern);
478
- if (chunks === null) {
479
- wrappedLines.push("");
480
- return;
481
- }
482
- let sumChunks = [chunks.shift()];
483
- let sumWidth = this.displayWidth(sumChunks[0]);
484
- chunks.forEach((chunk) => {
485
- const visibleWidth = this.displayWidth(chunk);
486
- if (sumWidth + visibleWidth <= width) {
487
- sumChunks.push(chunk);
488
- sumWidth += visibleWidth;
489
- return;
490
- }
491
- wrappedLines.push(sumChunks.join(""));
492
- const nextChunk = chunk.trimStart();
493
- sumChunks = [nextChunk];
494
- sumWidth = this.displayWidth(nextChunk);
495
- });
496
- wrappedLines.push(sumChunks.join(""));
497
- });
498
- return wrappedLines.join(`
499
- `);
500
- }
501
- }
502
- function stripColor(str) {
503
- const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
504
- return str.replace(sgrPattern, "");
505
- }
506
- exports.Help = Help;
507
- exports.stripColor = stripColor;
508
- });
509
-
510
- // node_modules/commander/lib/option.js
511
- var require_option = __commonJS((exports) => {
512
- var { InvalidArgumentError } = require_error();
513
-
514
- class Option {
515
- constructor(flags, description) {
516
- this.flags = flags;
517
- this.description = description || "";
518
- this.required = flags.includes("<");
519
- this.optional = flags.includes("[");
520
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
521
- this.mandatory = false;
522
- const optionFlags = splitOptionFlags(flags);
523
- this.short = optionFlags.shortFlag;
524
- this.long = optionFlags.longFlag;
525
- this.negate = false;
526
- if (this.long) {
527
- this.negate = this.long.startsWith("--no-");
528
- }
529
- this.defaultValue = undefined;
530
- this.defaultValueDescription = undefined;
531
- this.presetArg = undefined;
532
- this.envVar = undefined;
533
- this.parseArg = undefined;
534
- this.hidden = false;
535
- this.argChoices = undefined;
536
- this.conflictsWith = [];
537
- this.implied = undefined;
538
- this.helpGroupHeading = undefined;
539
- }
540
- default(value, description) {
541
- this.defaultValue = value;
542
- this.defaultValueDescription = description;
543
- return this;
544
- }
545
- preset(arg) {
546
- this.presetArg = arg;
547
- return this;
548
- }
549
- conflicts(names) {
550
- this.conflictsWith = this.conflictsWith.concat(names);
551
- return this;
552
- }
553
- implies(impliedOptionValues) {
554
- let newImplied = impliedOptionValues;
555
- if (typeof impliedOptionValues === "string") {
556
- newImplied = { [impliedOptionValues]: true };
557
- }
558
- this.implied = Object.assign(this.implied || {}, newImplied);
559
- return this;
560
- }
561
- env(name) {
562
- this.envVar = name;
563
- return this;
564
- }
565
- argParser(fn) {
566
- this.parseArg = fn;
567
- return this;
568
- }
569
- makeOptionMandatory(mandatory = true) {
570
- this.mandatory = !!mandatory;
571
- return this;
572
- }
573
- hideHelp(hide = true) {
574
- this.hidden = !!hide;
575
- return this;
576
- }
577
- _concatValue(value, previous) {
578
- if (previous === this.defaultValue || !Array.isArray(previous)) {
579
- return [value];
580
- }
581
- return previous.concat(value);
582
- }
583
- choices(values) {
584
- this.argChoices = values.slice();
585
- this.parseArg = (arg, previous) => {
586
- if (!this.argChoices.includes(arg)) {
587
- throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
588
- }
589
- if (this.variadic) {
590
- return this._concatValue(arg, previous);
591
- }
592
- return arg;
593
- };
594
- return this;
595
- }
596
- name() {
597
- if (this.long) {
598
- return this.long.replace(/^--/, "");
599
- }
600
- return this.short.replace(/^-/, "");
601
- }
602
- attributeName() {
603
- if (this.negate) {
604
- return camelcase(this.name().replace(/^no-/, ""));
605
- }
606
- return camelcase(this.name());
607
- }
608
- helpGroup(heading) {
609
- this.helpGroupHeading = heading;
610
- return this;
611
- }
612
- is(arg) {
613
- return this.short === arg || this.long === arg;
614
- }
615
- isBoolean() {
616
- return !this.required && !this.optional && !this.negate;
617
- }
618
- }
619
-
620
- class DualOptions {
621
- constructor(options) {
622
- this.positiveOptions = new Map;
623
- this.negativeOptions = new Map;
624
- this.dualOptions = new Set;
625
- options.forEach((option) => {
626
- if (option.negate) {
627
- this.negativeOptions.set(option.attributeName(), option);
628
- } else {
629
- this.positiveOptions.set(option.attributeName(), option);
630
- }
631
- });
632
- this.negativeOptions.forEach((value, key) => {
633
- if (this.positiveOptions.has(key)) {
634
- this.dualOptions.add(key);
635
- }
636
- });
637
- }
638
- valueFromOption(value, option) {
639
- const optionKey = option.attributeName();
640
- if (!this.dualOptions.has(optionKey))
641
- return true;
642
- const preset = this.negativeOptions.get(optionKey).presetArg;
643
- const negativeValue = preset !== undefined ? preset : false;
644
- return option.negate === (negativeValue === value);
645
- }
646
- }
647
- function camelcase(str) {
648
- return str.split("-").reduce((str2, word) => {
649
- return str2 + word[0].toUpperCase() + word.slice(1);
650
- });
651
- }
652
- function splitOptionFlags(flags) {
653
- let shortFlag;
654
- let longFlag;
655
- const shortFlagExp = /^-[^-]$/;
656
- const longFlagExp = /^--[^-]/;
657
- const flagParts = flags.split(/[ |,]+/).concat("guard");
658
- if (shortFlagExp.test(flagParts[0]))
659
- shortFlag = flagParts.shift();
660
- if (longFlagExp.test(flagParts[0]))
661
- longFlag = flagParts.shift();
662
- if (!shortFlag && shortFlagExp.test(flagParts[0]))
663
- shortFlag = flagParts.shift();
664
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
665
- shortFlag = longFlag;
666
- longFlag = flagParts.shift();
667
- }
668
- if (flagParts[0].startsWith("-")) {
669
- const unsupportedFlag = flagParts[0];
670
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
671
- if (/^-[^-][^-]/.test(unsupportedFlag))
672
- throw new Error(`${baseError}
673
- - a short flag is a single dash and a single character
674
- - either use a single dash and a single character (for a short flag)
675
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
676
- if (shortFlagExp.test(unsupportedFlag))
677
- throw new Error(`${baseError}
678
- - too many short flags`);
679
- if (longFlagExp.test(unsupportedFlag))
680
- throw new Error(`${baseError}
681
- - too many long flags`);
682
- throw new Error(`${baseError}
683
- - unrecognised flag format`);
684
- }
685
- if (shortFlag === undefined && longFlag === undefined)
686
- throw new Error(`option creation failed due to no flags found in '${flags}'.`);
687
- return { shortFlag, longFlag };
688
- }
689
- exports.Option = Option;
690
- exports.DualOptions = DualOptions;
691
- });
692
-
693
- // node_modules/commander/lib/suggestSimilar.js
694
- var require_suggestSimilar = __commonJS((exports) => {
695
- var maxDistance = 3;
696
- function editDistance(a, b) {
697
- if (Math.abs(a.length - b.length) > maxDistance)
698
- return Math.max(a.length, b.length);
699
- const d = [];
700
- for (let i = 0;i <= a.length; i++) {
701
- d[i] = [i];
702
- }
703
- for (let j = 0;j <= b.length; j++) {
704
- d[0][j] = j;
705
- }
706
- for (let j = 1;j <= b.length; j++) {
707
- for (let i = 1;i <= a.length; i++) {
708
- let cost = 1;
709
- if (a[i - 1] === b[j - 1]) {
710
- cost = 0;
711
- } else {
712
- cost = 1;
713
- }
714
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
715
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
716
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
717
- }
718
- }
719
- }
720
- return d[a.length][b.length];
721
- }
722
- function suggestSimilar(word, candidates) {
723
- if (!candidates || candidates.length === 0)
724
- return "";
725
- candidates = Array.from(new Set(candidates));
726
- const searchingOptions = word.startsWith("--");
727
- if (searchingOptions) {
728
- word = word.slice(2);
729
- candidates = candidates.map((candidate) => candidate.slice(2));
730
- }
731
- let similar = [];
732
- let bestDistance = maxDistance;
733
- const minSimilarity = 0.4;
734
- candidates.forEach((candidate) => {
735
- if (candidate.length <= 1)
736
- return;
737
- const distance = editDistance(word, candidate);
738
- const length = Math.max(word.length, candidate.length);
739
- const similarity = (length - distance) / length;
740
- if (similarity > minSimilarity) {
741
- if (distance < bestDistance) {
742
- bestDistance = distance;
743
- similar = [candidate];
744
- } else if (distance === bestDistance) {
745
- similar.push(candidate);
746
- }
747
- }
748
- });
749
- similar.sort((a, b) => a.localeCompare(b));
750
- if (searchingOptions) {
751
- similar = similar.map((candidate) => `--${candidate}`);
752
- }
753
- if (similar.length > 1) {
754
- return `
755
- (Did you mean one of ${similar.join(", ")}?)`;
756
- }
757
- if (similar.length === 1) {
758
- return `
759
- (Did you mean ${similar[0]}?)`;
760
- }
761
- return "";
762
- }
763
- exports.suggestSimilar = suggestSimilar;
764
- });
765
-
766
- // node_modules/commander/lib/command.js
767
- var require_command = __commonJS((exports) => {
768
- var EventEmitter = __require("node:events").EventEmitter;
769
- var childProcess = __require("node:child_process");
770
- var path = __require("node:path");
771
- var fs = __require("node:fs");
772
- var process2 = __require("node:process");
773
- var { Argument, humanReadableArgName } = require_argument();
774
- var { CommanderError } = require_error();
775
- var { Help, stripColor } = require_help();
776
- var { Option, DualOptions } = require_option();
777
- var { suggestSimilar } = require_suggestSimilar();
20
+ // src/cli/commands.ts
21
+ import * as childProcess2 from "node:child_process";
22
+ import fs3 from "node:fs";
23
+ import path3 from "node:path";
778
24
 
779
- class Command extends EventEmitter {
780
- constructor(name) {
781
- super();
782
- this.commands = [];
783
- this.options = [];
784
- this.parent = null;
785
- this._allowUnknownOption = false;
786
- this._allowExcessArguments = false;
787
- this.registeredArguments = [];
788
- this._args = this.registeredArguments;
789
- this.args = [];
790
- this.rawArgs = [];
791
- this.processedArgs = [];
792
- this._scriptPath = null;
793
- this._name = name || "";
794
- this._optionValues = {};
795
- this._optionValueSources = {};
796
- this._storeOptionsAsProperties = false;
797
- this._actionHandler = null;
798
- this._executableHandler = false;
799
- this._executableFile = null;
800
- this._executableDir = null;
801
- this._defaultCommandName = null;
802
- this._exitCallback = null;
803
- this._aliases = [];
804
- this._combineFlagAndOptionalValue = true;
805
- this._description = "";
806
- this._summary = "";
807
- this._argsDescription = undefined;
808
- this._enablePositionalOptions = false;
809
- this._passThroughOptions = false;
810
- this._lifeCycleHooks = {};
811
- this._showHelpAfterError = false;
812
- this._showSuggestionAfterError = true;
813
- this._savedState = null;
814
- this._outputConfiguration = {
815
- writeOut: (str) => process2.stdout.write(str),
816
- writeErr: (str) => process2.stderr.write(str),
817
- outputError: (str, write) => write(str),
818
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
819
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
820
- getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
821
- getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
822
- stripColor: (str) => stripColor(str)
823
- };
824
- this._hidden = false;
825
- this._helpOption = undefined;
826
- this._addImplicitHelpCommand = undefined;
827
- this._helpCommand = undefined;
828
- this._helpConfiguration = {};
829
- this._helpGroupHeading = undefined;
830
- this._defaultCommandGroup = undefined;
831
- this._defaultOptionGroup = undefined;
832
- }
833
- copyInheritedSettings(sourceCommand) {
834
- this._outputConfiguration = sourceCommand._outputConfiguration;
835
- this._helpOption = sourceCommand._helpOption;
836
- this._helpCommand = sourceCommand._helpCommand;
837
- this._helpConfiguration = sourceCommand._helpConfiguration;
838
- this._exitCallback = sourceCommand._exitCallback;
839
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
840
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
841
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
842
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
843
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
844
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
845
- return this;
846
- }
847
- _getCommandAndAncestors() {
848
- const result = [];
849
- for (let command = this;command; command = command.parent) {
850
- result.push(command);
851
- }
852
- return result;
853
- }
854
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
855
- let desc = actionOptsOrExecDesc;
856
- let opts = execOpts;
857
- if (typeof desc === "object" && desc !== null) {
858
- opts = desc;
859
- desc = null;
860
- }
861
- opts = opts || {};
862
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
863
- const cmd = this.createCommand(name);
864
- if (desc) {
865
- cmd.description(desc);
866
- cmd._executableHandler = true;
867
- }
868
- if (opts.isDefault)
869
- this._defaultCommandName = cmd._name;
870
- cmd._hidden = !!(opts.noHelp || opts.hidden);
871
- cmd._executableFile = opts.executableFile || null;
872
- if (args)
873
- cmd.arguments(args);
874
- this._registerCommand(cmd);
875
- cmd.parent = this;
876
- cmd.copyInheritedSettings(this);
877
- if (desc)
878
- return this;
879
- return cmd;
880
- }
881
- createCommand(name) {
882
- return new Command(name);
883
- }
884
- createHelp() {
885
- return Object.assign(new Help, this.configureHelp());
886
- }
887
- configureHelp(configuration) {
888
- if (configuration === undefined)
889
- return this._helpConfiguration;
890
- this._helpConfiguration = configuration;
891
- return this;
892
- }
893
- configureOutput(configuration) {
894
- if (configuration === undefined)
895
- return this._outputConfiguration;
896
- this._outputConfiguration = Object.assign({}, this._outputConfiguration, configuration);
897
- return this;
898
- }
899
- showHelpAfterError(displayHelp = true) {
900
- if (typeof displayHelp !== "string")
901
- displayHelp = !!displayHelp;
902
- this._showHelpAfterError = displayHelp;
903
- return this;
904
- }
905
- showSuggestionAfterError(displaySuggestion = true) {
906
- this._showSuggestionAfterError = !!displaySuggestion;
907
- return this;
908
- }
909
- addCommand(cmd, opts) {
910
- if (!cmd._name) {
911
- throw new Error(`Command passed to .addCommand() must have a name
912
- - specify the name in Command constructor or using .name()`);
913
- }
914
- opts = opts || {};
915
- if (opts.isDefault)
916
- this._defaultCommandName = cmd._name;
917
- if (opts.noHelp || opts.hidden)
918
- cmd._hidden = true;
919
- this._registerCommand(cmd);
920
- cmd.parent = this;
921
- cmd._checkForBrokenPassThrough();
922
- return this;
923
- }
924
- createArgument(name, description) {
925
- return new Argument(name, description);
926
- }
927
- argument(name, description, parseArg, defaultValue) {
928
- const argument = this.createArgument(name, description);
929
- if (typeof parseArg === "function") {
930
- argument.default(defaultValue).argParser(parseArg);
931
- } else {
932
- argument.default(parseArg);
933
- }
934
- this.addArgument(argument);
935
- return this;
936
- }
937
- arguments(names) {
938
- names.trim().split(/ +/).forEach((detail) => {
939
- this.argument(detail);
940
- });
941
- return this;
942
- }
943
- addArgument(argument) {
944
- const previousArgument = this.registeredArguments.slice(-1)[0];
945
- if (previousArgument && previousArgument.variadic) {
946
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
947
- }
948
- if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
949
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
950
- }
951
- this.registeredArguments.push(argument);
952
- return this;
953
- }
954
- helpCommand(enableOrNameAndArgs, description) {
955
- if (typeof enableOrNameAndArgs === "boolean") {
956
- this._addImplicitHelpCommand = enableOrNameAndArgs;
957
- if (enableOrNameAndArgs && this._defaultCommandGroup) {
958
- this._initCommandGroup(this._getHelpCommand());
959
- }
960
- return this;
961
- }
962
- const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
963
- const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
964
- const helpDescription = description ?? "display help for command";
965
- const helpCommand = this.createCommand(helpName);
966
- helpCommand.helpOption(false);
967
- if (helpArgs)
968
- helpCommand.arguments(helpArgs);
969
- if (helpDescription)
970
- helpCommand.description(helpDescription);
971
- this._addImplicitHelpCommand = true;
972
- this._helpCommand = helpCommand;
973
- if (enableOrNameAndArgs || description)
974
- this._initCommandGroup(helpCommand);
975
- return this;
976
- }
977
- addHelpCommand(helpCommand, deprecatedDescription) {
978
- if (typeof helpCommand !== "object") {
979
- this.helpCommand(helpCommand, deprecatedDescription);
980
- return this;
981
- }
982
- this._addImplicitHelpCommand = true;
983
- this._helpCommand = helpCommand;
984
- this._initCommandGroup(helpCommand);
985
- return this;
986
- }
987
- _getHelpCommand() {
988
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
989
- if (hasImplicitHelpCommand) {
990
- if (this._helpCommand === undefined) {
991
- this.helpCommand(undefined, undefined);
992
- }
993
- return this._helpCommand;
994
- }
995
- return null;
996
- }
997
- hook(event, listener) {
998
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
999
- if (!allowedValues.includes(event)) {
1000
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1001
- Expecting one of '${allowedValues.join("', '")}'`);
1002
- }
1003
- if (this._lifeCycleHooks[event]) {
1004
- this._lifeCycleHooks[event].push(listener);
1005
- } else {
1006
- this._lifeCycleHooks[event] = [listener];
1007
- }
1008
- return this;
1009
- }
1010
- exitOverride(fn) {
1011
- if (fn) {
1012
- this._exitCallback = fn;
1013
- } else {
1014
- this._exitCallback = (err) => {
1015
- if (err.code !== "commander.executeSubCommandAsync") {
1016
- throw err;
1017
- } else {}
1018
- };
1019
- }
1020
- return this;
1021
- }
1022
- _exit(exitCode, code, message) {
1023
- if (this._exitCallback) {
1024
- this._exitCallback(new CommanderError(exitCode, code, message));
1025
- }
1026
- process2.exit(exitCode);
1027
- }
1028
- action(fn) {
1029
- const listener = (args) => {
1030
- const expectedArgsCount = this.registeredArguments.length;
1031
- const actionArgs = args.slice(0, expectedArgsCount);
1032
- if (this._storeOptionsAsProperties) {
1033
- actionArgs[expectedArgsCount] = this;
1034
- } else {
1035
- actionArgs[expectedArgsCount] = this.opts();
1036
- }
1037
- actionArgs.push(this);
1038
- return fn.apply(this, actionArgs);
1039
- };
1040
- this._actionHandler = listener;
1041
- return this;
1042
- }
1043
- createOption(flags, description) {
1044
- return new Option(flags, description);
1045
- }
1046
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1047
- try {
1048
- return target.parseArg(value, previous);
1049
- } catch (err) {
1050
- if (err.code === "commander.invalidArgument") {
1051
- const message = `${invalidArgumentMessage} ${err.message}`;
1052
- this.error(message, { exitCode: err.exitCode, code: err.code });
1053
- }
1054
- throw err;
1055
- }
1056
- }
1057
- _registerOption(option) {
1058
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1059
- if (matchingOption) {
1060
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1061
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1062
- - already used by option '${matchingOption.flags}'`);
1063
- }
1064
- this._initOptionGroup(option);
1065
- this.options.push(option);
1066
- }
1067
- _registerCommand(command) {
1068
- const knownBy = (cmd) => {
1069
- return [cmd.name()].concat(cmd.aliases());
1070
- };
1071
- const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1072
- if (alreadyUsed) {
1073
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1074
- const newCmd = knownBy(command).join("|");
1075
- throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1076
- }
1077
- this._initCommandGroup(command);
1078
- this.commands.push(command);
1079
- }
1080
- addOption(option) {
1081
- this._registerOption(option);
1082
- const oname = option.name();
1083
- const name = option.attributeName();
1084
- if (option.negate) {
1085
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1086
- if (!this._findOption(positiveLongFlag)) {
1087
- this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1088
- }
1089
- } else if (option.defaultValue !== undefined) {
1090
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1091
- }
1092
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1093
- if (val == null && option.presetArg !== undefined) {
1094
- val = option.presetArg;
1095
- }
1096
- const oldValue = this.getOptionValue(name);
1097
- if (val !== null && option.parseArg) {
1098
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1099
- } else if (val !== null && option.variadic) {
1100
- val = option._concatValue(val, oldValue);
1101
- }
1102
- if (val == null) {
1103
- if (option.negate) {
1104
- val = false;
1105
- } else if (option.isBoolean() || option.optional) {
1106
- val = true;
1107
- } else {
1108
- val = "";
1109
- }
1110
- }
1111
- this.setOptionValueWithSource(name, val, valueSource);
1112
- };
1113
- this.on("option:" + oname, (val) => {
1114
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1115
- handleOptionValue(val, invalidValueMessage, "cli");
1116
- });
1117
- if (option.envVar) {
1118
- this.on("optionEnv:" + oname, (val) => {
1119
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1120
- handleOptionValue(val, invalidValueMessage, "env");
1121
- });
1122
- }
1123
- return this;
1124
- }
1125
- _optionEx(config, flags, description, fn, defaultValue) {
1126
- if (typeof flags === "object" && flags instanceof Option) {
1127
- throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1128
- }
1129
- const option = this.createOption(flags, description);
1130
- option.makeOptionMandatory(!!config.mandatory);
1131
- if (typeof fn === "function") {
1132
- option.default(defaultValue).argParser(fn);
1133
- } else if (fn instanceof RegExp) {
1134
- const regex = fn;
1135
- fn = (val, def) => {
1136
- const m = regex.exec(val);
1137
- return m ? m[0] : def;
1138
- };
1139
- option.default(defaultValue).argParser(fn);
1140
- } else {
1141
- option.default(fn);
1142
- }
1143
- return this.addOption(option);
1144
- }
1145
- option(flags, description, parseArg, defaultValue) {
1146
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1147
- }
1148
- requiredOption(flags, description, parseArg, defaultValue) {
1149
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1150
- }
1151
- combineFlagAndOptionalValue(combine = true) {
1152
- this._combineFlagAndOptionalValue = !!combine;
1153
- return this;
1154
- }
1155
- allowUnknownOption(allowUnknown = true) {
1156
- this._allowUnknownOption = !!allowUnknown;
1157
- return this;
1158
- }
1159
- allowExcessArguments(allowExcess = true) {
1160
- this._allowExcessArguments = !!allowExcess;
1161
- return this;
1162
- }
1163
- enablePositionalOptions(positional = true) {
1164
- this._enablePositionalOptions = !!positional;
1165
- return this;
1166
- }
1167
- passThroughOptions(passThrough = true) {
1168
- this._passThroughOptions = !!passThrough;
1169
- this._checkForBrokenPassThrough();
1170
- return this;
1171
- }
1172
- _checkForBrokenPassThrough() {
1173
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1174
- throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1175
- }
1176
- }
1177
- storeOptionsAsProperties(storeAsProperties = true) {
1178
- if (this.options.length) {
1179
- throw new Error("call .storeOptionsAsProperties() before adding options");
1180
- }
1181
- if (Object.keys(this._optionValues).length) {
1182
- throw new Error("call .storeOptionsAsProperties() before setting option values");
1183
- }
1184
- this._storeOptionsAsProperties = !!storeAsProperties;
1185
- return this;
1186
- }
1187
- getOptionValue(key) {
1188
- if (this._storeOptionsAsProperties) {
1189
- return this[key];
1190
- }
1191
- return this._optionValues[key];
1192
- }
1193
- setOptionValue(key, value) {
1194
- return this.setOptionValueWithSource(key, value, undefined);
1195
- }
1196
- setOptionValueWithSource(key, value, source) {
1197
- if (this._storeOptionsAsProperties) {
1198
- this[key] = value;
1199
- } else {
1200
- this._optionValues[key] = value;
1201
- }
1202
- this._optionValueSources[key] = source;
1203
- return this;
1204
- }
1205
- getOptionValueSource(key) {
1206
- return this._optionValueSources[key];
1207
- }
1208
- getOptionValueSourceWithGlobals(key) {
1209
- let source;
1210
- this._getCommandAndAncestors().forEach((cmd) => {
1211
- if (cmd.getOptionValueSource(key) !== undefined) {
1212
- source = cmd.getOptionValueSource(key);
1213
- }
1214
- });
1215
- return source;
1216
- }
1217
- _prepareUserArgs(argv, parseOptions) {
1218
- if (argv !== undefined && !Array.isArray(argv)) {
1219
- throw new Error("first parameter to parse must be array or undefined");
1220
- }
1221
- parseOptions = parseOptions || {};
1222
- if (argv === undefined && parseOptions.from === undefined) {
1223
- if (process2.versions?.electron) {
1224
- parseOptions.from = "electron";
1225
- }
1226
- const execArgv = process2.execArgv ?? [];
1227
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1228
- parseOptions.from = "eval";
1229
- }
1230
- }
1231
- if (argv === undefined) {
1232
- argv = process2.argv;
1233
- }
1234
- this.rawArgs = argv.slice();
1235
- let userArgs;
1236
- switch (parseOptions.from) {
1237
- case undefined:
1238
- case "node":
1239
- this._scriptPath = argv[1];
1240
- userArgs = argv.slice(2);
1241
- break;
1242
- case "electron":
1243
- if (process2.defaultApp) {
1244
- this._scriptPath = argv[1];
1245
- userArgs = argv.slice(2);
1246
- } else {
1247
- userArgs = argv.slice(1);
1248
- }
1249
- break;
1250
- case "user":
1251
- userArgs = argv.slice(0);
1252
- break;
1253
- case "eval":
1254
- userArgs = argv.slice(1);
1255
- break;
1256
- default:
1257
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1258
- }
1259
- if (!this._name && this._scriptPath)
1260
- this.nameFromFilename(this._scriptPath);
1261
- this._name = this._name || "program";
1262
- return userArgs;
1263
- }
1264
- parse(argv, parseOptions) {
1265
- this._prepareForParse();
1266
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1267
- this._parseCommand([], userArgs);
1268
- return this;
1269
- }
1270
- async parseAsync(argv, parseOptions) {
1271
- this._prepareForParse();
1272
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1273
- await this._parseCommand([], userArgs);
1274
- return this;
1275
- }
1276
- _prepareForParse() {
1277
- if (this._savedState === null) {
1278
- this.saveStateBeforeParse();
1279
- } else {
1280
- this.restoreStateBeforeParse();
1281
- }
1282
- }
1283
- saveStateBeforeParse() {
1284
- this._savedState = {
1285
- _name: this._name,
1286
- _optionValues: { ...this._optionValues },
1287
- _optionValueSources: { ...this._optionValueSources }
1288
- };
1289
- }
1290
- restoreStateBeforeParse() {
1291
- if (this._storeOptionsAsProperties)
1292
- throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1293
- - either make a new Command for each call to parse, or stop storing options as properties`);
1294
- this._name = this._savedState._name;
1295
- this._scriptPath = null;
1296
- this.rawArgs = [];
1297
- this._optionValues = { ...this._savedState._optionValues };
1298
- this._optionValueSources = { ...this._savedState._optionValueSources };
1299
- this.args = [];
1300
- this.processedArgs = [];
1301
- }
1302
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1303
- if (fs.existsSync(executableFile))
1304
- return;
1305
- 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";
1306
- const executableMissing = `'${executableFile}' does not exist
1307
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1308
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1309
- - ${executableDirMessage}`;
1310
- throw new Error(executableMissing);
1311
- }
1312
- _executeSubCommand(subcommand, args) {
1313
- args = args.slice();
1314
- let launchWithNode = false;
1315
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1316
- function findFile(baseDir, baseName) {
1317
- const localBin = path.resolve(baseDir, baseName);
1318
- if (fs.existsSync(localBin))
1319
- return localBin;
1320
- if (sourceExt.includes(path.extname(baseName)))
1321
- return;
1322
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1323
- if (foundExt)
1324
- return `${localBin}${foundExt}`;
1325
- return;
1326
- }
1327
- this._checkForMissingMandatoryOptions();
1328
- this._checkForConflictingOptions();
1329
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1330
- let executableDir = this._executableDir || "";
1331
- if (this._scriptPath) {
1332
- let resolvedScriptPath;
1333
- try {
1334
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1335
- } catch {
1336
- resolvedScriptPath = this._scriptPath;
1337
- }
1338
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1339
- }
1340
- if (executableDir) {
1341
- let localFile = findFile(executableDir, executableFile);
1342
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1343
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1344
- if (legacyName !== this._name) {
1345
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1346
- }
1347
- }
1348
- executableFile = localFile || executableFile;
1349
- }
1350
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1351
- let proc;
1352
- if (process2.platform !== "win32") {
1353
- if (launchWithNode) {
1354
- args.unshift(executableFile);
1355
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1356
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1357
- } else {
1358
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1359
- }
1360
- } else {
1361
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1362
- args.unshift(executableFile);
1363
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1364
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1365
- }
1366
- if (!proc.killed) {
1367
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1368
- signals.forEach((signal) => {
1369
- process2.on(signal, () => {
1370
- if (proc.killed === false && proc.exitCode === null) {
1371
- proc.kill(signal);
1372
- }
1373
- });
1374
- });
1375
- }
1376
- const exitCallback = this._exitCallback;
1377
- proc.on("close", (code) => {
1378
- code = code ?? 1;
1379
- if (!exitCallback) {
1380
- process2.exit(code);
1381
- } else {
1382
- exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1383
- }
1384
- });
1385
- proc.on("error", (err) => {
1386
- if (err.code === "ENOENT") {
1387
- this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1388
- } else if (err.code === "EACCES") {
1389
- throw new Error(`'${executableFile}' not executable`);
1390
- }
1391
- if (!exitCallback) {
1392
- process2.exit(1);
1393
- } else {
1394
- const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1395
- wrappedError.nestedError = err;
1396
- exitCallback(wrappedError);
1397
- }
1398
- });
1399
- this.runningCommand = proc;
1400
- }
1401
- _dispatchSubcommand(commandName, operands, unknown) {
1402
- const subCommand = this._findCommand(commandName);
1403
- if (!subCommand)
1404
- this.help({ error: true });
1405
- subCommand._prepareForParse();
1406
- let promiseChain;
1407
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1408
- promiseChain = this._chainOrCall(promiseChain, () => {
1409
- if (subCommand._executableHandler) {
1410
- this._executeSubCommand(subCommand, operands.concat(unknown));
1411
- } else {
1412
- return subCommand._parseCommand(operands, unknown);
1413
- }
1414
- });
1415
- return promiseChain;
1416
- }
1417
- _dispatchHelpCommand(subcommandName) {
1418
- if (!subcommandName) {
1419
- this.help();
1420
- }
1421
- const subCommand = this._findCommand(subcommandName);
1422
- if (subCommand && !subCommand._executableHandler) {
1423
- subCommand.help();
1424
- }
1425
- return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1426
- }
1427
- _checkNumberOfArguments() {
1428
- this.registeredArguments.forEach((arg, i) => {
1429
- if (arg.required && this.args[i] == null) {
1430
- this.missingArgument(arg.name());
1431
- }
1432
- });
1433
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1434
- return;
1435
- }
1436
- if (this.args.length > this.registeredArguments.length) {
1437
- this._excessArguments(this.args);
1438
- }
1439
- }
1440
- _processArguments() {
1441
- const myParseArg = (argument, value, previous) => {
1442
- let parsedValue = value;
1443
- if (value !== null && argument.parseArg) {
1444
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1445
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1446
- }
1447
- return parsedValue;
1448
- };
1449
- this._checkNumberOfArguments();
1450
- const processedArgs = [];
1451
- this.registeredArguments.forEach((declaredArg, index) => {
1452
- let value = declaredArg.defaultValue;
1453
- if (declaredArg.variadic) {
1454
- if (index < this.args.length) {
1455
- value = this.args.slice(index);
1456
- if (declaredArg.parseArg) {
1457
- value = value.reduce((processed, v) => {
1458
- return myParseArg(declaredArg, v, processed);
1459
- }, declaredArg.defaultValue);
1460
- }
1461
- } else if (value === undefined) {
1462
- value = [];
1463
- }
1464
- } else if (index < this.args.length) {
1465
- value = this.args[index];
1466
- if (declaredArg.parseArg) {
1467
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1468
- }
1469
- }
1470
- processedArgs[index] = value;
1471
- });
1472
- this.processedArgs = processedArgs;
1473
- }
1474
- _chainOrCall(promise, fn) {
1475
- if (promise && promise.then && typeof promise.then === "function") {
1476
- return promise.then(() => fn());
1477
- }
1478
- return fn();
1479
- }
1480
- _chainOrCallHooks(promise, event) {
1481
- let result = promise;
1482
- const hooks = [];
1483
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1484
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1485
- hooks.push({ hookedCommand, callback });
1486
- });
1487
- });
1488
- if (event === "postAction") {
1489
- hooks.reverse();
1490
- }
1491
- hooks.forEach((hookDetail) => {
1492
- result = this._chainOrCall(result, () => {
1493
- return hookDetail.callback(hookDetail.hookedCommand, this);
1494
- });
1495
- });
1496
- return result;
1497
- }
1498
- _chainOrCallSubCommandHook(promise, subCommand, event) {
1499
- let result = promise;
1500
- if (this._lifeCycleHooks[event] !== undefined) {
1501
- this._lifeCycleHooks[event].forEach((hook) => {
1502
- result = this._chainOrCall(result, () => {
1503
- return hook(this, subCommand);
1504
- });
1505
- });
1506
- }
1507
- return result;
1508
- }
1509
- _parseCommand(operands, unknown) {
1510
- const parsed = this.parseOptions(unknown);
1511
- this._parseOptionsEnv();
1512
- this._parseOptionsImplied();
1513
- operands = operands.concat(parsed.operands);
1514
- unknown = parsed.unknown;
1515
- this.args = operands.concat(unknown);
1516
- if (operands && this._findCommand(operands[0])) {
1517
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1518
- }
1519
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1520
- return this._dispatchHelpCommand(operands[1]);
1521
- }
1522
- if (this._defaultCommandName) {
1523
- this._outputHelpIfRequested(unknown);
1524
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1525
- }
1526
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1527
- this.help({ error: true });
1528
- }
1529
- this._outputHelpIfRequested(parsed.unknown);
1530
- this._checkForMissingMandatoryOptions();
1531
- this._checkForConflictingOptions();
1532
- const checkForUnknownOptions = () => {
1533
- if (parsed.unknown.length > 0) {
1534
- this.unknownOption(parsed.unknown[0]);
1535
- }
1536
- };
1537
- const commandEvent = `command:${this.name()}`;
1538
- if (this._actionHandler) {
1539
- checkForUnknownOptions();
1540
- this._processArguments();
1541
- let promiseChain;
1542
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1543
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1544
- if (this.parent) {
1545
- promiseChain = this._chainOrCall(promiseChain, () => {
1546
- this.parent.emit(commandEvent, operands, unknown);
1547
- });
1548
- }
1549
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1550
- return promiseChain;
1551
- }
1552
- if (this.parent && this.parent.listenerCount(commandEvent)) {
1553
- checkForUnknownOptions();
1554
- this._processArguments();
1555
- this.parent.emit(commandEvent, operands, unknown);
1556
- } else if (operands.length) {
1557
- if (this._findCommand("*")) {
1558
- return this._dispatchSubcommand("*", operands, unknown);
1559
- }
1560
- if (this.listenerCount("command:*")) {
1561
- this.emit("command:*", operands, unknown);
1562
- } else if (this.commands.length) {
1563
- this.unknownCommand();
1564
- } else {
1565
- checkForUnknownOptions();
1566
- this._processArguments();
1567
- }
1568
- } else if (this.commands.length) {
1569
- checkForUnknownOptions();
1570
- this.help({ error: true });
1571
- } else {
1572
- checkForUnknownOptions();
1573
- this._processArguments();
1574
- }
1575
- }
1576
- _findCommand(name) {
1577
- if (!name)
1578
- return;
1579
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1580
- }
1581
- _findOption(arg) {
1582
- return this.options.find((option) => option.is(arg));
1583
- }
1584
- _checkForMissingMandatoryOptions() {
1585
- this._getCommandAndAncestors().forEach((cmd) => {
1586
- cmd.options.forEach((anOption) => {
1587
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1588
- cmd.missingMandatoryOptionValue(anOption);
1589
- }
1590
- });
1591
- });
1592
- }
1593
- _checkForConflictingLocalOptions() {
1594
- const definedNonDefaultOptions = this.options.filter((option) => {
1595
- const optionKey = option.attributeName();
1596
- if (this.getOptionValue(optionKey) === undefined) {
1597
- return false;
1598
- }
1599
- return this.getOptionValueSource(optionKey) !== "default";
1600
- });
1601
- const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1602
- optionsWithConflicting.forEach((option) => {
1603
- const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1604
- if (conflictingAndDefined) {
1605
- this._conflictingOption(option, conflictingAndDefined);
1606
- }
1607
- });
1608
- }
1609
- _checkForConflictingOptions() {
1610
- this._getCommandAndAncestors().forEach((cmd) => {
1611
- cmd._checkForConflictingLocalOptions();
1612
- });
1613
- }
1614
- parseOptions(argv) {
1615
- const operands = [];
1616
- const unknown = [];
1617
- let dest = operands;
1618
- const args = argv.slice();
1619
- function maybeOption(arg) {
1620
- return arg.length > 1 && arg[0] === "-";
1621
- }
1622
- const negativeNumberArg = (arg) => {
1623
- if (!/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg))
1624
- return false;
1625
- return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1626
- };
1627
- let activeVariadicOption = null;
1628
- while (args.length) {
1629
- const arg = args.shift();
1630
- if (arg === "--") {
1631
- if (dest === unknown)
1632
- dest.push(arg);
1633
- dest.push(...args);
1634
- break;
1635
- }
1636
- if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1637
- this.emit(`option:${activeVariadicOption.name()}`, arg);
1638
- continue;
1639
- }
1640
- activeVariadicOption = null;
1641
- if (maybeOption(arg)) {
1642
- const option = this._findOption(arg);
1643
- if (option) {
1644
- if (option.required) {
1645
- const value = args.shift();
1646
- if (value === undefined)
1647
- this.optionMissingArgument(option);
1648
- this.emit(`option:${option.name()}`, value);
1649
- } else if (option.optional) {
1650
- let value = null;
1651
- if (args.length > 0 && (!maybeOption(args[0]) || negativeNumberArg(args[0]))) {
1652
- value = args.shift();
1653
- }
1654
- this.emit(`option:${option.name()}`, value);
1655
- } else {
1656
- this.emit(`option:${option.name()}`);
1657
- }
1658
- activeVariadicOption = option.variadic ? option : null;
1659
- continue;
1660
- }
1661
- }
1662
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1663
- const option = this._findOption(`-${arg[1]}`);
1664
- if (option) {
1665
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1666
- this.emit(`option:${option.name()}`, arg.slice(2));
1667
- } else {
1668
- this.emit(`option:${option.name()}`);
1669
- args.unshift(`-${arg.slice(2)}`);
1670
- }
1671
- continue;
1672
- }
1673
- }
1674
- if (/^--[^=]+=/.test(arg)) {
1675
- const index = arg.indexOf("=");
1676
- const option = this._findOption(arg.slice(0, index));
1677
- if (option && (option.required || option.optional)) {
1678
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
1679
- continue;
1680
- }
1681
- }
1682
- if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1683
- dest = unknown;
1684
- }
1685
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1686
- if (this._findCommand(arg)) {
1687
- operands.push(arg);
1688
- if (args.length > 0)
1689
- unknown.push(...args);
1690
- break;
1691
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1692
- operands.push(arg);
1693
- if (args.length > 0)
1694
- operands.push(...args);
1695
- break;
1696
- } else if (this._defaultCommandName) {
1697
- unknown.push(arg);
1698
- if (args.length > 0)
1699
- unknown.push(...args);
1700
- break;
1701
- }
1702
- }
1703
- if (this._passThroughOptions) {
1704
- dest.push(arg);
1705
- if (args.length > 0)
1706
- dest.push(...args);
1707
- break;
1708
- }
1709
- dest.push(arg);
1710
- }
1711
- return { operands, unknown };
1712
- }
1713
- opts() {
1714
- if (this._storeOptionsAsProperties) {
1715
- const result = {};
1716
- const len = this.options.length;
1717
- for (let i = 0;i < len; i++) {
1718
- const key = this.options[i].attributeName();
1719
- result[key] = key === this._versionOptionName ? this._version : this[key];
1720
- }
1721
- return result;
1722
- }
1723
- return this._optionValues;
1724
- }
1725
- optsWithGlobals() {
1726
- return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1727
- }
1728
- error(message, errorOptions) {
1729
- this._outputConfiguration.outputError(`${message}
1730
- `, this._outputConfiguration.writeErr);
1731
- if (typeof this._showHelpAfterError === "string") {
1732
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1733
- `);
1734
- } else if (this._showHelpAfterError) {
1735
- this._outputConfiguration.writeErr(`
1736
- `);
1737
- this.outputHelp({ error: true });
1738
- }
1739
- const config = errorOptions || {};
1740
- const exitCode = config.exitCode || 1;
1741
- const code = config.code || "commander.error";
1742
- this._exit(exitCode, code, message);
1743
- }
1744
- _parseOptionsEnv() {
1745
- this.options.forEach((option) => {
1746
- if (option.envVar && option.envVar in process2.env) {
1747
- const optionKey = option.attributeName();
1748
- if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1749
- if (option.required || option.optional) {
1750
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1751
- } else {
1752
- this.emit(`optionEnv:${option.name()}`);
1753
- }
1754
- }
1755
- }
1756
- });
1757
- }
1758
- _parseOptionsImplied() {
1759
- const dualHelper = new DualOptions(this.options);
1760
- const hasCustomOptionValue = (optionKey) => {
1761
- return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1762
- };
1763
- this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1764
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1765
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1766
- });
1767
- });
1768
- }
1769
- missingArgument(name) {
1770
- const message = `error: missing required argument '${name}'`;
1771
- this.error(message, { code: "commander.missingArgument" });
1772
- }
1773
- optionMissingArgument(option) {
1774
- const message = `error: option '${option.flags}' argument missing`;
1775
- this.error(message, { code: "commander.optionMissingArgument" });
1776
- }
1777
- missingMandatoryOptionValue(option) {
1778
- const message = `error: required option '${option.flags}' not specified`;
1779
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
1780
- }
1781
- _conflictingOption(option, conflictingOption) {
1782
- const findBestOptionFromValue = (option2) => {
1783
- const optionKey = option2.attributeName();
1784
- const optionValue = this.getOptionValue(optionKey);
1785
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1786
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1787
- if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1788
- return negativeOption;
1789
- }
1790
- return positiveOption || option2;
1791
- };
1792
- const getErrorMessage = (option2) => {
1793
- const bestOption = findBestOptionFromValue(option2);
1794
- const optionKey = bestOption.attributeName();
1795
- const source = this.getOptionValueSource(optionKey);
1796
- if (source === "env") {
1797
- return `environment variable '${bestOption.envVar}'`;
1798
- }
1799
- return `option '${bestOption.flags}'`;
1800
- };
1801
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1802
- this.error(message, { code: "commander.conflictingOption" });
1803
- }
1804
- unknownOption(flag) {
1805
- if (this._allowUnknownOption)
1806
- return;
1807
- let suggestion = "";
1808
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
1809
- let candidateFlags = [];
1810
- let command = this;
1811
- do {
1812
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1813
- candidateFlags = candidateFlags.concat(moreFlags);
1814
- command = command.parent;
1815
- } while (command && !command._enablePositionalOptions);
1816
- suggestion = suggestSimilar(flag, candidateFlags);
1817
- }
1818
- const message = `error: unknown option '${flag}'${suggestion}`;
1819
- this.error(message, { code: "commander.unknownOption" });
1820
- }
1821
- _excessArguments(receivedArgs) {
1822
- if (this._allowExcessArguments)
1823
- return;
1824
- const expected = this.registeredArguments.length;
1825
- const s = expected === 1 ? "" : "s";
1826
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1827
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1828
- this.error(message, { code: "commander.excessArguments" });
1829
- }
1830
- unknownCommand() {
1831
- const unknownName = this.args[0];
1832
- let suggestion = "";
1833
- if (this._showSuggestionAfterError) {
1834
- const candidateNames = [];
1835
- this.createHelp().visibleCommands(this).forEach((command) => {
1836
- candidateNames.push(command.name());
1837
- if (command.alias())
1838
- candidateNames.push(command.alias());
1839
- });
1840
- suggestion = suggestSimilar(unknownName, candidateNames);
1841
- }
1842
- const message = `error: unknown command '${unknownName}'${suggestion}`;
1843
- this.error(message, { code: "commander.unknownCommand" });
1844
- }
1845
- version(str, flags, description) {
1846
- if (str === undefined)
1847
- return this._version;
1848
- this._version = str;
1849
- flags = flags || "-V, --version";
1850
- description = description || "output the version number";
1851
- const versionOption = this.createOption(flags, description);
1852
- this._versionOptionName = versionOption.attributeName();
1853
- this._registerOption(versionOption);
1854
- this.on("option:" + versionOption.name(), () => {
1855
- this._outputConfiguration.writeOut(`${str}
1856
- `);
1857
- this._exit(0, "commander.version", str);
1858
- });
1859
- return this;
1860
- }
1861
- description(str, argsDescription) {
1862
- if (str === undefined && argsDescription === undefined)
1863
- return this._description;
1864
- this._description = str;
1865
- if (argsDescription) {
1866
- this._argsDescription = argsDescription;
1867
- }
1868
- return this;
1869
- }
1870
- summary(str) {
1871
- if (str === undefined)
1872
- return this._summary;
1873
- this._summary = str;
1874
- return this;
1875
- }
1876
- alias(alias) {
1877
- if (alias === undefined)
1878
- return this._aliases[0];
1879
- let command = this;
1880
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1881
- command = this.commands[this.commands.length - 1];
1882
- }
1883
- if (alias === command._name)
1884
- throw new Error("Command alias can't be the same as its name");
1885
- const matchingCommand = this.parent?._findCommand(alias);
1886
- if (matchingCommand) {
1887
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1888
- throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1889
- }
1890
- command._aliases.push(alias);
1891
- return this;
1892
- }
1893
- aliases(aliases) {
1894
- if (aliases === undefined)
1895
- return this._aliases;
1896
- aliases.forEach((alias) => this.alias(alias));
1897
- return this;
1898
- }
1899
- usage(str) {
1900
- if (str === undefined) {
1901
- if (this._usage)
1902
- return this._usage;
1903
- const args = this.registeredArguments.map((arg) => {
1904
- return humanReadableArgName(arg);
1905
- });
1906
- return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1907
- }
1908
- this._usage = str;
1909
- return this;
1910
- }
1911
- name(str) {
1912
- if (str === undefined)
1913
- return this._name;
1914
- this._name = str;
1915
- return this;
1916
- }
1917
- helpGroup(heading) {
1918
- if (heading === undefined)
1919
- return this._helpGroupHeading ?? "";
1920
- this._helpGroupHeading = heading;
1921
- return this;
1922
- }
1923
- commandsGroup(heading) {
1924
- if (heading === undefined)
1925
- return this._defaultCommandGroup ?? "";
1926
- this._defaultCommandGroup = heading;
1927
- return this;
1928
- }
1929
- optionsGroup(heading) {
1930
- if (heading === undefined)
1931
- return this._defaultOptionGroup ?? "";
1932
- this._defaultOptionGroup = heading;
1933
- return this;
1934
- }
1935
- _initOptionGroup(option) {
1936
- if (this._defaultOptionGroup && !option.helpGroupHeading)
1937
- option.helpGroup(this._defaultOptionGroup);
1938
- }
1939
- _initCommandGroup(cmd) {
1940
- if (this._defaultCommandGroup && !cmd.helpGroup())
1941
- cmd.helpGroup(this._defaultCommandGroup);
1942
- }
1943
- nameFromFilename(filename) {
1944
- this._name = path.basename(filename, path.extname(filename));
1945
- return this;
1946
- }
1947
- executableDir(path2) {
1948
- if (path2 === undefined)
1949
- return this._executableDir;
1950
- this._executableDir = path2;
1951
- return this;
1952
- }
1953
- helpInformation(contextOptions) {
1954
- const helper = this.createHelp();
1955
- const context = this._getOutputContext(contextOptions);
1956
- helper.prepareContext({
1957
- error: context.error,
1958
- helpWidth: context.helpWidth,
1959
- outputHasColors: context.hasColors
1960
- });
1961
- const text = helper.formatHelp(this, helper);
1962
- if (context.hasColors)
1963
- return text;
1964
- return this._outputConfiguration.stripColor(text);
1965
- }
1966
- _getOutputContext(contextOptions) {
1967
- contextOptions = contextOptions || {};
1968
- const error = !!contextOptions.error;
1969
- let baseWrite;
1970
- let hasColors;
1971
- let helpWidth;
1972
- if (error) {
1973
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
1974
- hasColors = this._outputConfiguration.getErrHasColors();
1975
- helpWidth = this._outputConfiguration.getErrHelpWidth();
1976
- } else {
1977
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
1978
- hasColors = this._outputConfiguration.getOutHasColors();
1979
- helpWidth = this._outputConfiguration.getOutHelpWidth();
1980
- }
1981
- const write = (str) => {
1982
- if (!hasColors)
1983
- str = this._outputConfiguration.stripColor(str);
1984
- return baseWrite(str);
1985
- };
1986
- return { error, write, hasColors, helpWidth };
1987
- }
1988
- outputHelp(contextOptions) {
1989
- let deprecatedCallback;
1990
- if (typeof contextOptions === "function") {
1991
- deprecatedCallback = contextOptions;
1992
- contextOptions = undefined;
1993
- }
1994
- const outputContext = this._getOutputContext(contextOptions);
1995
- const eventContext = {
1996
- error: outputContext.error,
1997
- write: outputContext.write,
1998
- command: this
1999
- };
2000
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2001
- this.emit("beforeHelp", eventContext);
2002
- let helpInformation = this.helpInformation({ error: outputContext.error });
2003
- if (deprecatedCallback) {
2004
- helpInformation = deprecatedCallback(helpInformation);
2005
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2006
- throw new Error("outputHelp callback must return a string or a Buffer");
2007
- }
2008
- }
2009
- outputContext.write(helpInformation);
2010
- if (this._getHelpOption()?.long) {
2011
- this.emit(this._getHelpOption().long);
2012
- }
2013
- this.emit("afterHelp", eventContext);
2014
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2015
- }
2016
- helpOption(flags, description) {
2017
- if (typeof flags === "boolean") {
2018
- if (flags) {
2019
- if (this._helpOption === null)
2020
- this._helpOption = undefined;
2021
- if (this._defaultOptionGroup) {
2022
- this._initOptionGroup(this._getHelpOption());
2023
- }
2024
- } else {
2025
- this._helpOption = null;
2026
- }
2027
- return this;
2028
- }
2029
- this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2030
- if (flags || description)
2031
- this._initOptionGroup(this._helpOption);
2032
- return this;
2033
- }
2034
- _getHelpOption() {
2035
- if (this._helpOption === undefined) {
2036
- this.helpOption(undefined, undefined);
2037
- }
2038
- return this._helpOption;
2039
- }
2040
- addHelpOption(option) {
2041
- this._helpOption = option;
2042
- this._initOptionGroup(option);
2043
- return this;
2044
- }
2045
- help(contextOptions) {
2046
- this.outputHelp(contextOptions);
2047
- let exitCode = Number(process2.exitCode ?? 0);
2048
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2049
- exitCode = 1;
2050
- }
2051
- this._exit(exitCode, "commander.help", "(outputHelp)");
2052
- }
2053
- addHelpText(position, text) {
2054
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2055
- if (!allowedValues.includes(position)) {
2056
- throw new Error(`Unexpected value for position to addHelpText.
2057
- Expecting one of '${allowedValues.join("', '")}'`);
2058
- }
2059
- const helpEvent = `${position}Help`;
2060
- this.on(helpEvent, (context) => {
2061
- let helpStr;
2062
- if (typeof text === "function") {
2063
- helpStr = text({ error: context.error, command: context.command });
2064
- } else {
2065
- helpStr = text;
2066
- }
2067
- if (helpStr) {
2068
- context.write(`${helpStr}
2069
- `);
2070
- }
2071
- });
2072
- return this;
2073
- }
2074
- _outputHelpIfRequested(args) {
2075
- const helpOption = this._getHelpOption();
2076
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2077
- if (helpRequested) {
2078
- this.outputHelp();
2079
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2080
- }
25
+ // src/config.ts
26
+ import fs from "node:fs";
27
+ import os from "node:os";
28
+ import path from "node:path";
29
+ function configDir() {
30
+ return path.join(process.env.HOME ?? os.homedir(), ".config", "webtty");
31
+ }
32
+ function getConfigPath() {
33
+ return path.join(configDir(), "config.json");
34
+ }
35
+ var DEFAULT_THEME = {
36
+ background: "#000000",
37
+ foreground: "#CCCCCC",
38
+ cursor: "#FFFFFF",
39
+ selection: "#FFFFFF",
40
+ black: "#0C0C0C",
41
+ red: "#C50F1F",
42
+ green: "#13A10E",
43
+ yellow: "#C19C00",
44
+ blue: "#0037DA",
45
+ purple: "#881798",
46
+ cyan: "#3A96DD",
47
+ white: "#CCCCCC",
48
+ brightBlack: "#767676",
49
+ brightRed: "#E74856",
50
+ brightGreen: "#16C60C",
51
+ brightYellow: "#F9F1A5",
52
+ brightBlue: "#3B78FF",
53
+ brightPurple: "#B4009E",
54
+ brightCyan: "#61D6D6",
55
+ brightWhite: "#F2F2F2"
56
+ };
57
+ var DEFAULT_CONFIG = {
58
+ port: 2346,
59
+ host: "127.0.0.1",
60
+ shell: process.platform === "win32" ? process.env.COMSPEC ?? "cmd.exe" : process.env.SHELL ?? "/bin/bash",
61
+ term: process.env.TERM ?? "xterm-256color",
62
+ colorTerm: "truecolor",
63
+ scrollback: 256 * 1024,
64
+ cols: 80,
65
+ rows: 24,
66
+ fontSize: 13,
67
+ fontFamily: "Menlo, Consolas, 'DejaVu Sans Mono', monospace",
68
+ cursorStyle: "bar",
69
+ cursorStyleBlink: true,
70
+ copyOnSelect: true,
71
+ rightClickBehavior: "default",
72
+ logs: false,
73
+ theme: DEFAULT_THEME
74
+ };
75
+ function loadConfig() {
76
+ if (!fs.existsSync(getConfigPath())) {
77
+ try {
78
+ saveConfig(DEFAULT_CONFIG);
79
+ } catch (err) {
80
+ console.warn(`webtty: failed to write default config to ${getConfigPath()}: ${err.message}`);
81
+ return { ...DEFAULT_CONFIG };
2081
82
  }
2082
83
  }
2083
- function incrementNodeInspectorPort(args) {
2084
- return args.map((arg) => {
2085
- if (!arg.startsWith("--inspect")) {
2086
- return arg;
2087
- }
2088
- let debugOption;
2089
- let debugHost = "127.0.0.1";
2090
- let debugPort = "9229";
2091
- let match;
2092
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2093
- debugOption = match[1];
2094
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2095
- debugOption = match[1];
2096
- if (/^\d+$/.test(match[3])) {
2097
- debugPort = match[3];
2098
- } else {
2099
- debugHost = match[3];
2100
- }
2101
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2102
- debugOption = match[1];
2103
- debugHost = match[3];
2104
- debugPort = match[4];
2105
- }
2106
- if (debugOption && debugPort !== "0") {
2107
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2108
- }
2109
- return arg;
2110
- });
84
+ let raw;
85
+ try {
86
+ raw = fs.readFileSync(getConfigPath(), "utf8");
87
+ } catch (err) {
88
+ throw new Error(`webtty: failed to read config at ${getConfigPath()}: ${err.message}`);
2111
89
  }
2112
- function useColor() {
2113
- if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2114
- return false;
2115
- if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2116
- return true;
2117
- return;
90
+ let parsed;
91
+ try {
92
+ parsed = JSON.parse(raw);
93
+ } catch {
94
+ throw new Error(`webtty: invalid JSON in config file ${getConfigPath()}`);
2118
95
  }
2119
- exports.Command = Command;
2120
- exports.useColor = useColor;
2121
- });
2122
-
2123
- // node_modules/commander/index.js
2124
- var require_commander = __commonJS((exports) => {
2125
- var { Argument } = require_argument();
2126
- var { Command } = require_command();
2127
- var { CommanderError, InvalidArgumentError } = require_error();
2128
- var { Help } = require_help();
2129
- var { Option } = require_option();
2130
- exports.program = new Command;
2131
- exports.createCommand = (name) => new Command(name);
2132
- exports.createOption = (flags, description) => new Option(flags, description);
2133
- exports.createArgument = (name, description) => new Argument(name, description);
2134
- exports.Command = Command;
2135
- exports.Option = Option;
2136
- exports.Argument = Argument;
2137
- exports.Help = Help;
2138
- exports.CommanderError = CommanderError;
2139
- exports.InvalidArgumentError = InvalidArgumentError;
2140
- exports.InvalidOptionArgumentError = InvalidArgumentError;
2141
- });
2142
-
2143
- // node_modules/commander/esm.mjs
2144
- var import__ = __toESM(require_commander(), 1);
2145
- var {
2146
- program,
2147
- createCommand,
2148
- createArgument,
2149
- createOption,
2150
- CommanderError,
2151
- InvalidArgumentError,
2152
- InvalidOptionArgumentError,
2153
- Command,
2154
- Argument,
2155
- Option,
2156
- Help
2157
- } = import__.default;
96
+ const p = parsed;
97
+ return {
98
+ ...DEFAULT_CONFIG,
99
+ ...typeof p.port === "number" && { port: p.port },
100
+ ...typeof p.host === "string" && { host: p.host },
101
+ ...typeof p.shell === "string" && { shell: p.shell },
102
+ ...typeof p.term === "string" && { term: p.term },
103
+ ...typeof p.colorTerm === "string" && { colorTerm: p.colorTerm },
104
+ ...typeof p.scrollback === "number" && { scrollback: p.scrollback },
105
+ ...typeof p.cols === "number" && { cols: p.cols },
106
+ ...typeof p.rows === "number" && { rows: p.rows },
107
+ ...typeof p.fontSize === "number" && { fontSize: p.fontSize },
108
+ ...typeof p.fontFamily === "string" && { fontFamily: p.fontFamily },
109
+ ...typeof p.cursorStyle === "string" && (p.cursorStyle === "block" || p.cursorStyle === "bar" || p.cursorStyle === "underline") && {
110
+ cursorStyle: p.cursorStyle
111
+ },
112
+ ...typeof p.cursorStyleBlink === "boolean" && { cursorStyleBlink: p.cursorStyleBlink },
113
+ ...typeof p.copyOnSelect === "boolean" && { copyOnSelect: p.copyOnSelect },
114
+ ...typeof p.rightClickBehavior === "string" && {
115
+ rightClickBehavior: p.rightClickBehavior === "copyPaste" ? "copyPaste" : "default"
116
+ },
117
+ ...typeof p.logs === "boolean" && { logs: p.logs },
118
+ ...p.theme && typeof p.theme === "object" && { theme: { ...DEFAULT_THEME, ...p.theme } }
119
+ };
120
+ }
121
+ function saveConfig(_config) {
122
+ fs.mkdirSync(path.dirname(getConfigPath()), { recursive: true });
123
+ const content = JSON.stringify({
124
+ port: DEFAULT_CONFIG.port,
125
+ host: DEFAULT_CONFIG.host
126
+ }, null, 2);
127
+ fs.writeFileSync(getConfigPath(), content, "utf8");
128
+ }
2158
129
 
2159
130
  // src/cli/http.ts
2160
131
  import * as childProcess from "node:child_process";
2161
- import fs from "node:fs";
2162
- import path from "node:path";
132
+ import fs2 from "node:fs";
133
+ import path2 from "node:path";
2163
134
  import { fileURLToPath } from "node:url";
2164
135
  var __filename2 = fileURLToPath(import.meta.url);
2165
- var __dirname2 = path.dirname(__filename2);
136
+ var __dirname2 = path2.dirname(__filename2);
2166
137
  var PORT = Number(process.env.PORT) || 2346;
2167
138
  var BASE_URL = `http://127.0.0.1:${PORT}`;
139
+ function logPath() {
140
+ return path2.join(configDir(), "server.log");
141
+ }
2168
142
  async function isServerRunning() {
2169
143
  try {
2170
- await fetch(`${BASE_URL}/api/sessions`);
2171
- return true;
144
+ const res = await fetch(`${BASE_URL}/api/sessions`);
145
+ if (!res.ok)
146
+ return false;
147
+ const body = await res.json();
148
+ return Array.isArray(body);
2172
149
  } catch {
2173
150
  return false;
2174
151
  }
@@ -2176,17 +153,28 @@ async function isServerRunning() {
2176
153
  async function startServer(timeoutMs = 1e4, _spawn = childProcess.spawn) {
2177
154
  const isBun = typeof globalThis.Bun !== "undefined";
2178
155
  const isTs = isBun && __filename2.endsWith(".ts");
2179
- const serverEntry = path.resolve(__dirname2, isTs ? "../server/index.ts" : "../server/index.js");
2180
- if (!fs.existsSync(serverEntry)) {
156
+ const serverEntry = path2.resolve(__dirname2, isTs ? "../server/index.ts" : "../server/index.js");
157
+ if (!fs2.existsSync(serverEntry)) {
2181
158
  console.error(`webtty: server entry not found at ${serverEntry}`);
2182
159
  process.exit(1);
2183
160
  }
161
+ const config = loadConfig();
162
+ let stdio = "ignore";
163
+ let logFd;
164
+ if (config.logs) {
165
+ const log = logPath();
166
+ fs2.mkdirSync(path2.dirname(log), { recursive: true });
167
+ logFd = fs2.openSync(log, "a");
168
+ stdio = ["ignore", logFd, logFd];
169
+ }
2184
170
  const child = _spawn(process.execPath, [serverEntry], {
2185
171
  detached: true,
2186
- stdio: "ignore",
172
+ stdio,
2187
173
  env: { ...process.env, PORT: String(PORT) }
2188
174
  });
2189
175
  child.unref();
176
+ if (logFd !== undefined)
177
+ fs2.closeSync(logFd);
2190
178
  const deadline = Date.now() + timeoutMs;
2191
179
  while (Date.now() < deadline) {
2192
180
  if (await isServerRunning())
@@ -2226,148 +214,204 @@ function openBrowser(url, _spawn = childProcess.spawn) {
2226
214
  }
2227
215
 
2228
216
  // src/cli/commands.ts
2229
- function registerCommands(program2) {
2230
- program2.command("start").description("Start the webtty server").action(async () => {
2231
- if (await isServerRunning()) {
2232
- console.log("webtty is already running");
2233
- return;
2234
- }
217
+ async function cmdGo(id = "main") {
218
+ if (!await isServerRunning()) {
2235
219
  await startServer();
2236
- console.log("webtty started");
2237
- });
2238
- program2.command("stop").description("Stop the webtty server").action(async () => {
2239
- if (!await isServerRunning()) {
2240
- console.log("webtty is not running");
2241
- return;
2242
- }
2243
- const ok = await stopServer();
2244
- if (ok) {
2245
- console.log("webtty stopped");
2246
- } else {
2247
- console.error("webtty stop failed");
2248
- process.exit(1);
2249
- }
2250
- });
2251
- program2.command("ls").description("List all sessions").action(async () => {
2252
- let res;
2253
- try {
2254
- res = await fetch(`${BASE_URL}/api/sessions`);
2255
- } catch {
2256
- console.log("webtty is not running");
2257
- process.exit(1);
2258
- }
2259
- const sessions = await res.json();
2260
- if (sessions.length === 0) {
2261
- console.log("no sessions");
2262
- return;
2263
- }
2264
- console.log("id\t\t\tconnected\tcreated");
2265
- for (const s of sessions) {
2266
- const created = new Date(s.createdAt).toLocaleString();
2267
- console.log(`${s.id} ${s.connected} ${created}`);
2268
- }
2269
- });
2270
- program2.command("run [id]").description("Create or reuse a session and open it in the browser").action(async (id) => {
2271
- if (!await isServerRunning()) {
2272
- await startServer();
2273
- }
2274
- let sessionId;
2275
- if (id) {
2276
- const check = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`);
2277
- if (check.status === 200) {
2278
- sessionId = id;
2279
- } else {
2280
- const res = await fetch(`${BASE_URL}/api/sessions`, {
2281
- method: "POST",
2282
- headers: { "Content-Type": "application/json" },
2283
- body: JSON.stringify({ id })
2284
- });
2285
- if (!res.ok) {
2286
- const body = await res.json();
2287
- console.error(`webtty: ${body.error ?? `failed to create session (${res.status})`}`);
2288
- process.exit(1);
2289
- }
2290
- const session = await res.json();
2291
- sessionId = session.id;
2292
- }
2293
- } else {
2294
- const res = await fetch(`${BASE_URL}/api/sessions`, {
2295
- method: "POST",
2296
- headers: { "Content-Type": "application/json" },
2297
- body: "{}"
2298
- });
2299
- if (!res.ok) {
2300
- const body = await res.json();
2301
- console.error(`webtty: ${body.error ?? `failed to create session (${res.status})`}`);
2302
- process.exit(1);
2303
- }
2304
- const session = await res.json();
2305
- sessionId = session.id;
2306
- }
2307
- const url = `${BASE_URL}/s/${sessionId}`;
2308
- console.log(url);
2309
- openBrowser(url);
2310
- });
2311
- program2.command("rm <id>").description("Kill a session and its PTY").action(async (id) => {
2312
- let res;
2313
- try {
2314
- res = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`, {
2315
- method: "DELETE"
2316
- });
2317
- } catch {
2318
- console.log("webtty is not running");
2319
- process.exit(1);
2320
- }
2321
- if (res.status === 204) {
2322
- console.log(`removed ${id}`);
2323
- } else if (res.status === 404) {
2324
- console.error(`session ${id} not found`);
2325
- process.exit(1);
2326
- } else {
2327
- console.error(`webtty rm failed (status: ${res.status})`);
2328
- process.exit(1);
2329
- }
2330
- });
2331
- program2.command("rename <id> <new-id>").description("Rename a session").action(async (id, newId) => {
2332
- let res;
2333
- try {
2334
- res = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`, {
2335
- method: "PATCH",
2336
- headers: { "Content-Type": "application/json" },
2337
- body: JSON.stringify({ id: newId })
2338
- });
2339
- } catch {
2340
- console.log("webtty is not running");
2341
- process.exit(1);
2342
- }
2343
- if (res.ok) {
2344
- console.log(`renamed ${id} → ${newId}`);
2345
- } else if (res.status === 404) {
2346
- console.error(`session ${id} not found`);
2347
- process.exit(1);
2348
- } else {
220
+ }
221
+ let sessionId;
222
+ const check = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`);
223
+ if (check.status === 200) {
224
+ sessionId = id;
225
+ } else {
226
+ const res = await fetch(`${BASE_URL}/api/sessions`, {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/json" },
229
+ body: JSON.stringify({ id })
230
+ });
231
+ if (!res.ok) {
2349
232
  const body = await res.json();
2350
- console.error(`webtty: ${body.error ?? `rename failed (${res.status})`}`);
233
+ console.error(`webtty: ${body.error ?? `failed to create session (${res.status})`}`);
2351
234
  process.exit(1);
2352
235
  }
2353
- });
2354
- program2.command("restart").description("Restart the webtty server").action(async () => {
2355
- if (await isServerRunning()) {
2356
- const ok = await stopServer();
2357
- if (!ok) {
2358
- console.error("webtty: failed to stop server");
2359
- process.exit(1);
2360
- }
2361
- }
2362
- await startServer();
2363
- console.log("webtty restarted");
2364
- });
236
+ const session = await res.json();
237
+ sessionId = session.id;
238
+ }
239
+ const url = `${BASE_URL}/s/${sessionId}`;
240
+ console.log(url);
241
+ openBrowser(url);
242
+ }
243
+ async function cmdList(filter) {
244
+ let res;
245
+ try {
246
+ res = await fetch(`${BASE_URL}/api/sessions`);
247
+ } catch {
248
+ console.log("webtty is not running");
249
+ process.exit(1);
250
+ }
251
+ const all = await res.json();
252
+ const sessions = filter ? all.filter((s) => s.id.includes(filter)) : all;
253
+ if (sessions.length === 0) {
254
+ console.log("no sessions");
255
+ return;
256
+ }
257
+ console.log("id\t\t\tconnected\tcreated");
258
+ for (const s of sessions) {
259
+ const created = new Date(s.createdAt).toLocaleString();
260
+ console.log(`${s.id} ${s.connected} ${created}`);
261
+ }
262
+ }
263
+ async function cmdRemove(id) {
264
+ if (!id) {
265
+ console.error("webtty: rm requires a session id");
266
+ process.exit(1);
267
+ }
268
+ let res;
269
+ try {
270
+ res = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`, {
271
+ method: "DELETE"
272
+ });
273
+ } catch {
274
+ console.log("webtty is not running");
275
+ process.exit(1);
276
+ }
277
+ if (res.status === 204) {
278
+ console.log(`removed ${id}`);
279
+ if (res.headers.get("x-sessions-remaining") === "0") {
280
+ await stopServer();
281
+ console.log("no sessions remaining — webtty stopped");
282
+ }
283
+ } else if (res.status === 404) {
284
+ console.error(`session ${id} not found`);
285
+ process.exit(1);
286
+ } else {
287
+ console.error(`webtty rm failed (status: ${res.status})`);
288
+ process.exit(1);
289
+ }
290
+ }
291
+ async function cmdRename(id, newId) {
292
+ if (!id || !newId) {
293
+ console.error("webtty: rename requires two arguments: [id] [new-id]");
294
+ process.exit(1);
295
+ }
296
+ let res;
297
+ try {
298
+ res = await fetch(`${BASE_URL}/api/sessions/${encodeURIComponent(id)}`, {
299
+ method: "PATCH",
300
+ headers: { "Content-Type": "application/json" },
301
+ body: JSON.stringify({ id: newId })
302
+ });
303
+ } catch {
304
+ console.log("webtty is not running");
305
+ process.exit(1);
306
+ }
307
+ if (res.ok) {
308
+ console.log(`renamed ${id} → ${newId}`);
309
+ } else if (res.status === 404) {
310
+ console.error(`session ${id} not found`);
311
+ process.exit(1);
312
+ } else {
313
+ const body = await res.json();
314
+ console.error(`webtty: ${body.error ?? `rename failed (${res.status})`}`);
315
+ process.exit(1);
316
+ }
317
+ }
318
+ async function cmdStop() {
319
+ if (!await isServerRunning()) {
320
+ console.log("webtty is not running");
321
+ return;
322
+ }
323
+ const ok = await stopServer();
324
+ if (ok) {
325
+ console.log("webtty stopped");
326
+ } else {
327
+ console.error("webtty stop failed");
328
+ process.exit(1);
329
+ }
330
+ }
331
+ async function cmdStart() {
332
+ if (await isServerRunning()) {
333
+ console.log("webtty is already running");
334
+ return;
335
+ }
336
+ await startServer();
337
+ console.log("webtty started");
338
+ }
339
+ function cmdConfig() {
340
+ const dir = configDir();
341
+ const configPath = path3.join(dir, "config.json");
342
+ fs3.mkdirSync(dir, { recursive: true });
343
+ if (!fs3.existsSync(configPath)) {
344
+ fs3.writeFileSync(configPath, `{}
345
+ `, "utf8");
346
+ }
347
+ const editor = process.env.VISUAL ?? process.env.EDITOR ?? (process.platform === "win32" ? "notepad" : "vi");
348
+ childProcess2.spawnSync(editor, [configPath], { stdio: "inherit" });
2365
349
  }
2366
350
 
2367
351
  // src/cli/index.ts
2368
- var program2 = new Command;
2369
- program2.name("webtty").description("Web TTY — run terminal sessions in a browser tab");
2370
- registerCommands(program2);
2371
- program2.parse(process.argv);
352
+ var GO_ALIASES = new Set(["go", "a", "run", "attach", "open"]);
353
+ function printHelp() {
354
+ const indent = " ";
355
+ const col = 18;
356
+ const row = (term, desc) => `${indent}${term.padEnd(col)} ${desc}`;
357
+ console.log([
358
+ "Launch Terminal UI in the browser.",
359
+ "",
360
+ "USAGE",
361
+ row("webtty", "Open main session in the browser"),
362
+ row("webtty [command]", "Execute a specific command"),
363
+ "",
364
+ "COMMANDS",
365
+ row("go [id]", "Open a new or existing session in the browser"),
366
+ row("ls [id]", "List all sessions, or filter by id substring"),
367
+ row("rm <id>", "Destroy a session"),
368
+ row("mv <id> <new-id>", "Rename a session"),
369
+ row("stop", "Stop the webtty server"),
370
+ row("start", "Start the webtty server"),
371
+ row("config", "Open the config file in $VISUAL, $EDITOR, or a default editor"),
372
+ row("help", "Show this help message")
373
+ ].join(`
374
+ `));
375
+ }
376
+ var [, , cmd, ...rest] = process.argv;
377
+ if (!cmd) {
378
+ await cmdGo();
379
+ } else if (GO_ALIASES.has(cmd)) {
380
+ await cmdGo(rest[0]);
381
+ } else {
382
+ switch (cmd) {
383
+ case "ls":
384
+ case "list":
385
+ await cmdList(rest[0]);
386
+ break;
387
+ case "rm":
388
+ case "remove":
389
+ await cmdRemove(rest[0]);
390
+ break;
391
+ case "mv":
392
+ case "move":
393
+ case "rename":
394
+ await cmdRename(rest[0], rest[1]);
395
+ break;
396
+ case "stop":
397
+ await cmdStop();
398
+ break;
399
+ case "start":
400
+ await cmdStart();
401
+ break;
402
+ case "config":
403
+ cmdConfig();
404
+ break;
405
+ case "help":
406
+ case "--help":
407
+ case "-h":
408
+ printHelp();
409
+ break;
410
+ default:
411
+ console.error(`webtty: unknown command '${cmd}'
412
+ Run \`webtty help\` for usage.`);
413
+ process.exit(1);
414
+ }
415
+ }
2372
416
 
2373
- //# debugId=1DEC1C353196B21C64756E2164756E21
417
+ //# debugId=2F831607DCDC8E5D64756E2164756E21