Files
local-github-upload/lib/github.js
T
2026-11-17 12:09:15 +08:00

83 lines
3.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 = '' }) {
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 }
}
}