cURL Command Builder — JavaScript source
Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// curl-builder — structured input → copy-paste curl command + reverse parser.
// JavaScript port (canonical TS: src/lib/curl-builder.ts; Go twin:
// cli/curl-builder). Composes a copy-paste curl command from structured
// input; also parses an existing command back into the structure
// (round-trip). Values are single-quoted with embedded quotes escaped
// (' → '\'') — safe for POSIX shells. The flag order is fixed and
// deterministic: method (-X) → headers (-H, insertion order) → auth (-u) →
// data (-d) → boolean flags (-I -k -L --compressed) → the URL last.
// Never throws — errors travel in the result (`error: null` on success).
const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
/** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
function shellQuote(value) {
return `'${value.replace(/'/g, `'\\''`)}'`;
}
/** Build the curl command. URL required; method/header names validated. */
function buildCurlCommand(req) {
if (!req.url.trim()) return { command: '', error: 'A URL is required' };
if (!/^(https?:\/\/|\/|\$)/.test(req.url.trim())) {
return { command: '', error: 'URL must start with http://, https://, / or $ (a variable)' };
}
const method = (req.method ?? 'GET').toUpperCase();
if (!METHODS.has(method)) {
return {
command: '',
error: `unsupported method ${req.method} (use ${[...METHODS].join(', ')})`,
};
}
for (const h of req.headers) {
if (!/^[A-Za-z0-9-]+$/.test(h.key)) {
return {
command: '',
error: `invalid header name "${h.key}" (letters, digits and hyphens only)`,
};
}
}
const parts = ['curl'];
if (method !== 'GET') parts.push(`-X ${method}`);
for (const h of req.headers) parts.push(`-H ${shellQuote(`${h.key}: ${h.value}`)}`);
if (req.auth) parts.push(`-u ${shellQuote(`${req.auth.user}:${req.auth.password}`)}`);
if (req.data !== undefined && req.data !== '') parts.push(`-d ${shellQuote(req.data)}`);
if (req.headOnly) parts.push('-I');
if (req.insecure) parts.push('-k');
if (req.followRedirects) parts.push('-L');
if (req.compressed) parts.push('--compressed');
parts.push(shellQuote(req.url.trim()));
return { command: parts.join(' '), error: null };
}
/** Shell word-split respecting single and double quotes. */
function splitWords(line) {
const words = [];
let cur = '';
let quote = null;
let has = false;
for (const ch of line) {
if (quote) {
if (ch === quote) quote = null;
else cur += ch;
} else if (ch === "'" || ch === '"') {
quote = ch;
has = true;
} else if (ch === ' ' || ch === '\t') {
if (cur || has) words.push(cur);
cur = '';
has = false;
} else {
cur += ch;
has = true;
}
}
if (has) words.push(cur); // any accumulated characters imply has
return words;
}
/** Parse a curl command line back into a request (best effort, ordered). */
function parseCurlCommand(line) {
const trimmed = line.trim();
if (!trimmed) return { parsed: null, error: 'A command is required' };
const words = splitWords(trimmed.replace(/\\\n/g, ' '));
if (words[0] !== 'curl') return { parsed: null, error: 'command must start with curl' };
const req = { url: '', headers: [] };
const unknownFlags = [];
let i = 1;
for (; i < words.length; i++) {
const w = words[i];
if (w === '-X' || w === '--request') {
req.method = words[++i];
} else if (w === '-H' || w === '--header') {
const raw = words[++i];
const at = raw.indexOf(':');
if (at > 0) req.headers.push({ key: raw.slice(0, at).trim(), value: raw.slice(at + 1).trim() });
} else if (w === '-u' || w === '--user') {
const raw = words[++i];
const at = raw.indexOf(':');
req.auth = { user: at === -1 ? raw : raw.slice(0, at), password: at === -1 ? '' : raw.slice(at + 1) };
} else if (w === '-d' || w === '--data') {
req.data = words[++i];
} else if (w === '-I' || w === '--head') {
req.headOnly = true;
} else if (w === '-k' || w === '--insecure') {
req.insecure = true;
} else if (w === '-L' || w === '--location') {
req.followRedirects = true;
} else if (w === '--compressed') {
req.compressed = true;
} else if (w.startsWith('-')) {
unknownFlags.push(w);
} else {
req.url = w;
}
}
if (!req.url) return { parsed: null, error: 'no URL found in command' };
return { parsed: { request: req, unknownFlags }, error: null };
}
// Example:
// shellQuote("it's") → "'it'\\''s'"
// buildCurlCommand({ url: 'https://api.example.com', method: 'post',
// headers: [{ key: 'X-Tag', value: "it's" }], data: 'k=v' })
// → { command: "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'", error: null }
// parseCurlCommand("curl -sL --compressed 'https://x.dev'")
// → { parsed: { request: { url: 'https://x.dev', headers: [], compressed: true }, unknownFlags: ['-sL'] }, error: null }
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →