xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / terminal.test.ts

6.8 KB
1import { describe, expect, test } from "bun:test";
2import { ProcessTerminal } from "./terminal.js";
3
4type Restorer = () => void;
5type TerminationSignal = "SIGINT" | "SIGTERM";
6
7const CLEANUP_SEQUENCE =
8  "\x1b[?1006l\x1b[?1000l\x1b[?2004l\x1b[<u\x1b[0 q\x1b[?25h\x1b[?1049l";
9
10async function runSignalChild(
11  signal: TerminationSignal,
12  withApplicationListener = false,
13) {
14  const terminalModuleUrl = new URL("./terminal.ts", import.meta.url).href;
15  const source = `
16    import { ProcessTerminal } from ${JSON.stringify(terminalModuleUrl)};
17
18    if (${JSON.stringify(withApplicationListener)}) {
19      process.on(${JSON.stringify(signal)}, () => {});
20    }
21    const terminal = new ProcessTerminal();
22    terminal.start(() => {}, () => {});
23    setTimeout(() => process.exit(99), 100);
24    process.kill(process.pid, ${JSON.stringify(signal)});
25  `;
26  const child = Bun.spawn([process.execPath, "-e", source], {
27    stdin: "ignore",
28    stdout: "pipe",
29    stderr: "pipe",
30  });
31  const stdout = new Response(child.stdout).text();
32  const stderr = new Response(child.stderr).text();
33  const status = await child.exited;
34
35  return {
36    status,
37    signalCode: child.signalCode,
38    stderr: await stderr,
39    stdout: await stdout,
40  };
41}
42
43function replaceMethod<T extends object, K extends keyof T>(
44  object: T,
45  key: K,
46  value: T[K],
47): Restorer {
48  const descriptor = Object.getOwnPropertyDescriptor(object, key);
49  Object.defineProperty(object, key, {
50    configurable: true,
51    writable: true,
52    value,
53  });
54
55  return () => {
56    if (descriptor) {
57      Object.defineProperty(object, key, descriptor);
58    }
59  };
60}
61
62function patchProcessIo(): Restorer {
63  const restoreStdoutWrite = replaceMethod(
64    process.stdout,
65    "write",
66    (() => true) as typeof process.stdout.write,
67  );
68  const restoreResume = replaceMethod(
69    process.stdin,
70    "resume",
71    (() => process.stdin) as typeof process.stdin.resume,
72  );
73  const restorePause = replaceMethod(
74    process.stdin,
75    "pause",
76    (() => process.stdin) as typeof process.stdin.pause,
77  );
78  const restoreSetEncoding = replaceMethod(
79    process.stdin,
80    "setEncoding",
81    (() => process.stdin) as typeof process.stdin.setEncoding,
82  );
83  const restoreSetRawMode = replaceMethod(
84    process.stdin,
85    "setRawMode",
86    (() => process.stdin) as typeof process.stdin.setRawMode,
87  );
88
89  return () => {
90    restoreSetRawMode();
91    restoreSetEncoding();
92    restorePause();
93    restoreResume();
94    restoreStdoutWrite();
95  };
96}
97
98class CapturingProcessTerminal extends ProcessTerminal {
99  output = "";
100
101  override write(data: string): void {
102    this.output += data;
103  }
104}
105
106describe("ProcessTerminal", () => {
107  test("keeps the default Kitty disambiguation flag", () => {
108    const restoreIo = patchProcessIo();
109    const term = new CapturingProcessTerminal();
110
111    try {
112      term.start(
113        () => {},
114        () => {},
115      );
116      expect(term.output).toContain("\x1b[>1u");
117    } finally {
118      term.stop();
119      restoreIo();
120    }
121  });
122
123  test("pushes the requested Kitty progressive-enhancement flags", () => {
124    const restoreIo = patchProcessIo();
125    const term = new CapturingProcessTerminal();
126
127    try {
128      term.start(
129        () => {},
130        () => {},
131        {
132          kittyKeyboard: {
133            reportEventTypes: true,
134            reportAlternateKeys: true,
135            reportAllKeys: true,
136            reportAssociatedText: true,
137          },
138        },
139      );
140      expect(term.output).toContain("\x1b[>31u");
141      term.stop();
142      expect(term.output.indexOf("\x1b[>31u")).toBeLessThan(
143        term.output.indexOf("\x1b[<u"),
144      );
145      expect(term.output.split("\x1b[<u")).toHaveLength(2);
146    } finally {
147      term.stop();
148      restoreIo();
149    }
150  });
151
152  test("associated text automatically enables all-keys reporting", () => {
153    const restoreIo = patchProcessIo();
154    const term = new CapturingProcessTerminal();
155
156    try {
157      term.start(
158        () => {},
159        () => {},
160        { kittyKeyboard: { reportAssociatedText: true } },
161      );
162      expect(term.output).toContain("\x1b[>25u");
163    } finally {
164      term.stop();
165      restoreIo();
166    }
167  });
168
169  for (const [signal, expectedStatus] of [
170    ["SIGINT", 130],
171    ["SIGTERM", 143],
172  ] as const) {
173    test(`${signal} restores terminal state and preserves signal termination`, async () => {
174      const result = await runSignalChild(signal);
175
176      expect(result.stderr).toBe("");
177      expect(result.stdout.endsWith(CLEANUP_SEQUENCE)).toBe(true);
178      expect(result.status).toBe(expectedStatus);
179      expect(result.signalCode).toBe(signal);
180    });
181
182    test(`${signal} still terminates when the application registered a listener`, async () => {
183      const result = await runSignalChild(signal, true);
184
185      expect(result.stderr).toBe("");
186      expect(result.stdout.endsWith(CLEANUP_SEQUENCE)).toBe(true);
187      expect(result.status).toBe(expectedStatus);
188      expect(result.signalCode).toBe(signal);
189    });
190  }
191
192  test("start and stop clean up crash listeners across repeated cycles", () => {
193    const restoreIo = patchProcessIo();
194    const term = new ProcessTerminal();
195    const beforeSigint = process.listenerCount("SIGINT");
196    const beforeSigterm = process.listenerCount("SIGTERM");
197    const beforeUncaught = process.listenerCount("uncaughtException");
198    const beforeUnhandled = process.listenerCount("unhandledRejection");
199
200    try {
201      term.start(
202        () => {},
203        () => {},
204      );
205      expect(process.listenerCount("uncaughtException")).toBe(
206        beforeUncaught + 1,
207      );
208      expect(process.listenerCount("unhandledRejection")).toBe(
209        beforeUnhandled + 1,
210      );
211      expect(process.listenerCount("SIGINT")).toBe(beforeSigint + 1);
212      expect(process.listenerCount("SIGTERM")).toBe(beforeSigterm + 1);
213
214      term.stop();
215      expect(process.listenerCount("SIGINT")).toBe(beforeSigint);
216      expect(process.listenerCount("SIGTERM")).toBe(beforeSigterm);
217      expect(process.listenerCount("uncaughtException")).toBe(beforeUncaught);
218      expect(process.listenerCount("unhandledRejection")).toBe(beforeUnhandled);
219
220      term.start(
221        () => {},
222        () => {},
223      );
224      expect(process.listenerCount("uncaughtException")).toBe(
225        beforeUncaught + 1,
226      );
227      expect(process.listenerCount("unhandledRejection")).toBe(
228        beforeUnhandled + 1,
229      );
230      expect(process.listenerCount("SIGINT")).toBe(beforeSigint + 1);
231      expect(process.listenerCount("SIGTERM")).toBe(beforeSigterm + 1);
232
233      term.stop();
234      expect(process.listenerCount("SIGINT")).toBe(beforeSigint);
235      expect(process.listenerCount("SIGTERM")).toBe(beforeSigterm);
236      expect(process.listenerCount("uncaughtException")).toBe(beforeUncaught);
237      expect(process.listenerCount("unhandledRejection")).toBe(beforeUnhandled);
238    } finally {
239      term.stop();
240      restoreIo();
241    }
242  });
243});