75 lines
2.4 KiB
Python
75 lines
2.4 KiB
Python
{"""JavaScript code generator."""
|
|
|
|
import json
|
|
from curlconverter.parser import ParsedCurl
|
|
from curlconverter.generators import register_generator
|
|
|
|
|
|
def _detect_content_type(headers: dict, data: str) -> str:
|
|
"""Detect content type from headers or data."""
|
|
if "Content-Type" in headers:
|
|
return headers["Content-Type"]
|
|
if "content-type" in headers:
|
|
return headers["content-type"]
|
|
if data:
|
|
try:
|
|
json.loads(data)
|
|
return "application/json"
|
|
except (json.JSONDecodeError, TypeError):
|
|
pass
|
|
return "application/x-www-form-urlencoded"
|
|
|
|
|
|
@register_generator("javascript")
|
|
def generate_javascript(parsed: ParsedCurl) -> str:
|
|
"""Generate JavaScript fetch code from parsed curl data."""
|
|
lines = []
|
|
|
|
lines.append(f"const url = {repr(parsed.url)};")
|
|
lines.append("")
|
|
|
|
options = {"method": parsed.method}
|
|
headers = dict(parsed.headers) if parsed.headers else {}
|
|
|
|
if parsed.user_agent and "User-Agent" not in headers and "user-agent" not in headers:
|
|
headers["User-Agent"] = parsed.user_agent
|
|
|
|
if parsed.auth:
|
|
encoded = btoa(f"{parsed.auth[0]}:{parsed.auth[1]}")
|
|
headers["Authorization"] = f"Basic {encoded}"
|
|
|
|
if parsed.data:
|
|
content_type = _detect_content_type(headers, parsed.data)
|
|
|
|
if content_type == "application/json":
|
|
try:
|
|
json_data = json.loads(parsed.data)
|
|
options["body"] = json.dumps(json_data)
|
|
headers["Content-Type"] = "application/json"
|
|
except (json.JSONDecodeError, TypeError):
|
|
options["body"] = repr(parsed.data)
|
|
else:
|
|
options["body"] = repr(parsed.data)
|
|
|
|
if parsed.cookies:
|
|
headers["Cookie"] = parsed.cookies
|
|
|
|
if headers:
|
|
lines.append("const headers = " + json.dumps(headers, indent=2) + ";")
|
|
options["headers"] = "headers"
|
|
|
|
if len(options) > 1:
|
|
lines.append("const options = " + json.dumps(options, indent=2) + ";")
|
|
lines.append("")
|
|
lines.append("fetch(url, options)")
|
|
else:
|
|
lines.append("fetch(url)")
|
|
|
|
lines.append(" .then(response => {")
|
|
lines.append(" console.log(response.status);")
|
|
lines.append(" return response.text();")
|
|
lines.append(" })")
|
|
lines.append(" .then(data => console.log(data))")
|
|
lines.append(" .catch(error => console.error(error));")
|
|
|
|
return "\n".join(lines) |