-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.ts
More file actions
1317 lines (1142 loc) · 40.5 KB
/
Copy pathinteractive.ts
File metadata and controls
1317 lines (1142 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Command } from "@oclif/core";
import * as readline from "node:readline";
import * as path from "node:path";
import * as fs from "node:fs";
import chalk from "chalk";
import { HistoryManager } from "../services/history-manager.js";
import { displayLogo } from "../utils/logo.js";
import {
WEB_CLI_RESTRICTED_COMMANDS,
WEB_CLI_ANONYMOUS_RESTRICTED_COMMANDS,
INTERACTIVE_UNSUITABLE_COMMANDS,
} from "../base-command.js";
import { TerminalDiagnostics } from "../utils/terminal-diagnostics.js";
import { formatWarning } from "../utils/output.js";
import "../utils/sigint-exit.js";
import isWebCliMode from "../utils/web-mode.js";
interface HistorySearchState {
active: boolean;
searchTerm: string;
matches: string[];
currentIndex: number;
originalLine: string;
originalCursorPos: number;
}
export default class Interactive extends Command {
static description =
"Launch interactive Ably shell (ALPHA - experimental feature)";
static hidden = true; // Hide from help until stable
static EXIT_CODE_USER_EXIT = 42; // Special code for 'exit' command
private rl: readline.Interface | null = null;
private historyManager!: HistoryManager;
private isWrapperMode = process.env.ABLY_WRAPPER_MODE === "1";
private _flagsCache?: Record<string, string[]>;
private _manifestCache?: {
commands: Record<
string,
{
flags: Record<
string,
{
name: string;
char?: string;
description?: string;
type?: string;
hidden?: boolean;
}
>;
}
>;
};
private runningCommand = false;
private cleanupDone = false;
private historySearch: HistorySearchState = {
active: false,
searchTerm: "",
matches: [],
currentIndex: 0,
originalLine: "",
originalCursorPos: 0,
};
async run() {
TerminalDiagnostics.log("Interactive.run() started");
// In non-TTY mode, readline doesn't convert \x03 to SIGINT
// We need to handle this at the process level for wrapper compatibility
if (!process.stdin.isTTY) {
// Install a data handler on stdin to detect Ctrl+C
const handleStdinData = (data: Buffer) => {
if (data.includes(0x03)) {
// Non-TTY readline doesn't synthesise SIGINT from a 0x03 (Ctrl+C)
// byte, so we do it. This only fires while stdin is flowing: at the
// prompt, or while a command is itself reading stdin (e.g. a y/n
// confirmation). For an ordinary long-running command the outer
// readline keeps stdin paused, so the byte is buffered and never
// reaches here — those are interrupted by a real OS SIGINT, which is
// what a TTY and the node-pty web CLI deliver.
if (this.runningCommand) {
// A command is reading stdin (e.g. a prompt): SIGINT ourselves so
// its own handlers unwind and we return to the prompt.
process.kill(process.pid, "SIGINT");
} else {
// At the prompt: let readline show ^C and a fresh prompt.
this.rl?.emit("SIGINT");
}
}
};
// We'll set this up after readline is created
(
this as Interactive & { _handleStdinData?: (data: Buffer) => void }
)._handleStdinData = handleStdinData;
}
try {
// Don't automatically use wrapper - let users choose
// Don't install any signal handlers at the process level
// When SIGINT is received:
// - If at prompt: readline handles it (shows ^C and new prompt)
// - If running command: the command's own SIGINT handling unwinds and we
// return to the prompt in-process (a double Ctrl+C still force-quits)
// Set environment variable to indicate we're in interactive mode
process.env.ABLY_INTERACTIVE_MODE = "true";
// SIGINT handling will be set up after readline is created
// Disable stack traces in interactive mode unless explicitly debugging
if (!process.env.DEBUG) {
process.env.NODE_ENV = "production";
}
// Silence oclif's error output
const originalConsoleError = console.error;
let suppressNextError = false;
console.error = ((...args: unknown[]) => {
// Skip oclif error stack traces in interactive mode
if (
suppressNextError ||
(args[0] &&
typeof args[0] === "string" &&
(args[0].includes("at async Config.runCommand") ||
args[0].includes("at Object.hook")))
) {
suppressNextError = false;
return;
}
originalConsoleError.apply(console, args);
}) as typeof console.error;
// Store readline instance globally for hooks to access
(globalThis as Record<string, unknown>).__ablyInteractiveReadline = null;
// Show welcome message only on first run
if (!process.env.ABLY_SUPPRESS_WELCOME) {
// Display logo
displayLogo(console.log);
console.log(` ${chalk.dim(`Version ${this.config.version}`)}\n`);
// Show appropriate tagline based on mode
let tagline = "ably.com ";
if (this.isWebCliMode()) {
tagline += "browser-based ";
}
tagline += "interactive CLI for Pub/Sub, Chat and Spaces";
console.log(chalk.bold(tagline));
console.log();
// Ctrl+C guidance. A single Ctrl+C interrupts a running command and
// returns to the prompt; type `exit` (or Ctrl+D) to leave the shell.
if (!this.isWrapperMode && !this.isWebCliMode()) {
console.log(
chalk.dim(
"Press Ctrl+C to interrupt a running command. Type 'exit' to quit.\n",
),
);
}
// Show formatted common commands
console.log(chalk.bold("COMMON COMMANDS"));
const isAnonymousMode = this.isAnonymousWebMode();
// Basic commands always available
const commands = [
["help", "Show help for any command"],
[
"channels publish [channel] [message]",
"Publish a message to a channel",
],
["channels subscribe [channel]", "Subscribe to a channel"],
];
// Commands available only for authenticated users
if (!isAnonymousMode) {
commands.push(["channels list", "List active channels"]);
}
commands.push(
["spaces enter [space]", "Enter a collaborative space"],
[
"rooms messages send [room] [message]",
"Send a message to a chat room",
],
["exit", "Exit the interactive shell"],
);
// Calculate padding for alignment
const maxCmdLength = Math.max(...commands.map(([cmd]) => cmd!.length));
// Display commands with proper alignment
commands.forEach(([cmd, desc]) => {
const paddedCmd = cmd!.padEnd(maxCmdLength + 2);
console.log(` ${chalk.cyan(paddedCmd)}${desc}`);
});
console.log();
console.log(
"Type " +
chalk.cyan("help") +
" to see the complete list of commands.",
);
console.log();
}
this.historyManager = new HistoryManager();
this.setupReadline();
await this.historyManager.loadHistory(this.rl!);
// Don't install SIGINT handler - sigint-exit.ts handles this with proper feedback
// It will show "↓ Stopping command..." and give 5 seconds for cleanup
// Also handle SIGTERM to ensure cleanup
process.once("SIGTERM", () => {
if (!this.cleanupDone) {
this.cleanupAndExit(143); // Standard SIGTERM exit code
}
});
// Handle unexpected exits to ensure terminal is restored
process.once("exit", () => {
if (
!this.cleanupDone && // Emergency cleanup - just restore terminal
process.stdin.isTTY &&
typeof (
process.stdin as NodeJS.ReadStream & {
setRawMode?: (mode: boolean) => void;
}
).setRawMode === "function"
) {
try {
(
process.stdin as NodeJS.ReadStream & {
setRawMode: (mode: boolean) => void;
}
).setRawMode(false);
} catch {
// Ignore errors
}
}
});
this.rl!.prompt();
} catch (error) {
// If there's an error starting up, exit gracefully
console.error("Failed to start interactive mode:", error);
process.exit(1);
}
}
private setupReadline() {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: "ably> ",
terminal: true,
completer: this.completer.bind(this),
});
// Install stdin data handler for non-TTY mode
if (
(this as Interactive & { _handleStdinData?: (data: Buffer) => void })
._handleStdinData
) {
process.stdin.on(
"data",
(this as Interactive & { _handleStdinData?: (data: Buffer) => void })
._handleStdinData!,
);
}
// Store readline instance globally for hooks to access
(globalThis as Record<string, unknown>).__ablyInteractiveReadline = this.rl;
// Setup keypress handler for Ctrl+R and other special keys
this.setupKeypressHandler();
// Don't install any SIGINT handler initially
this.rl.on("line", (input) => {
// Exit history search mode when a command is executed
if (this.historySearch.active) {
this.exitHistorySearch();
}
void this.handleCommand(input.trim());
});
// SIGINT handling is done through readline's built-in mechanism
// Handle SIGINT events on readline
this.rl.on("SIGINT", () => {
if (this.runningCommand) {
// Don't handle SIGINT here - sigint-exit.ts will handle it
// with proper feedback and 5-second timeout
return;
}
// If in history search mode, exit it
if (this.historySearch.active) {
this.exitHistorySearch();
return;
}
// Clear the current line similar to how zsh behaves
const currentLine =
(this.rl as readline.Interface & { line?: string }).line || "";
if (currentLine.length > 0) {
// Clear the entire line content
(
this.rl as readline.Interface & { _deleteLineLeft: () => void }
)._deleteLineLeft();
(
this.rl as readline.Interface & { _deleteLineRight: () => void }
)._deleteLineRight();
// Show ^C and new prompt
process.stdout.write("^C\n");
} else {
// At empty prompt - show message about how to exit
process.stdout.write("^C\n");
console.log(
chalk.yellow(
"Signal received. To exit this shell, type 'exit' and press Enter.",
),
);
}
this.rl!.prompt();
});
// For non-TTY environments, we need special SIGINT handling
// But we should NOT interfere with sigint-exit.ts handler
if (!process.stdin.isTTY) {
// Don't install any handler here - sigint-exit.ts handles everything
// It will show feedback and manage the 5-second timeout
}
this.rl.on("close", () => {
TerminalDiagnostics.log("readline close event triggered");
if (!this.runningCommand) {
this.cleanup();
// Use special exit code when in wrapper mode
const exitCode = this.isWrapperMode
? Interactive.EXIT_CODE_USER_EXIT
: 0;
process.exit(exitCode);
}
});
}
private async handleCommand(input: string) {
if (input === "exit" || input === ".exit") {
this.rl!.close();
return;
}
if (input === "") {
this.rl!.prompt();
return;
}
// Save to history (before handling any commands)
await this.historyManager.saveCommand(input);
// Handle version command (hidden command)
if (input === "version") {
const { getVersionInfo } = await import("../utils/version.js");
const versionInfo = getVersionInfo(this.config);
this.log(`Version: ${versionInfo.version}`);
this.rl!.prompt();
return;
}
// Handle "ably" command - inform user they're already in interactive mode
if (input === "ably") {
console.log(
chalk.yellow(
"You're already in interactive mode. Type 'help' or press TAB to see available commands.",
),
);
this.rl!.prompt();
return;
}
// Set command running state
this.runningCommand = true;
(globalThis as Record<string, unknown>).__ablyInteractiveRunningCommand =
true;
// Pause readline
TerminalDiagnostics.log("Pausing readline for command execution");
this.rl!.pause();
// CRITICAL FIX: Set stdin to cooked mode to allow Ctrl+C to generate SIGINT
// Readline keeps stdin in raw mode even when paused, which prevents signal generation
if (
process.stdin.isTTY &&
typeof (
process.stdin as NodeJS.ReadStream & {
setRawMode?: (mode: boolean) => void;
}
).setRawMode === "function"
) {
TerminalDiagnostics.log(
"Setting terminal to cooked mode for command execution",
);
(
process.stdin as NodeJS.ReadStream & {
setRawMode: (mode: boolean) => void;
}
).setRawMode(false);
}
// SIGINT handling is done at module level in sigint-handler.ts
try {
const args = this.parseCommand(input);
// Separate command parts from args (everything before first flag)
const commandParts: string[] = [];
let firstFlagIndex = args.findIndex((arg) => arg.startsWith("-"));
if (firstFlagIndex === -1) {
// No flags, all args are command parts
commandParts.push(...args);
} else {
// Everything before first flag is command parts
commandParts.push(...args.slice(0, firstFlagIndex));
}
// Everything from first flag onwards stays together for oclif to parse
const remainingArgs =
firstFlagIndex === -1 ? [] : args.slice(firstFlagIndex);
// Handle special case of only flags (like --version)
if (commandParts.length === 0 && remainingArgs.length > 0) {
// Check for version flag
if (
remainingArgs.includes("--version") ||
remainingArgs.includes("-v")
) {
const { getVersionInfo } = await import("../utils/version.js");
const versionInfo = getVersionInfo(this.config);
this.log(`Version: ${versionInfo.version}`);
return;
}
// For other global flags, show help
await this.config.runCommand("help", []);
return;
}
// Find the command by trying different combinations
// Commands in oclif use colons, e.g., "help:ask" for "help ask"
let commandId: string | undefined;
let commandArgs: string[] = [];
// Try to find a matching command
for (let i = commandParts.length; i > 0; i--) {
const possibleId = commandParts.slice(0, i).join(":");
const cmd = this.config.findCommand(possibleId);
if (cmd) {
commandId = possibleId;
// Include remaining command parts and all remaining args
commandArgs = [...commandParts.slice(i), ...remainingArgs];
break;
}
}
if (!commandId) {
// No command found - this will trigger command_not_found hook
commandId = commandParts.join(":");
commandArgs = remainingArgs;
}
// Check if the command is restricted
if (this.isCommandRestricted(commandId)) {
const displayCommand = commandId.replaceAll(":", " ");
let errorMessage: string;
if (this.isAnonymousWebMode()) {
errorMessage = `The '${displayCommand}' command is not available in anonymous mode.\nPlease provide an access token to use this command.`;
} else if (this.isWebCliMode()) {
errorMessage = `The '${displayCommand}' command is not available in the web CLI.`;
} else {
errorMessage = `The '${displayCommand}' command is not available in interactive mode.`;
}
console.error(chalk.red("Error:"), errorMessage);
return;
}
// Special handling for help flags
if (commandArgs.includes("--help") || commandArgs.includes("-h")) {
// If the command has help flags, we need to handle it specially
// because oclif's runCommand doesn't properly handle help for subcommands
const { default: CustomHelp } = await import("../help.js");
const help = new CustomHelp(this.config);
// Find the actual command
const cmd = this.config.findCommand(commandId);
if (cmd) {
await help.showCommandHelp(cmd);
return;
}
}
// Run command without any timeout
await this.config.runCommand(commandId, commandArgs);
} catch (error) {
const err = error as {
code?: string;
exitCode?: number;
message?: string;
isCommandNotFound?: boolean;
oclif?: { exit?: number };
stack?: string;
};
// Special handling for intentional exits
if (err.code === "EEXIT" && err.exitCode === 0) {
// Normal exit (like from help command) - don't display anything
return;
}
// Always show errors in red
let errorMessage = err.message || "Unknown error";
// Clean up the error message if it has ANSI codes or extra formatting
// eslint-disable-next-line no-control-regex
errorMessage = errorMessage.replaceAll(/\u001B\[[0-9;]*m/g, ""); // Remove ANSI codes
// Check for specific error types
if (err.isCommandNotFound) {
// Command not found - already has appropriate message
console.error(chalk.red(errorMessage));
} else if (
err.oclif?.exit !== undefined ||
err.exitCode !== undefined ||
err.code === "EEXIT"
) {
// This is an oclif error or exit that would normally exit the process
// Show in red without the "Error:" prefix as it's already formatted
console.error(chalk.red(errorMessage));
} else if (err.stack && process.env.DEBUG) {
// Show stack trace in debug mode
console.error(chalk.red("Error:"), errorMessage);
console.error(err.stack);
} else {
// All other errors - show with Error prefix
console.error(chalk.red("Error:"), errorMessage);
}
} finally {
// SIGINT handling is done at module level
// Reset command running state
this.runningCommand = false;
(globalThis as Record<string, unknown>).__ablyInteractiveRunningCommand =
false;
// Restore raw mode for readline with error handling
if (
process.stdin.isTTY &&
typeof (
process.stdin as NodeJS.ReadStream & {
setRawMode?: (mode: boolean) => void;
}
).setRawMode === "function"
) {
try {
TerminalDiagnostics.log(
"Restoring terminal to raw mode for readline",
);
(
process.stdin as NodeJS.ReadStream & {
setRawMode: (mode: boolean) => void;
}
).setRawMode(true);
TerminalDiagnostics.log("Terminal restored to raw mode successfully");
} catch (error) {
TerminalDiagnostics.log(
"Error restoring terminal to raw mode",
error as Error,
);
// Terminal might be in a bad state after SIGINT
// Try to recover by recreating the readline interface
if ((error as NodeJS.ErrnoException).code === "EIO") {
console.error(
chalk.yellow(
"\nTerminal state corrupted. Please restart the interactive shell.",
),
);
this.cleanup(false);
process.exit(1);
}
}
}
// Resume readline
this.rl!.resume();
// Small delay to ensure error messages are visible
setTimeout(() => {
if (this.rl) {
this.rl.prompt();
}
}, 50);
}
}
private parseCommand(input: string): string[] {
const args: string[] = [];
let current = "";
let inDoubleQuote = false;
let inSingleQuote = false;
let escaped = false;
for (let i = 0; i < input.length; i++) {
const char = input[i];
const nextChar = input[i + 1];
if (escaped) {
// Add the escaped character literally
current += char;
escaped = false;
continue;
}
if (char === "\\" && (inDoubleQuote || inSingleQuote)) {
// Check if this is an escape sequence
if (
inDoubleQuote &&
(nextChar === '"' ||
nextChar === "\\" ||
nextChar === "$" ||
nextChar === "`")
) {
escaped = true;
continue;
} else if (inSingleQuote && nextChar === "'") {
escaped = true;
continue;
}
// Otherwise, backslash is literal
current += char;
continue;
}
if (char === '"' && !inSingleQuote) {
inDoubleQuote = !inDoubleQuote;
// If we're closing a quote and have content, that's an argument
if (!inDoubleQuote && current === "") {
// Empty string argument
args.push("");
current = "";
}
continue;
}
if (char === "'" && !inDoubleQuote) {
inSingleQuote = !inSingleQuote;
// If we're closing a quote and have content, that's an argument
if (!inSingleQuote && current === "") {
// Empty string argument
args.push("");
current = "";
}
continue;
}
if (char === " " && !inDoubleQuote && !inSingleQuote) {
// Space outside quotes - end current argument
if (current.length > 0) {
args.push(current);
current = "";
}
continue;
}
// Regular character - add to current argument
current += char;
}
// Handle any remaining content
if (current.length > 0 || inDoubleQuote || inSingleQuote) {
args.push(current);
}
// Warn about unclosed quotes
if (inDoubleQuote || inSingleQuote) {
const quoteType = inDoubleQuote ? "double" : "single";
console.error(formatWarning(`Unclosed ${quoteType} quote in command`));
}
return args;
}
private cleanup(showGoodbye = true) {
TerminalDiagnostics.log("cleanup() called");
// Close the readline interface first
if (this.rl) {
try {
TerminalDiagnostics.log("Closing readline interface");
this.rl.close();
TerminalDiagnostics.log("Readline interface closed");
} catch (error) {
TerminalDiagnostics.log("Error closing readline", error as Error);
}
}
// Ensure terminal is restored to normal mode
if (
process.stdin.isTTY &&
typeof (
process.stdin as NodeJS.ReadStream & {
setRawMode?: (mode: boolean) => void;
}
).setRawMode === "function"
) {
try {
TerminalDiagnostics.log("Restoring terminal to cooked mode");
(
process.stdin as NodeJS.ReadStream & {
setRawMode: (mode: boolean) => void;
}
).setRawMode(false);
TerminalDiagnostics.log("Terminal restored successfully");
} catch (error) {
TerminalDiagnostics.log("Error restoring terminal", error as Error);
}
}
// Ensure stdin is unrefed so it doesn't keep the process alive
if (typeof process.stdin.unref === "function") {
process.stdin.unref();
}
if (showGoodbye) {
console.log("\nGoodbye!");
}
}
private cleanupAndExit(code: number) {
TerminalDiagnostics.log(`cleanupAndExit(${code}) called`);
// Mark cleanup as done to prevent double cleanup
this.cleanupDone = true;
// Perform cleanup without goodbye message
this.cleanup(false);
TerminalDiagnostics.log(`Exiting with code ${code}`);
// Exit with the specified code
process.exit(code);
}
private completer(
line: string,
callback?: (err: Error | null, result: [string[], string]) => void,
): [string[], string] | void {
// Don't provide completions during history search
if (this.historySearch.active) {
const emptyResult: [string[], string] = [[], line];
if (callback) {
callback(null, emptyResult);
} else {
return emptyResult;
}
return;
}
// Support both sync and async patterns
const result = this.getCompletions(line);
if (callback) {
// Async mode - used by readline for custom display
callback(null, result);
} else {
// Sync mode - fallback
return result;
}
}
private getCompletions(line: string): [string[], string] {
const words = line.trim().split(/\s+/);
const lastWord = words.at(-1) || "";
// If line ends with a space, we're starting a new word
const isNewWord = line.endsWith(" ");
const currentWord = isNewWord ? "" : lastWord;
// Get the command path (excluding the last word if not new)
const commandPath = isNewWord ? words : words.slice(0, -1);
if (commandPath.length === 0 || (!isNewWord && words.length === 1)) {
// Complete top-level commands
const commands = this.getTopLevelCommands();
const matches = commands.filter((cmd) => cmd.startsWith(currentWord));
// Custom display for multiple matches
if (matches.length > 1) {
this.displayCompletions(matches, "command");
return [[], line]; // Don't auto-complete, just show options
}
return [matches, currentWord];
}
// Check if we're completing flags
if (currentWord.startsWith("-")) {
const flags = this.getFlagsForCommandSync(commandPath);
const matches = flags.filter((flag) => flag.startsWith(currentWord));
if (matches.length > 1) {
this.displayCompletions(matches, "flag");
return [[], line];
}
return [matches, currentWord];
}
// Try to find subcommands
const subcommands = this.getSubcommandsForPath(commandPath);
const matches = subcommands.filter((cmd) => cmd.startsWith(currentWord));
if (matches.length > 1) {
this.displayCompletions(matches, "subcommand", commandPath);
return [[], line];
}
return [matches.length > 0 ? matches : [], currentWord];
}
private getTopLevelCommands(): string[] {
// Cache this on first use
if (!this._commandCache) {
this._commandCache = [];
for (const command of this.config.commands) {
if (
!command.hidden &&
!command.id.includes(":") && // Filter out restricted commands
!this.isCommandRestricted(command.id)
) {
this._commandCache.push(command.id);
}
}
// Add special commands that aren't filtered
// Only add 'exit' since help, version, config, and autocomplete are filtered out
this._commandCache.push("exit");
this._commandCache.sort();
}
return this._commandCache;
}
private getSubcommandsForPath(commandPath: string[]): string[] {
// Convert space-separated path to colon-separated for oclif
const parentCommand = commandPath.filter(Boolean).join(":");
const subcommands: string[] = [];
for (const command of this.config.commands) {
if (
!command.hidden &&
command.id.startsWith(parentCommand + ":") && // Filter out restricted commands
!this.isCommandRestricted(command.id)
) {
// Get the next part of the command
const remaining = command.id.slice(parentCommand.length + 1);
const parts = remaining.split(":");
const nextPart = parts[0];
// Only add direct children (one level deep)
if (nextPart && parts.length === 1) {
subcommands.push(nextPart);
}
}
}
return [...new Set(subcommands)].toSorted();
}
private getFlagsForCommandSync(commandPath: string[]): string[] {
// Get cached flags if available
const commandId = commandPath.filter(Boolean).join(":");
if (this._flagsCache && this._flagsCache[commandId]) {
return this._flagsCache[commandId];
}
// Basic flags available for all commands
const flags: string[] = ["--help", "-h"];
// Try to get flags from manifest first
try {
// Load manifest if not already loaded
if (!this._manifestCache) {
const manifestPath = path.join(this.config.root, "oclif.manifest.json");
if (fs.existsSync(manifestPath)) {
this._manifestCache = JSON.parse(
fs.readFileSync(manifestPath, "utf8"),
) as typeof this._manifestCache;
}
}
// Get flags from manifest
if (this._manifestCache?.commands) {
const manifestCommand = this._manifestCache.commands[commandId];
if (manifestCommand?.flags) {
for (const [name, flag] of Object.entries(manifestCommand.flags)) {
const flagDef = flag;
// Skip hidden flags unless in dev mode
if (flagDef.hidden && process.env.ABLY_SHOW_DEV_FLAGS !== "true") {
continue;
}
flags.push(`--${name}`);
if (flagDef.char) {
flags.push(`-${flagDef.char}`);
}
}
}
}
} catch {
// Fall back to trying to get from loaded command
try {
const command = this.config.findCommand(commandId);
if (command?.flags) {
// Add flags from command definition (these are already loaded)
for (const [name, flag] of Object.entries(command.flags)) {
flags.push(`--${name}`);
if (flag.char) {
flags.push(`-${flag.char}`);
}
}
}
} catch {
// Ignore errors
}
}
// Add global flags for top-level
if (commandPath.length === 0 || commandPath[0] === "") {
flags.push("--version", "-v");
}
const uniqueFlags = [...new Set(flags)].toSorted();
// Cache for next time
if (!this._flagsCache) {
this._flagsCache = {};
}
this._flagsCache[commandId] = uniqueFlags;
return uniqueFlags;
}
private displayCompletions(
matches: string[],
type: string,
commandPath?: string[],
): void {
console.log(); // New line for better display
// Get descriptions for each match
const items: Array<{ name: string; description: string }> = [];
for (const match of matches) {
let description = "";
if (type === "command" || type === "subcommand") {
const fullId = commandPath ? [...commandPath, match].join(":") : match;
const cmd = this.config.findCommand(fullId);
if (cmd && cmd.description) {
description = cmd.description;
}
} else if (
type === "flag" && // Extract flag description from manifest first, then fall back to command
commandPath
) {
const commandId = commandPath.filter(Boolean).join(":");
const flagName = match.replace(/^--?/, "");
// Try manifest first
if (this._manifestCache?.commands) {
const manifestCommand = this._manifestCache.commands[commandId];
if (manifestCommand?.flags) {
// Find flag by name or char
for (const [name, flag] of Object.entries(manifestCommand.flags)) {
const flagDef = flag;
if (
name === flagName ||
(flagDef.char && flagDef.char === flagName)
) {
description = flagDef.description || "";
break;
}
}