Skip to content

cURL Command Builder — TypeScript 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 TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the cURL Command Builder (slug: 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
// below is fixed and deterministic (documented; the Go twin reproduces it):
// method (-X) → headers (-H, insertion order) → auth (-u) → data (-d) →
// then the boolean flags (-I -k -L --compressed) → the URL last.
export interface CurlRequest {
  url: string;
  method?: string;
  headers: Array<{ key: string; value: string }>;
  data?: string;
  auth?: { user: string; password: string };
  headOnly?: boolean;
  insecure?: boolean;
  followRedirects?: boolean;
  compressed?: boolean;
}

export type CurlBuildResult =
  | { command: string; error: null }
  | { command: ''; error: string };

export interface ParsedCurl {
  request: CurlRequest;
  /** Flags the parser does not model, kept verbatim for the round trip. */
  unknownFlags: string[];
}

export type CurlParseResult =
  | { parsed: ParsedCurl; error: null }
  | { parsed: null; error: string };

const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);

/** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
export function shellQuote(value: string): string {
  return `'${value.replace(/'/g, `'\\''`)}'`;
}

/** Build the curl command. URL required; method/header names validated. */
export function buildCurlCommand(req: CurlRequest): CurlBuildResult {
  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: string[] = ['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: string): string[] {
  const words: string[] = [];
  let cur = '';
  let quote: string | null = null;
  let has = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    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;
}

const FLAG_KEYS = new Set(['-X', '-H', '-u', '-d', '--user', '--data', '--header', '--request']);
const BOOL_FLAGS = new Set(['-I', '-k', '-L', '--compressed', '--head', '--insecure', '--location']);

/** Parse a curl command line back into a request (best effort, ordered). */
export function parseCurlCommand(line: string): CurlParseResult {
  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: CurlRequest = { url: '', headers: [] };
  const unknownFlags: string[] = [];
  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 };
}

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 →