import { encode } from "js-base64";
import { parse } from "shell-quote";
//#region src/libs/parse-curl.ts
/** Parse and normalize a curl command */
function parseCurlCommand(curlCommand) {
	const args = parse(curlCommand).map((arg) => {
		if (typeof arg === "object" && "op" in arg && arg.op === "glob") return arg.pattern.trim();
		return typeof arg === "string" ? arg.trim() : arg;
	}).filter((arg) => arg !== "");
	const result = { url: "" };
	const iterator = args[Symbol.iterator]();
	let arg = iterator.next().value;
	while (arg) {
		if (arg === "-X" || arg === "--request") parseMethod(iterator, result);
		else if (arg === "--url") parseUrl(iterator, result);
		else if (arg === "-H" || arg === "--header") parseHeader(iterator, result);
		else if (arg === "--data" || arg === "-d" || arg === "--data-raw" || arg === "--data-urlencode" || arg === "--data-binary" || arg === "--data-ascii") parseData(iterator, result, curlCommand);
		else if (typeof arg === "string" && !result.url && (arg.startsWith("http") || arg.startsWith("www."))) parseUrl([arg][Symbol.iterator](), result);
		else if (arg === "-P") parsePathVariables(iterator, result);
		else if (typeof arg === "string" && arg.toLowerCase().includes("content-type")) parseContentType(arg, result);
		else if (arg === "-u" || arg === "--user") parseAuth(iterator, result);
		else if (arg === "-b" || arg === "--cookie") parseCookie(iterator, result);
		arg = iterator.next().value;
	}
	return result;
}
/** Get the method from a curl command */
function parseMethod(iterator, result) {
	result.method = iterator.next().value.toLowerCase();
}
/** Get the URL from a curl command */
function parseUrl(iterator, result) {
	const url = new URL(iterator.next().value.replace(/['"]/g, ""));
	result.servers = [url.origin];
	result.path = url.pathname !== "/" ? url.pathname : "";
	result.url = result.servers[0] + result.path;
	const urlQueryParameters = parseQueryParameters(url.search);
	result.queryParameters = result.queryParameters ? [...result.queryParameters, ...urlQueryParameters] : urlQueryParameters;
}
/** Get the headers from a curl command */
function parseHeader(iterator, result) {
	const header = iterator.next().value.split(/:(.*)/);
	result.headers = result.headers || {};
	if (header[1] !== void 0) result.headers[header[0].trim()] = header[1].trim();
	else result.headers[header[0].trim()] = "";
}
/** Get the {query} parameters from a curl command */
function parsePathVariables(iterator, result) {
	const param = iterator.next().value.replace(/['"]/g, "").split("=");
	result.pathVariables = result.pathVariables || {};
	if (param[1] !== void 0) result.pathVariables[param[0].trim()] = param[1].trim();
	else result.pathVariables[param[0].trim()] = "";
}
/** Get the ?query=parameters from a curl command */
function parseQueryParameters(url) {
	const queryParameters = [];
	new URL(url, "http://example.com").searchParams.forEach((value, key) => {
		queryParameters.push({
			key,
			value
		});
	});
	return queryParameters;
}
/** Get the Content-Type header from a curl command */
function parseContentType(arg, result) {
	const header = arg.replace(/['"]/g, "").split(/:(.+)/);
	result.headers = result.headers || {};
	if (!header[0]) return;
	if (header[1] !== void 0) result.headers[header[0].trim()] = header[1].trim();
	else result.headers[header[0].trim()] = "";
}
/** Get the Authorization header from a curl command */
function parseAuth(iterator, result) {
	const auth = iterator.next().value;
	try {
		const encodedAuth = encode(auth);
		result.headers = result.headers || {};
		result.headers["Authorization"] = `Basic ${encodedAuth}`;
	} catch (error) {
		console.warn("Could not base64 encode these HTTP basic auth credentials:", auth, error);
	}
}
/** Get the Cookie header from a curl command */
function parseCookie(iterator, result) {
	const cookie = iterator.next().value;
	result.headers = result.headers || {};
	if (result.headers["Cookie"]) result.headers["Cookie"] += `; ${cookie}`;
	else result.headers["Cookie"] = cookie.replace(/;$/, "");
}
/** Parse data from a curl command */
function parseData(iterator, result, curlCommand) {
	const nextArg = iterator.next().value;
	if (typeof nextArg === "string") {
		if (nextArg.startsWith("@")) result.body = "";
		else result.body = nextArg;
		if (!result.url || curlCommand.includes("-G")) {
			const newQueryParams = parseQueryParameters(`?${result.body}`);
			result.queryParameters = result.queryParameters ? [...result.queryParameters, ...newQueryParams] : newQueryParams;
		}
	}
}
//#endregion
export { parseCurlCommand };

//# sourceMappingURL=parse-curl.js.map