UNPKG

@scalar/api-client

Version:

the open source API testing client

60 lines (59 loc) 2.78 kB
import { parse as c } from "shell-quote"; import { encode as h } from "js-base64"; function P(o) { const e = c(o).map((i) => typeof i == "object" && "op" in i && i.op === "glob" ? i.pattern.trim() : typeof i == "string" ? i.trim() : i).filter((i) => i !== ""), a = { url: "" }, t = e[Symbol.iterator](); let r = t.next().value; for (; r; ) r === "-X" || r === "--request" ? p(t, a) : r === "--url" ? n(t, a) : r === "-H" || r === "--header" ? d(t, a) : r === "--data" || r === "-d" || r === "--data-raw" || r === "--data-urlencode" || r === "--data-binary" || r === "--data-ascii" ? y(t, a, o) : typeof r == "string" && !a.url && (r.startsWith("http") || r.startsWith("www.")) ? n([r][Symbol.iterator](), a) : r === "-P" ? f(t, a) : typeof r == "string" && r.toLowerCase().includes("content-type") ? m(r, a) : r === "-u" || r === "--user" ? l(t, a) : (r === "-b" || r === "--cookie") && u(t, a), r = t.next().value; return a; } function p(o, e) { e.method = o.next().value.toLowerCase(); } function n(o, e) { const a = new URL(o.next().value.replace(/['"]/g, "")); e.servers = [a.origin], e.path = a.pathname !== "/" ? a.pathname : "", e.url = e.servers[0] + e.path; const t = s(a.search); e.queryParameters = e.queryParameters ? [...e.queryParameters, ...t] : t; } function d(o, e) { const a = o.next().value.split(/:(.*)/); e.headers = e.headers || {}, a[1] !== void 0 ? e.headers[a[0].trim()] = a[1].trim() : e.headers[a[0].trim()] = ""; } function f(o, e) { const a = o.next().value.replace(/['"]/g, "").split("="); e.pathVariables = e.pathVariables || {}, a[1] !== void 0 ? e.pathVariables[a[0].trim()] = a[1].trim() : e.pathVariables[a[0].trim()] = ""; } function s(o) { const e = []; return new URL(o, "http://example.com").searchParams.forEach((t, r) => { e.push({ key: r, value: t }); }), e; } function m(o, e) { const a = o.replace(/['"]/g, "").split(/:(.+)/); e.headers = e.headers || {}, a[0] && (a[1] !== void 0 ? e.headers[a[0].trim()] = a[1].trim() : e.headers[a[0].trim()] = ""); } function l(o, e) { const a = o.next().value; try { const t = h(a); e.headers = e.headers || {}, e.headers.Authorization = `Basic ${t}`; } catch (t) { console.warn("Could not base64 encode these HTTP basic auth credentials:", a, t); } } function u(o, e) { const a = o.next().value; e.headers = e.headers || {}, e.headers.Cookie ? e.headers.Cookie += `; ${a}` : e.headers.Cookie = a.replace(/;$/, ""); } function y(o, e, a) { const t = o.next().value; if (typeof t == "string" && (t.startsWith("@") ? e.body = "" : e.body = t, !e.url || a.includes("-G"))) { const r = s(`?${e.body}`); e.queryParameters = e.queryParameters ? [...e.queryParameters, ...r] : r; } } export { P as parseCurlCommand };