function http_fetch_spawn(argv) { if (typeof Bun !== "undefined" && typeof Bun.spawnSync === "function") { const r = Bun.spawnSync({ cmd: argv, stdout: "pipe", stderr: "pipe", }); const dec = new TextDecoder(); return { status: r.exitCode ?? 1, stdout: dec.decode(r.stdout ?? new Uint8Array()), stderr: dec.decode(r.stderr ?? new Uint8Array()), }; } const { spawnSync } = require("node:child_process"); const r = spawnSync(argv[0], argv.slice(1), { encoding: "utf8" }); return { status: r.status == null ? 1 : r.status, stdout: r.stdout || "", stderr: r.stderr || "", }; } function http_fetch_status(hdr) { let status = 0; const lines = String(hdr).split(/\r?\n/); for (const line of lines) { if (line.indexOf("HTTP/") === 0) { const parts = line.split(" "); if (parts.length > 1) { status = Number(parts[1]) >>> 0; } } } return status; } function http_fetch(method, url, headers, body) { const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const dir = os.tmpdir(); const id = String(Date.now()) + "-" + String(Math.random()).slice(2); const hdrPath = path.join(dir, "bend-http-h-" + id); const outPath = path.join(dir, "bend-http-b-" + id); const inPath = path.join(dir, "bend-http-i-" + id); const argv = [ "curl", "-sS", "--max-time", "30", "-D", hdrPath, "-o", outPath, "-X", method, ]; String(headers).split("\n").forEach((line) => { if (line) { argv.push("-H", line); } }); if (body) { fs.writeFileSync(inPath, body); argv.push("--data-binary", "@" + inPath); } argv.push("--url", url); try { const r = http_fetch_spawn(argv); if (r.status === 127) { return io_fail(2); } if (r.status !== 0) { return io_fail(5); } const hdr = fs.existsSync(hdrPath) ? fs.readFileSync(hdrPath, "utf8") : ""; const out = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : ""; return io_done(io_tup(http_fetch_status(hdr), hdr, out)); } catch (e) { return io_fail(5); } finally { try { fs.unlinkSync(hdrPath); } catch (_) {} try { fs.unlinkSync(outPath); } catch (_) {} try { fs.unlinkSync(inPath); } catch (_) {} } }