function cloudflare({ token, fetchProxy = fetch } = {}) {
const _fetch = fetchProxy;
const api = Object.assign(async function (
endpoint,
{ body, json, headers = {}, method = "GET" } = {}
) {
const prefixUrl = "https://api.cloudflare.com/client/v4/";
const isGet = method === "GET";
const url =
prefixUrl + endpoint + (isGet ? "?" + new URLSearchParams(json) : "");
if (!body && !isGet && json) {
body = JSON.stringify(json);
headers = {
"Content-Type": "application/json",
...headers
};
}
const response = await _fetch(url, {
method,
body,
headers: {
...headers,
Authorization: "Bearer " + token
}
});
let responseBody = response.headers
.get("content-type")
.includes("application/json")
? await response.json()
: await response.text();
if (!response.ok) {
throw new Error(
`HTTP error\n${JSON.stringify(
{
ok: response.ok,
status: response.status,
statusText: response.statusText,
responseBody
},
undefined,
" "
)}`
);
}
if ("success" in responseBody) {
if (!responseBody.success) {
throw new Error(
`API error\n${JSON.stringify(responseBody)},
undefined,
" "
)}`
);
}
responseBody = responseBody.result;
}
return responseBody;
},
Object.fromEntries(["get", "head", "put", "post", "delete", "options"].map((method) => [method, (endpoint, options) => api(endpoint, { ...options, method })])));
return {
accounts(accountId) {
return {
details: () => api(`accounts/${accountId}/`),
workers: {
scripts(scriptName) {
if (!scriptName) {
return api(`accounts/${accountId}/workers/scripts/`);
}
const endpoint = `accounts/${accountId}/workers/scripts/${scriptName}/`;
return {
upload: (sourceCode) =>
api.put(endpoint, {
body: sourceCode,
headers: {
"Content-Type": "application/javascript"
}
}),
download: () => api(endpoint),
subdomain: (props) =>
props
? api.post(endpoint + "subdomain/", { json: props })
: api(endpoint + "subdomain/"),
delete: () => api.delete(endpoint)
};
}
}
};
},
zones(zoneId) {}
};
}