Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Runs before the Effect runtime starts, on raw file descriptors.
2import * as NodeFS from "node:fs";
3import * as NodeTty from "node:tty";
4
5import * as HostProcess from "@t3tools/shared/HostProcess";
6
7/**
8 * Electron's Windows executable is a GUI program, so `t3.cmd` under
9 * `ELECTRON_RUN_AS_NODE` gets the console for stdout and stderr but no stdin.
10 * Piped or redirected input and runs whose output is not a console are left alone.
11 */
12function needsConsoleStdin(input: {
13 readonly platform: NodeJS.Platform;
14 readonly env: NodeJS.ProcessEnv;
15 readonly stdinOpen: boolean;
16 readonly stdoutIsConsole: boolean;
17}): boolean {
18 return (
19 input.platform === "win32" &&
20 // Set only by the launcher (DesktopCliShim), never for the desktop backend.
21 input.env.T3CODE_DESKTOP_CLI_LAUNCHER === "1" &&
22 !input.stdinOpen &&
23 input.stdoutIsConsole
24 );
25}
26
27const isOpen = (fd: number) => {
28 try {
29 NodeFS.fstatSync(fd);
30 return true;
31 } catch {
32 return false;
33 }
34};
35
36/** Call before reading process.stdin. Returns the reopened fd for children, or undefined without changing stdin. */
37export function attachConsoleStdin(): number | undefined {
38 const needed = needsConsoleStdin({
39 platform: HostProcess.Platform.defaultValue(),
40 env: process.env,
41 stdinOpen: isOpen(0),
42 stdoutIsConsole: NodeTty.isatty(1),
43 });
44 // The launcher marker must not propagate to child shells or t3 processes.
45 delete process.env.T3CODE_DESKTOP_CLI_LAUNCHER;
46 if (!needed) return undefined;
47 let fd: number;
48 try {
49 fd = NodeFS.openSync("\\\\.\\CONIN$", "r+");
50 } catch {
51 return undefined;
52 }
53 if (!NodeTty.isatty(fd)) {
54 NodeFS.closeSync(fd);
55 return undefined;
56 }
57 const stdin = new NodeTty.ReadStream(fd);
58 Object.defineProperty(process, "stdin", { value: stdin, configurable: true, enumerable: true });
59 consoleStdinFd = fd;
60 return fd;
61}
62
63let consoleStdinFd: number | undefined;
64
65export const interactiveStdin = (): number | "inherit" => consoleStdinFd ?? "inherit";