Open History to see the last commit
1/// <reference types="bun" />
2
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
7
8import * as PtyAdapter from "./PtyAdapter.ts";
9
10export class BunPtyUnsupportedPlatformError extends Schema.TaggedError<BunPtyUnsupportedPlatformError>()(
11 "BunPtyUnsupportedPlatformError",
12 {
13 platform: Schema.Literal("win32"),
14 },
15) {
16 override get message(): string {
17 return `Bun PTY terminal support is unavailable on ${this.platform}. Please use Node.js (e.g. by running \`npx t3\`) instead.`;
18 }
19}
20
21export class BunPtyOperationUnavailableError extends Schema.TaggedError<BunPtyOperationUnavailableError>()(
22 "BunPtyOperationUnavailableError",
23 {
24 operation: Schema.Literals(["write", "resize"]),
25 pid: Schema.Number,
26 },
27) {
28 override get message(): string {
29 return `Bun PTY ${this.operation} is unavailable for process ${this.pid}.`;
30 }
31}
32
33class BunPtyProcess implements PtyAdapter.PtyProcess {
34 private readonly dataListeners = new Set<(data: string) => void>();
35 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
36 private readonly decoder = new TextDecoder();
37 private readonly process: Bun.Subprocess;
38 private didExit = false;
39
40 constructor(process: Bun.Subprocess) {
41 this.process = process;
42 void this.process.exited
43 .then((exitCode) => {
44 this.emitExit({
45 exitCode: Number.isInteger(exitCode) ? exitCode : 0,
46 signal: typeof this.process.signalCode === "number" ? this.process.signalCode : null,
47 });
48 })
49 .catch(() => {
50 this.emitExit({ exitCode: 1, signal: null });
51 });
52 }
53
54 get pid(): number {
55 return this.process.pid;
56 }
57
58 write(data: string): void {
59 if (!this.process.terminal) {
60 throw new BunPtyOperationUnavailableError({ operation: "write", pid: this.pid });
61 }
62 this.process.terminal.write(data);
63 }
64
65 resize(cols: number, rows: number): void {
66 if (!this.process.terminal?.resize) {
67 throw new BunPtyOperationUnavailableError({ operation: "resize", pid: this.pid });
68 }
69 this.process.terminal.resize(cols, rows);
70 }
71
72 kill(signal?: string): void {
73 if (!signal) {
74 this.process.kill();
75 return;
76 }
77 this.process.kill(signal as NodeJS.Signals);
78 }
79
80 onData(callback: (data: string) => void): () => void {
81 this.dataListeners.add(callback);
82 return () => {
83 this.dataListeners.delete(callback);
84 };
85 }
86
87 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
88 this.exitListeners.add(callback);
89 return () => {
90 this.exitListeners.delete(callback);
91 };
92 }
93
94 emitData(data: Uint8Array): void {
95 if (this.didExit) return;
96 const text = this.decoder.decode(data, { stream: true });
97 if (text.length === 0) return;
98 for (const listener of this.dataListeners) {
99 listener(text);
100 }
101 }
102
103 private emitExit(event: PtyAdapter.PtyExitEvent): void {
104 if (this.didExit) return;
105 this.didExit = true;
106
107 const remainder = this.decoder.decode();
108 if (remainder.length > 0) {
109 for (const listener of this.dataListeners) {
110 listener(remainder);
111 }
112 }
113
114 for (const listener of this.exitListeners) {
115 listener(event);
116 }
117 }
118}
119
120export const make = Effect.fn("BunPtyAdapter.make")(function* () {
121 const platform = yield* HostProcessPlatform;
122 if (platform === "win32") {
123 return yield* Effect.die(new BunPtyUnsupportedPlatformError({ platform }));
124 }
125 return PtyAdapter.PtyAdapter.of({
126 spawn: (input) =>
127 Effect.try({
128 try: () => {
129 let processHandle: BunPtyProcess | null = null;
130 const command = [input.shell, ...(input.args ?? [])];
131 const subprocess = Bun.spawn(command, {
132 cwd: input.cwd,
133 env: input.env,
134 terminal: {
135 cols: input.cols,
136 rows: input.rows,
137 data: (_terminal, data) => {
138 processHandle?.emitData(data);
139 },
140 },
141 });
142 processHandle = new BunPtyProcess(subprocess);
143 return processHandle;
144 },
145 catch: (cause) =>
146 new PtyAdapter.PtySpawnError({
147 adapter: "bun",
148 shell: input.shell,
149 cause,
150 }),
151 }),
152 });
153});
154
155export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());