sweet-curl-parser
v1.0.4
Published
A comprehensive TypeScript library for parsing curl commands into structured JavaScript objects.
Maintainers
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-parserQuick 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_KEYin 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
`);