1 | import { addQueryParameters } from "./util/add-query-parameters.js";
|
2 | import { extractUrlVariableNames } from "./util/extract-url-variable-names.js";
|
3 | import { omit } from "./util/omit.js";
|
4 | import { parseUrl } from "./util/url-template.js";
|
5 | function parse(options) {
|
6 | let method = options.method.toUpperCase();
|
7 | let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}");
|
8 | let headers = Object.assign({}, options.headers);
|
9 | let body;
|
10 | let parameters = omit(options, [
|
11 | "method",
|
12 | "baseUrl",
|
13 | "url",
|
14 | "headers",
|
15 | "request",
|
16 | "mediaType"
|
17 | ]);
|
18 | const urlVariableNames = extractUrlVariableNames(url);
|
19 | url = parseUrl(url).expand(parameters);
|
20 | if (!/^http/.test(url)) {
|
21 | url = options.baseUrl + url;
|
22 | }
|
23 | const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl");
|
24 | const remainingParameters = omit(parameters, omittedParameters);
|
25 | const isBinaryRequest = /application\/octet-stream/i.test(headers.accept);
|
26 | if (!isBinaryRequest) {
|
27 | if (options.mediaType.format) {
|
28 | headers.accept = headers.accept.split(/,/).map(
|
29 | (format) => format.replace(
|
30 | /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/,
|
31 | `application/vnd$1$2.${options.mediaType.format}`
|
32 | )
|
33 | ).join(",");
|
34 | }
|
35 | if (url.endsWith("/graphql")) {
|
36 | if (options.mediaType.previews?.length) {
|
37 | const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || [];
|
38 | headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => {
|
39 | const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json";
|
40 | return `application/vnd.github.${preview}-preview${format}`;
|
41 | }).join(",");
|
42 | }
|
43 | }
|
44 | }
|
45 | if (["GET", "HEAD"].includes(method)) {
|
46 | url = addQueryParameters(url, remainingParameters);
|
47 | } else {
|
48 | if ("data" in remainingParameters) {
|
49 | body = remainingParameters.data;
|
50 | } else {
|
51 | if (Object.keys(remainingParameters).length) {
|
52 | body = remainingParameters;
|
53 | }
|
54 | }
|
55 | }
|
56 | if (!headers["content-type"] && typeof body !== "undefined") {
|
57 | headers["content-type"] = "application/json; charset=utf-8";
|
58 | }
|
59 | if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") {
|
60 | body = "";
|
61 | }
|
62 | return Object.assign(
|
63 | { method, url, headers },
|
64 | typeof body !== "undefined" ? { body } : null,
|
65 | options.request ? { request: options.request } : null
|
66 | );
|
67 | }
|
68 | export {
|
69 | parse
|
70 | };
|