93 lines
4.2 KiB
JavaScript
93 lines
4.2 KiB
JavaScript
// GitHub REST 调用:校验令牌、取账号、按需创建仓库。只用原生 fetch。
|
||
const API = (process.env.DSH_GITHUB_API || 'https://api.github.com').replace(/\/+$/, '')
|
||
const UA = 'dsh-go-github-upload/0.1'
|
||
|
||
export class GitHubError extends Error {
|
||
constructor(message, { status = 0, code = '' } = {}) {
|
||
super(message)
|
||
this.name = 'GitHubError'
|
||
this.status = status
|
||
this.code = code
|
||
}
|
||
}
|
||
|
||
function headers(token, extra = {}) {
|
||
return {
|
||
accept: 'application/vnd.github+json',
|
||
authorization: `Bearer ${token}`,
|
||
'x-github-api-version': '2022-11-28',
|
||
'user-agent': UA,
|
||
...extra
|
||
}
|
||
}
|
||
|
||
async function request(path, { token, method = 'GET', body, timeoutMs = 25000 } = {}) {
|
||
let res
|
||
try {
|
||
res = await fetch(`${API}${path}`, {
|
||
method,
|
||
headers: headers(token, body === undefined ? {} : { 'content-type': 'application/json' }),
|
||
body: body === undefined ? undefined : JSON.stringify(body),
|
||
signal: AbortSignal.timeout(timeoutMs)
|
||
})
|
||
} catch (error) {
|
||
const reason = error?.name === 'TimeoutError' ? '请求超时' : '连不上 GitHub'
|
||
throw new GitHubError(`${reason},请检查手机网络(GitHub 在国内可能不稳定),或稍后重试。`, { code: 'network' })
|
||
}
|
||
const text = await res.text().catch(() => '')
|
||
let json = null
|
||
try { json = text === '' ? null : JSON.parse(text) } catch {}
|
||
if (res.ok) return json
|
||
const detail = typeof json?.message === 'string' ? json.message : text.slice(0, 200)
|
||
if (res.status === 401) throw new GitHubError('GitHub 令牌无效或已过期,请重新生成令牌。', { status: 401, code: 'bad-token' })
|
||
if (res.status === 403) {
|
||
const limited = String(json?.message || '').toLowerCase().includes('rate limit')
|
||
throw new GitHubError(limited ? 'GitHub 接口被限流,过一会儿再试。' : `GitHub 拒绝了这个操作(403):${detail}`, { status: 403, code: limited ? 'rate-limit' : 'forbidden' })
|
||
}
|
||
if (res.status === 404) throw new GitHubError(`找不到 GitHub 资源(404):${detail}`, { status: 404, code: 'not-found' })
|
||
if (res.status === 422) throw new GitHubError(`GitHub 不接受这次请求(422):${detail}`, { status: 422, code: 'invalid' })
|
||
throw new GitHubError(`GitHub 返回 ${res.status}:${detail}`, { status: res.status, code: 'http' })
|
||
}
|
||
|
||
/** 校验令牌并返回账号名。 */
|
||
export async function getLogin(token) {
|
||
const me = await request('/user', { token })
|
||
if (typeof me?.login !== 'string' || me.login === '') throw new GitHubError('GitHub 没有返回账号名,令牌可能权限不足。', { code: 'bad-token' })
|
||
return me.login
|
||
}
|
||
|
||
/** 保证仓库存在;已存在就复用。返回 { url, cloneUrl, created }。 */
|
||
export async function ensureRepo({ token, login, name, privateRepo = true, description = '' }) {
|
||
// 先问一下仓库在不在:已经推过一次的项目不必每次都调创建接口,
|
||
// 也避开 GitHub 对「内容创建」的二次限流(那个档位下 POST 会被 403)。
|
||
try {
|
||
const existing = await request(`/repos/${login}/${name}`, { token })
|
||
if (existing && existing.html_url) {
|
||
return { url: existing.html_url, cloneUrl: existing.clone_url, created: false }
|
||
}
|
||
} catch (error) {
|
||
if (!(error instanceof GitHubError) || error.status !== 404) throw error
|
||
}
|
||
try {
|
||
const repo = await request('/user/repos', {
|
||
token,
|
||
method: 'POST',
|
||
body: { name, description: description.slice(0, 350), private: privateRepo, auto_init: false, has_issues: true, has_wiki: false }
|
||
})
|
||
return { url: repo.html_url, cloneUrl: repo.clone_url, created: true }
|
||
} catch (error) {
|
||
if (!(error instanceof GitHubError) || error.status !== 422) throw error
|
||
// 同名仓库已存在:复用(可能是之前上传过的)。
|
||
let repo
|
||
try {
|
||
repo = await request(`/repos/${login}/${name}`, { token })
|
||
} catch (inner) {
|
||
throw new GitHubError(`仓库名 ${name} 已被占用且无法访问,请改名后重试。`, { code: 'name-taken' })
|
||
}
|
||
if (repo?.full_name?.toLowerCase() !== `${login}/${name}`.toLowerCase()) {
|
||
throw new GitHubError(`仓库名 ${name} 已被其它账号占用。`, { code: 'name-taken' })
|
||
}
|
||
return { url: repo.html_url, cloneUrl: repo.clone_url, created: false }
|
||
}
|
||
}
|