Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

github.ts

37 lines1.1 KB

1import type { ProviderSecrets } from './types.ts'
2​
3const GITHUB_API_HOST = 'api.github.com'
4​
5/**
6 * Attach `Authorization: Bearer` to `api.github.com` when `GITHUB_TOKEN` is
7 * set. Workers share egress IPs, so the anonymous 60-requests-per-hour quota
8 * is exhausted by other tenants and the contents API returns 403. A blank
9 * token stays anonymous. `raw.githubusercontent.com` is a different host and
10 * is returned unchanged.
11 */
12export function githubRequestInit(
13 url: string,
14 env: Pick<ProviderSecrets, 'GITHUB_TOKEN'>,
15 init?: RequestInit,
16): RequestInit {
17 let host = ''
18 try {
19 host = new URL(url).host
20 } catch {
21 return init ?? {}
22 }
23 if (host !== GITHUB_API_HOST) return init ?? {}
24​
25 const headers = new Headers(init?.headers)
26 if (!headers.has('Accept')) {
27 headers.set('Accept', 'application/vnd.github+json')
28 }
29 if (!headers.has('User-Agent')) {
30 headers.set('User-Agent', 'modelschemas')
31 }
32 const token = env.GITHUB_TOKEN?.trim()
33 if (token && !headers.has('Authorization')) {
34 headers.set('Authorization', `Bearer ${token}`)
35 }
36 return { ...init, headers }