async function gh(
link
, {
endpoint = "repos",
ghToken = credentials[0].ghToken,
debug = false
} = {}) {
const URL_PREFIX = 'https://api.github.com'
const headers = {
Accept: `application/vnd.github.raw`
}
if (ghToken !== null) {
headers["Authorization"] = `token ${ghToken}`
}
if (link == undefined) { return "Include GitHub Link (Docs: https://observablehq.com/@periscopic/github-api-in-observable)"}
let urlLink = ""
if (link !== "") {
const rawLink = String(link)
let inputLink = rawLink
let unpack = inputLink.split("/").slice(3)
let owner = unpack.slice(0, 1)
let repo = unpack.slice(1, 2)
let flowType = unpack.slice(2, 3)
let branch = unpack.slice(3, 4)
let path = unpack.slice(4)
let fetchMeta = `${URL_PREFIX}/repos/${[owner, repo].join("/")}`
let resMeta = await fetch(fetchMeta, {
headers: headers
}).then((response) => response.json())
let defaultBranch = resMeta.default_branch
let branchRef = branch.slice(0, 1).length === 0 | branch.slice(0, 1)[0] === defaultBranch ? "" : "?ref=" + branch.slice(0, 1)[0]
let linkArray = [owner, repo, "contents", path, branchRef]
let linkCollapsed = linkArray.flat()
urlLink = linkCollapsed.slice(0, -1).join("/") + linkCollapsed.slice(-1)
if (!urlLink.startsWith("/") & urlLink !== "") { urlLink = '/' + urlLink }
}
const rawEndpoint = String(endpoint)
let urlEndpoint = rawEndpoint
if (!urlEndpoint.startsWith("/")) { urlEndpoint = '/' + urlEndpoint }
let fetchQuery = `${URL_PREFIX}${urlEndpoint}${urlLink}`
if (debug) { return fetchQuery }
const response = await fetch(fetchQuery, {
headers: headers
})
return response
}