| 1 | import { |
| 2 | GitHubNotConnectedError, |
| 3 | GitHubRepositoryNotFoundError, |
| 4 | GitHubUnavailableError, |
| 5 | } from './imports.errors.js'; |
| 6 | |
| 7 | const API = ' |
| 8 | const TIMEOUT_MS = 10_000 |
| 9 | const PAGE_SIZE = 100 |
| 10 | // ponytail: stops at the 1,000 most recently pushed; an account past that needs server-side search over a cached list. |
| 11 | const MAX_PAGES = 10 |
| 12 | |
| 13 | export type GitHubRepository |
| 14 | fullName: string |
| 15 | private: boolean |
| 16 | description: string |
| 17 | }; |
| 18 | |
| 19 | type RawRepository |
| 20 | full_name: string |
| 21 | private: boolean |
| 22 | description: string |
| 23 | }; |
| 24 | |
| 25 | /** Null for a 404. A 401 means the linked token was revoked, which only linking GitHub again fixes. */ |
| 26 | async function githubGet< |
| 27 | const response = |
| 28 | headers: { |
| 29 | Accept: 'application/vnd.github+json', |
| 30 | Authorization: `Bearer ${token |
| 31 | 'X-GitHub-Api-Version': '2022-11-28', |
| 32 | }, |
| 33 | signal: AbortSignal.timeout |
| 34 | }).catch((cause |
| 35 | throw new GitHubUnavailableError( |
| 36 | }); |
| 37 | |
| 38 | if (response.status |
| 39 | if (response.status |
| 40 | if (!response.ok |
| 41 | throw new GitHubUnavailableError( |
| 42 | cause: new Error |
| 43 | `GitHub answered ${response.status |
| 44 | ), |
| 45 | }); |
| 46 | } |
| 47 | return (await response |
| 48 | } |
| 49 | |
| 50 | /** Refuses before a repository is created for a source the token cannot read. GitHub answers 404 rather than 403 for a private repository the token cannot see. */ |
| 51 | export async function assertGitHubRepositoryReadable |
| 52 | token: string, |
| 53 | source: string, |
| 54 | ) { |
| 55 | const repository = |
| 56 | if (!repository) |
| 57 | } |
| 58 | |
| 59 | /** Every repository the user owns, collaborates on, or reaches through an organization, most recently pushed first. Public repositories they merely can read are left out. */ |
| 60 | export async function listGitHubRepositories |
| 61 | token: string, |
| 62 | ): Promise<GitHubRepository |
| 63 | const repositories: |
| 64 | for (let page |
| 65 | const raw = |
| 66 | (await githubGet<RawRepository |
| 67 | token, |
| 68 | `/user/repos?sort=pushed&per_page=${PAGE_SIZE}&page=${ |
| 69 | )) ?? []; |
| 70 | for (const repository |
| 71 | repositories.push({ |
| 72 | fullName: repository.full_name |
| 73 | private: repository.private |
| 74 | description: repository.description |
| 75 | }); |
| 76 | } |
| 77 | if (raw.length |
| 78 | } |
| 79 | return repositories; |
| 80 | } |