UNPKG

@scalar/api-client

Version:

the open source API testing client

121 lines (120 loc) 2.93 kB
import { httpStatusCodes as S } from "@scalar/helpers/http/http-status-codes"; import { normalizeError as b, ERRORS as x } from "../../../../libs/errors.js"; import { normalizeHeaders as D } from "../../../../libs/normalize-headers.js"; import { executeHook as f } from "../../../helpers/plugins.js"; import { decodeBuffer as E } from "./decode-buffer.js"; import { getCookieHeaderKeys as T } from "./get-cookie-header-keys.js"; const H = [204, 205, 304], v = async ({ isUsingProxy: t, operation: o, request: i, plugins: n }) => { try { const s = await f(i, "beforeRequest", n), m = Date.now(), e = await fetch(s), a = Date.now(), c = a - m, d = e.headers.get("content-type"), r = D(e.headers, t), u = new URL(e.url), h = u.pathname + u.search, p = e.statusText || S[e.status]?.name || "", l = s.method, y = H.includes(e.status); return d?.startsWith("text/event-stream") && e.body ? k({ response: e, modifiedRequest: s, operation: o, plugins: n, endTime: a, duration: c, responseHeaders: r, statusText: p, method: l, fullPath: h }) : q({ response: e, modifiedRequest: s, operation: o, plugins: n, endTime: a, duration: c, responseHeaders: r, statusText: p, method: l, fullPath: h, contentType: d, shouldSkipBody: y }); } catch (s) { return [b(s, x.REQUEST_FAILED), null]; } }, k = async ({ response: t, modifiedRequest: o, operation: i, plugins: n, endTime: s, duration: m, responseHeaders: e, statusText: a, method: c, fullPath: d }) => { const r = new Response(null, { status: t.status, statusText: a, headers: t.headers }); await f({ response: r, request: o, operation: i }, "responseReceived", n); const u = T(r.headers); return [ null, { timestamp: s, request: o, response: { ...r, headers: e, cookieHeaderKeys: u, reader: t.body.getReader(), duration: m, method: c, path: d } } ]; }, q = async ({ response: t, modifiedRequest: o, operation: i, plugins: n, endTime: s, duration: m, responseHeaders: e, statusText: a, method: c, fullPath: d, contentType: r, shouldSkipBody: u }) => { const p = await t.clone().arrayBuffer(), y = E(p, r ?? "text/plain;charset=UTF-8"), R = new Response(u ? null : p, { status: t.status, statusText: a, headers: t.headers }); await f({ response: R, request: o, operation: i }, "responseReceived", n); const w = T(R.headers); return [ null, { timestamp: s, request: o, response: { ...R, headers: e, cookieHeaderKeys: w, data: y, size: p.byteLength, duration: m, method: c, status: t.status, path: d } } ]; }; export { v as sendRequest };