
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="39b74749-67c4-57b0-b495-dbcf401f2edb")}catch(e){}}();
import * as pty from "node-pty";
const MAX_HISTORY_BYTES = 1024 * 1024;
const WINDOWS_CMD_META_CHARS_REGEXP = /([()\][%!^"`<>&|;, *?])/g;
function normalizeOutputChunk(data) {
    if (typeof data === "string") {
        return Buffer.from(data, "utf8");
    }
    return Buffer.isBuffer(data) ? data : Buffer.from(data);
}
function isIgnorablePtyWriteError(error) {
    if (!(error instanceof Error)) {
        return false;
    }
    const code = error.code;
    return code === "EIO" || code === "EBADF";
}
function terminatePtyProcess(ptyProcess) {
    const pid = ptyProcess.pid;
    ptyProcess.kill();
    if (process.platform !== "win32" && Number.isFinite(pid) && pid > 0) {
        try {
            process.kill(-pid, "SIGTERM");
        }
        catch {
            // Best effort: process group may already be gone or inaccessible.
        }
    }
}
function resolveWindowsComSpec() {
    const comSpec = process.env.ComSpec?.trim() || process.env.COMSPEC?.trim();
    return comSpec || "cmd.exe";
}
function escapeWindowsCommand(value) {
    return value.replace(WINDOWS_CMD_META_CHARS_REGEXP, "^$1");
}
function normalizeWindowsCmdArgument(value) {
    return value.replaceAll("\r\n", "\n").replaceAll("\r", "\n").replaceAll("\n", "\\n");
}
function escapeWindowsArgument(value) {
    let escaped = normalizeWindowsCmdArgument(`${value}`);
    escaped = escaped.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
    escaped = escaped.replace(/(?=(\\+?)?)\1$/g, "$1$1");
    escaped = `"${escaped}"`;
    escaped = escaped.replace(WINDOWS_CMD_META_CHARS_REGEXP, "^$1");
    return escaped;
}
function buildWindowsCmdArgsCommandLine(binary, args) {
    const escapedCommand = escapeWindowsCommand(binary);
    const escapedArgs = args.map((part) => escapeWindowsArgument(part));
    const shellCommand = [escapedCommand, ...escapedArgs].join(" ");
    return `/d /s /c "${shellCommand}"`;
}
function shouldUseWindowsShellLaunch(binary) {
    if (process.platform !== "win32") {
        return false;
    }
    const normalized = binary.trim().toLowerCase();
    if (!normalized) {
        return false;
    }
    if (normalized === "cmd" || normalized === "cmd.exe") {
        return false;
    }
    return normalized !== resolveWindowsComSpec().toLowerCase();
}
export class PtySession {
    onDataCallback;
    onExitCallback;
    ptyProcess;
    outputHistory = [];
    historyBytes = 0;
    interrupted = false;
    constructor(ptyProcess, onDataCallback, onExitCallback) {
        this.onDataCallback = onDataCallback;
        this.onExitCallback = onExitCallback;
        this.ptyProcess = ptyProcess;
        this.ptyProcess.onData((data) => {
            const chunk = normalizeOutputChunk(data);
            this.outputHistory.push(chunk);
            this.historyBytes += chunk.byteLength;
            while (this.historyBytes > MAX_HISTORY_BYTES && this.outputHistory.length > 0) {
                const shifted = this.outputHistory.shift();
                if (!shifted) {
                    break;
                }
                this.historyBytes -= shifted.byteLength;
            }
            this.onDataCallback?.(chunk);
        });
        this.ptyProcess.onExit((event) => {
            this.onExitCallback?.(event);
        });
    }
    static spawn({ binary, args = [], cwd, env, cols, rows, onData, onExit }) {
        const normalizedArgs = typeof args === "string" ? [args] : args;
        const terminalName = env?.TERM?.trim() || process.env.TERM?.trim() || "xterm-256color";
        const useWindowsShellLaunch = shouldUseWindowsShellLaunch(binary);
        const spawnBinary = useWindowsShellLaunch ? resolveWindowsComSpec() : binary;
        const spawnArgs = useWindowsShellLaunch
            ? buildWindowsCmdArgsCommandLine(binary, normalizedArgs)
            : normalizedArgs;
        const ptyOptions = {
            name: terminalName,
            cwd,
            env,
            cols,
            rows,
            encoding: null,
        };
        const ptyProcess = pty.spawn(spawnBinary, spawnArgs, ptyOptions);
        return new PtySession(ptyProcess, onData, onExit);
    }
    get pid() {
        return this.ptyProcess.pid;
    }
    getOutputHistory() {
        return this.outputHistory;
    }
    write(data) {
        try {
            this.ptyProcess.write(typeof data === "string" ? data : data.toString("utf8"));
        }
        catch (error) {
            if (isIgnorablePtyWriteError(error)) {
                return;
            }
            throw error;
        }
    }
    resize(cols, rows, pixelWidth, pixelHeight) {
        if (pixelWidth !== undefined && pixelHeight !== undefined) {
            this.ptyProcess.resize(cols, rows, {
                width: pixelWidth,
                height: pixelHeight,
            });
            return;
        }
        this.ptyProcess.resize(cols, rows);
    }
    pause() {
        this.ptyProcess.pause();
    }
    resume() {
        this.ptyProcess.resume();
    }
    stop(options) {
        if (options?.interrupted) {
            this.interrupted = true;
        }
        terminatePtyProcess(this.ptyProcess);
    }
    wasInterrupted() {
        return this.interrupted;
    }
}
//# sourceMappingURL=pty-session.js.map
//# debugId=39b74749-67c4-57b0-b495-dbcf401f2edb
