npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

sweet-curl-parser

v1.0.4

Published

A comprehensive TypeScript library for parsing curl commands into structured JavaScript objects.

Readme

Curl Command Parser

A TypeScript library that parses curl commands into structured JavaScript objects.

Features

  • Parse curl commands into structured data
  • Extract URLs, headers, authentication, request bodies, and more
  • Full TypeScript support
  • Comprehensive error handling

Installation

npm i sweet-curl-parser

Quick Start

import { parseCurl } from 'sweet-curl-parser';

const result = parseCurl(`
  curl -X POST https://api.example.com/users \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer token123" \
    -d '{"name": "john", "email": "[email protected]"}'
`);

if (result.success) {
  console.log('Method:', result.data.method); // "POST"
  console.log('URL:', result.data.url.host); // "api.example.com"
  console.log('Headers:', result.data.headers);
} else {
  console.error('Errors:', result.errors);
}

// API Key authentication example
const apiResult = parseCurl(`
  curl --api-key abc123 https://api.example.com/data
`);

if (apiResult.success) {
  console.log('Auth type:', apiResult.data.authentication?.type); // "api-key"
  console.log('API Key:', apiResult.data.authentication?.token); // "abc123"
}

Output Structure

The parser returns a ParserResult object with the following structure:

Success Response

{
  success: true,
  data: {
    method: string,                    // HTTP method (GET, POST, PUT, etc.)
    url: {
      protocol: string,                // "http" or "https"
      host: string,                    // Domain name
      port?: number,                   // Port number if specified
      path: string,                    // URL path
      queryParams: Array<{             // Query parameters
        key: string,
        value: string
      }>,
      fullUrl: string                  // Complete URL
    },
    headers: Array<{                   // HTTP headers
      name: string,
      value: string
    }>,
    body?: {                           // Request body (if present)
      type: 'raw' | 'json' | 'form' | 'file',
      content: string,
      parsed?: any                     // Parsed JSON if type is 'json'
    },
    authentication?: {                 // Authentication details
      type: 'basic' | 'bearer' | 'digest' | 'api-key' | 'oauth',
      username?: string,
      password?: string,
      token?: string,
      credentials?: string
    },
    ssl: {                            // SSL/TLS configuration
      insecure: boolean,
      cert?: string,
      key?: string,
      cacert?: string
    },
    proxy?: {                         // Proxy configuration
      url: string,
      username?: string,
      password?: string
    },
    cookies?: Array<{                 // Cookies
      name: string,
      value: string
    }>,
    timeout: {                        // Timeout settings
      connect?: number,
      max?: number
    },
    retry: {                          // Retry configuration
      count?: number,
      delay?: number
    },
    output: {                         // Output options
      verbose: boolean,
      silent: boolean,
      showError: boolean,
      failOnError: boolean,
      includeHeaders: boolean,
      progressBar: boolean,
      file?: string
    },
    compression: {                    // Compression settings
      compressed: boolean,
      encoding?: string
    },
    followRedirects: boolean,         // Follow redirects
    maxRedirects?: number,            // Maximum redirects
    raw: string                       // Original curl command
  }
}

Error Response

{
  success: false,
  errors: Array<{                     // Array of parsing errors
    message: string,
    code?: string
  }>,
  warnings?: string[]                 // Non-fatal warnings
}

Example Output

const result = parseCurl(`
  curl -X POST https://api.example.com:8080/users?active=true \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer abc123" \
    -d '{"name": "John Doe", "email": "[email protected]"}' \
    --insecure \
    --connect-timeout 30
`);

// Result:
{
  success: true,
  data: {
    method: "POST",
    url: {
      protocol: "https",
      host: "api.example.com",
      port: 8080,
      path: "/users",
      queryParams: [{ key: "active", value: "true" }],
      fullUrl: "https://api.example.com:8080/users?active=true"
    },
    headers: [
      { name: "Content-Type", value: "application/json" },
      { name: "Authorization", value: "Bearer abc123" }
    ],
    body: {
      type: "json",
      content: '{"name": "John Doe", "email": "[email protected]"}',
      parsed: { name: "John Doe", email: "[email protected]" }
    },
    authentication: {
      type: "bearer",
      token: "abc123"
    },
    ssl: {
      insecure: true
    },
    timeout: {
      connect: 30
    },
    // ... other fields with default values
  }
}

Supported Options

  • HTTP methods (-X, --request)
  • Headers (-H, --header)
  • Request data (-d, --data, --json)
  • Authentication (-u, --user, --oauth2-bearer, --api-key)
  • SSL/TLS (-k, --insecure, --cert)
  • Proxy (-x, --proxy)
  • Cookies (-b, --cookie)
  • And many more...

Parser Options

You can customize the parser behavior by passing options:

import { parseCurl } from 'sweet-curl-parser';

const options = {
  strict: true,           // Strict parsing mode (default: false)
  throwOnError: true,     // Throw exception on parse errors (default: false)
  parseBody: true,        // Parse JSON/form body content (default: false)
  expandEnvVars: true     // Expand environment variables (default: false)
};

const result = parseCurl(curlCommand, options);

Option Details

  • strict: When true, the parser is more strict about syntax and will report more errors
  • throwOnError: When true, throws an exception instead of returning error in result
  • parseBody: When true, attempts to parse JSON and form data in request bodies
  • expandEnvVars: When true, expands environment variables like $API_KEY in the command

Error Handling

The parser provides comprehensive error handling:

const result = parseCurl('invalid curl command');

if (!result.success) {
  console.log('Parsing failed:');
  result.errors.forEach(error => {
    console.log(`- ${error.message}`);
  });
  
  // Check for warnings (non-fatal issues)
  if (result.warnings) {
    console.log('Warnings:');
    result.warnings.forEach(warning => {
      console.log(`- ${warning}`);
    });
  }
}

// Alternative: throw on error
try {
  const result = parseCurl(curlCommand, { throwOnError: true });
  // Use result.data safely
} catch (error) {
  console.error('Parse error:', error.message);
}

Advanced Examples

File Upload

const result = parseCurl(`
  curl -X POST https://api.example.com/upload \
    -F "file=@/path/to/file.txt" \
    -F "description=Test file"
`);
// result.data.body.type === 'form'

Multiple Authentication Methods

// Basic Auth
parseCurl('curl -u username:password https://api.example.com');

// Bearer Token  
parseCurl('curl -H "Authorization: Bearer token123" https://api.example.com');

// API Key
parseCurl('curl --api-key abc123 https://api.example.com');

Proxy and SSL

const result = parseCurl(`
  curl https://api.example.com \
    --proxy http://proxy.company.com:8080 \
    --proxy-user username:password \
    --cacert /path/to/ca.crt \
    --cert /path/to/client.crt
`);