import {
  getConfig
} 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 {
  ApiError
} from "../chunk-EZYKRG4W.js";
import "../chunk-2ESYSVXG.js";

// src/providers/cloudflare.ts
function resolveConfig(secrets) {
  const cfg = getConfig();
  const url = secrets?.CLOUDFLARE_SANDBOX_URL ?? process.env.CLOUDFLARE_SANDBOX_URL ?? cfg.cloudflareSandboxUrl;
  const secret = secrets?.CLOUDFLARE_SANDBOX_SECRET ?? process.env.CLOUDFLARE_SANDBOX_SECRET ?? "";
  if (!url) throw new Error("CLOUDFLARE_SANDBOX_URL required \u2014 set in .env or vault");
  return { url: url.replace(/\/$/, ""), secret };
}
async function cfFetch(path, opts) {
  const { url, secret } = resolveConfig(opts.secrets);
  const res = await fetch(`${url}${path}`, {
    method: opts.method ?? "GET",
    headers: {
      "Content-Type": "application/json",
      ...secret ? { Authorization: `Bearer ${secret}` } : {}
    },
    body: opts.body ? JSON.stringify(opts.body) : void 0,
    signal: AbortSignal.timeout(opts.timeoutMs ?? 6e4)
  });
  return res;
}
async function cfJson(path, opts) {
  const res = await cfFetch(path, opts);
  if (!res.ok) {
    const text = await res.text().catch(() => "");
    throw new ApiError(
      res.status >= 500 ? 502 : 500,
      "server_error",
      `cloudflare ${opts.method ?? "GET"} ${path} failed (${res.status}): ${text.slice(0, 300)}`
    );
  }
  return await res.json();
}
var cloudflareProvider = {
  name: "cloudflare",
  stripControlChars: false,
  supportsWarmPool: true,
  async checkAvailability(secrets) {
    try {
      const { url } = resolveConfig(secrets);
      const res = await fetch(`${url}/health`, {
        signal: AbortSignal.timeout(5e3)
      });
      if (res.ok) return { available: true };
      return { available: false, message: `Cloudflare bridge health check failed: ${res.status}` };
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg.includes("CLOUDFLARE_SANDBOX_URL required")) {
        return { available: false, message: "CLOUDFLARE_SANDBOX_URL required \u2014 set in .env or vault" };
      }
      return { available: false, message: `Cloudflare bridge unreachable: ${msg}` };
    }
  },
  async create({ name, secrets }) {
    await cfJson("/sandboxes", {
      method: "POST",
      body: { name },
      secrets,
      timeoutMs: 12e4
    });
  },
  async delete(name, secrets) {
    await cfFetch(`/sandboxes/${encodeURIComponent(name)}`, {
      method: "DELETE",
      secrets
    }).catch(() => {
    });
  },
  async list(opts) {
    const prefix = opts?.prefix ?? "ca-sess-";
    const result = await cfJson("/sandboxes", {
      secrets: void 0
    });
    return result.sandboxes.filter((s) => s.name.startsWith(prefix));
  },
  async exec(name, argv, opts) {
    return cfJson(
      `/sandboxes/${encodeURIComponent(name)}/exec`,
      {
        method: "POST",
        body: { argv, stdin: opts?.stdin, timeoutMs: opts?.timeoutMs },
        secrets: opts?.secrets,
        timeoutMs: (opts?.timeoutMs ?? 12e4) + 5e3
        // HTTP timeout slightly longer than exec timeout
      }
    );
  },
  async startExec(name, opts) {
    const { url, secret } = resolveConfig(opts.secrets);
    const res = await fetch(`${url}/sandboxes/${encodeURIComponent(name)}/stream`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...secret ? { Authorization: `Bearer ${secret}` } : {}
      },
      body: JSON.stringify({
        argv: opts.argv,
        stdin: opts.stdin,
        timeoutMs: opts.timeoutMs
      }),
      signal: opts.signal ?? AbortSignal.timeout(opts.timeoutMs ?? 6e5)
    });
    if (!res.ok) {
      const text = await res.text().catch(() => "");
      throw new ApiError(502, "server_error", `cloudflare stream exec failed (${res.status}): ${text.slice(0, 300)}`);
    }
    const stdout = res.body;
    let exitResolve;
    const exit = new Promise((resolve) => {
      exitResolve = resolve;
    });
    const [streamForConsumer, streamForMonitor] = stdout.tee();
    (async () => {
      const reader = streamForMonitor.getReader();
      try {
        while (true) {
          const { done } = await reader.read();
          if (done) break;
        }
      } catch {
      }
      exitResolve({ code: 0 });
    })();
    return {
      stdout: streamForConsumer,
      exit,
      async kill() {
        await cfFetch(`/sandboxes/${encodeURIComponent(name)}/kill`, {
          method: "POST",
          secrets: opts.secrets
        }).catch(() => {
        });
      }
    };
  }
};
export {
  cloudflareProvider
};
