import {
  shellEscape
} from "../chunk-H26LNIXA.js";
import {
  readEnvOrSetting
} from "../chunk-2MAQ6JFL.js";
import "../chunk-HFDLUBWN.js";
import "../chunk-RII4M3J2.js";
import "../chunk-DDJOPRB7.js";
import "../chunk-TLEKKGH7.js";
import "../chunk-KBM3MISV.js";
import "../chunk-2ESYSVXG.js";

// src/providers/vercel.ts
var SandboxClass = null;
async function loadSdk() {
  if (SandboxClass) return SandboxClass;
  try {
    const mod = await import("../dist-3ZD3ELTH.js");
    SandboxClass = mod.Sandbox ?? mod.default;
    if (!SandboxClass?.create) {
      throw new Error("Sandbox.create not found in @vercel/sandbox exports");
    }
    return SandboxClass;
  } catch (err) {
    if (err instanceof Error && (err.message.includes("Cannot find module") || err.message.includes("MODULE_NOT_FOUND") || err.message.includes("ERR_MODULE_NOT_FOUND"))) {
      throw new Error(
        "Vercel provider requires the @vercel/sandbox package. Install it with: npm install @vercel/sandbox"
      );
    }
    throw err;
  }
}
var g = globalThis;
if (!g.__caVercelSandboxes) g.__caVercelSandboxes = /* @__PURE__ */ new Map();
var sandboxes = g.__caVercelSandboxes;
var vercelProvider = {
  name: "vercel",
  stripControlChars: false,
  async checkAvailability(secrets) {
    try {
      await loadSdk();
    } catch {
      return { available: false, message: "Vercel Sandbox requires the @vercel/sandbox package. Install with: npm install @vercel/sandbox" };
    }
    const hasToken = secrets?.VERCEL_TOKEN ?? readEnvOrSetting("VERCEL_TOKEN");
    const hasOidc = process.env.VERCEL_OIDC_TOKEN;
    if (!hasToken && !hasOidc) {
      return { available: false, message: "VERCEL_TOKEN required \u2014 add to vault or .env (or set VERCEL_OIDC_TOKEN)" };
    }
    return { available: true };
  },
  async create({ name, secrets }) {
    const Sandbox = await loadSdk();
    const runtime = process.env.VERCEL_SANDBOX_RUNTIME ?? "node24";
    const sandbox = await Sandbox.create({
      runtime,
      token: secrets?.VERCEL_TOKEN ?? readEnvOrSetting("VERCEL_TOKEN"),
      teamId: secrets?.VERCEL_TEAM_ID ?? readEnvOrSetting("VERCEL_TEAM_ID"),
      projectId: secrets?.VERCEL_PROJECT_ID ?? readEnvOrSetting("VERCEL_PROJECT_ID")
    });
    sandboxes.set(name, sandbox);
  },
  async delete(name) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) return;
    try {
      await sandbox.stop();
    } catch {
    }
    sandboxes.delete(name);
  },
  async list(opts) {
    const prefix = opts?.prefix ?? "ca-sess-";
    return Array.from(sandboxes.keys()).filter((n) => n.startsWith(prefix)).map((name) => ({ name }));
  },
  async exec(name, argv, opts) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) throw new Error(`Vercel sandbox not found: ${name}`);
    const cmd = argv.map((a) => shellEscape(a)).join(" ");
    if (opts?.stdin) {
      const stdinPath = `/tmp/_stdin_${Date.now()}_${Math.random().toString(36).slice(2)}`;
      await sandbox.writeFiles([{ path: stdinPath, content: opts.stdin }]);
      const result2 = await sandbox.runCommand("bash", [
        "-c",
        `cat ${shellEscape(stdinPath)} | ${cmd} ; rm -f ${shellEscape(stdinPath)}`
      ]);
      return {
        stdout: await result2.stdout(),
        stderr: await result2.stderr(),
        exit_code: result2.exitCode
      };
    }
    const result = await sandbox.runCommand("bash", ["-c", cmd]);
    return {
      stdout: await result.stdout(),
      stderr: await result.stderr(),
      exit_code: result.exitCode
    };
  },
  async startExec(name, opts) {
    const sandbox = sandboxes.get(name);
    if (!sandbox) throw new Error(`Vercel sandbox not found: ${name}`);
    const cmd = opts.argv.map((a) => shellEscape(a)).join(" ");
    let stdinPath;
    if (opts.stdin) {
      stdinPath = `/tmp/_stdin_${Date.now()}_${Math.random().toString(36).slice(2)}`;
      await sandbox.writeFiles([{ path: stdinPath, content: opts.stdin }]);
    }
    const fullCmd = stdinPath ? `cat ${shellEscape(stdinPath)} | ${cmd} ; rm -f ${shellEscape(stdinPath)}` : cmd;
    const encoder = new TextEncoder();
    let streamController;
    const stdout = new ReadableStream({
      start(controller) {
        streamController = controller;
      }
    });
    const resultPromise = sandbox.runCommand("bash", ["-c", fullCmd]);
    const exit = resultPromise.then(async (result) => {
      try {
        const out = await result.stdout();
        streamController.enqueue(encoder.encode(out));
        streamController.close();
      } catch {
      }
      return { code: result.exitCode };
    }).catch((err) => {
      try {
        streamController.error(err);
      } catch {
      }
      throw err;
    });
    return {
      stdout,
      exit,
      async kill() {
      }
    };
  }
};
export {
  vercelProvider
};
