import {
  PtyAdapter
} from "./index-gzh4v9tz.js";
import"./index-y24mzzdg.js";
import {
  exports_Effect,
  exports_Layer
} from "./index-w9j14fjm.js";
import"./index-sdksp5px.js";

// src/terminal/Layers/BunPTY.ts
class BunPtyProcess {
  process;
  dataListeners = new Set;
  exitListeners = new Set;
  decoder = new TextDecoder;
  didExit = false;
  constructor(process2) {
    this.process = process2;
    this.process.exited.then((exitCode) => {
      this.emitExit({
        exitCode: Number.isInteger(exitCode) ? exitCode : 0,
        signal: typeof this.process.signalCode === "number" ? this.process.signalCode : null
      });
    }).catch(() => {
      this.emitExit({ exitCode: 1, signal: null });
    });
  }
  get pid() {
    return this.process.pid;
  }
  write(data) {
    if (!this.process.terminal) {
      throw new Error("Bun PTY terminal handle is unavailable");
    }
    this.process.terminal.write(data);
  }
  resize(cols, rows) {
    if (!this.process.terminal?.resize) {
      throw new Error("Bun PTY resize is unavailable");
    }
    this.process.terminal.resize(cols, rows);
  }
  kill(signal) {
    if (!signal) {
      this.process.kill();
      return;
    }
    this.process.kill(signal);
  }
  onData(callback) {
    this.dataListeners.add(callback);
    return () => {
      this.dataListeners.delete(callback);
    };
  }
  onExit(callback) {
    this.exitListeners.add(callback);
    return () => {
      this.exitListeners.delete(callback);
    };
  }
  emitData(data) {
    if (this.didExit)
      return;
    const text = this.decoder.decode(data, { stream: true });
    if (text.length === 0)
      return;
    for (const listener of this.dataListeners) {
      listener(text);
    }
  }
  emitExit(event) {
    if (this.didExit)
      return;
    this.didExit = true;
    const remainder = this.decoder.decode();
    if (remainder.length > 0) {
      for (const listener of this.dataListeners) {
        listener(remainder);
      }
    }
    for (const listener of this.exitListeners) {
      listener(event);
    }
  }
}
var layer = exports_Layer.effect(PtyAdapter, exports_Effect.gen(function* () {
  if (process.platform === "win32") {
    return yield* exports_Effect.die("Bun PTY terminal support is unavailable on Windows. Please use Node.js (e.g. by running `npx t3`) instead.");
  }
  return {
    spawn: (input) => exports_Effect.sync(() => {
      let processHandle = null;
      const command = [input.shell, ...input.args ?? []];
      const subprocess = Bun.spawn(command, {
        cwd: input.cwd,
        env: input.env,
        terminal: {
          cols: input.cols,
          rows: input.rows,
          data: (_terminal, data) => {
            processHandle?.emitData(data);
          }
        }
      });
      processHandle = new BunPtyProcess(subprocess);
      return processHandle;
    })
  };
}));
export {
  layer
};
