import { v as validateAuth } from './auth-DeCdZ83n.js';
import { p as ptyManager } from './pty-manager-DR0Wt2Ac.js';
import { t as toErrorMessage } from './error-DDXB3duW.js';
import { j as json } from './shared-server-sSGG17Df.js';
import { realpathSync, statSync } from 'fs';
import { basename } from 'path';
import 'crypto';
import 'child_process';
import 'url';
import 'net';
import 'better-sqlite3';

const ALLOWED_COMMANDS = ["zsh", "bash", "sh", "fish", "claude", "opencode"];
const GET = ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  try {
    const terminals = ptyManager.list().map((t) => ({
      args: t.args,
      clientCount: t.clients.size,
      command: t.command,
      createdAt: t.createdAt.toISOString(),
      currentCwd: t.currentCwd,
      cwd: t.cwd,
      exitCode: t.exitCode,
      exitedAt: t.exitedAt?.toISOString() ?? null,
      id: t.id,
      isActive: t.isActive,
      pid: t.pid,
      status: t.status
    }));
    return json({
      count: terminals.length,
      terminals,
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    });
  } catch (error) {
    console.error("[terminals] Failed to list terminals:", toErrorMessage(error));
    return json({ error: "Failed to list terminals" }, { status: 500 });
  }
};
const POST = async ({ request }) => {
  const authError = validateAuth(request);
  if (authError) {
    return authError;
  }
  let body;
  try {
    body = await request.json();
  } catch {
    return json({ error: "Invalid JSON in request body" }, { status: 400 });
  }
  try {
    const { args, cols, command, cwd, rows } = body;
    if (!command) {
      return json({ error: "command is required" }, { status: 400 });
    }
    const commandBasename = basename(command);
    if (!ALLOWED_COMMANDS.includes(commandBasename)) {
      return json(
        { error: `Command not allowed. Allowed: ${ALLOWED_COMMANDS.join(", ")}` },
        { status: 400 }
      );
    }
    if (!cwd) {
      return json({ error: "cwd is required" }, { status: 400 });
    }
    let realCwd;
    try {
      realCwd = realpathSync(cwd);
    } catch {
      return json({ error: "Invalid working directory" }, { status: 400 });
    }
    if (!statSync(realCwd).isDirectory()) {
      return json({ error: "Invalid working directory" }, { status: 400 });
    }
    const home = process.env.HOME || "";
    if (home && !realCwd.startsWith(home)) {
      return json({ error: "Working directory must be under home directory" }, { status: 400 });
    }
    if (args !== void 0 && !Array.isArray(args)) {
      return json({ error: "args must be an array of strings" }, { status: 400 });
    }
    if (args && !args.every((a) => typeof a === "string")) {
      return json({ error: "All args must be strings" }, { status: 400 });
    }
    if (cols !== void 0 && (typeof cols !== "number" || cols < 1)) {
      return json({ error: "cols must be a positive number" }, { status: 400 });
    }
    if (rows !== void 0 && (typeof rows !== "number" || rows < 1)) {
      return json({ error: "rows must be a positive number" }, { status: 400 });
    }
    const terminal = await ptyManager.create(command, args ?? [], realCwd, cols ?? 80, rows ?? 24);
    console.log(
      `[terminals] Created terminal ${terminal.id} (pid=${terminal.pid}, command=${command})`
    );
    return json(
      {
        command: terminal.command,
        createdAt: terminal.createdAt,
        cwd: terminal.cwd,
        id: terminal.id,
        pid: terminal.pid,
        sessionWs: `/ws/session/${terminal.id}`,
        ws: `/ws/terminal/${terminal.id}`
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("[terminals] Failed to create terminal:", toErrorMessage(error));
    return json({ error: "Failed to create terminal" }, { status: 500 });
  }
};

export { GET, POST };
//# sourceMappingURL=_server.ts-CS5H5klP.js.map
