| 17 | const GITHUB_USERNAME_REGEX = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/; |
| 18 | |
| 19 | function parseGithubUsernameFromInput(input: string): string { |
| 20 | const trimmed = input.trim(); |
| 21 | |
| 22 | // Check if it's a URL |
| 23 | if (trimmed.includes("://")) { |
| 24 | let url: URL; |
| 25 | try { |
| 26 | url = new URL(trimmed); |
| 27 | } catch { |
| 28 | throw new Error("Invalid GitHub profile URL"); |
| 29 | } |
| 30 | |
| 31 | if (!GITHUB_HOSTS.has(url.hostname)) { |
| 32 | throw new Error("Invalid GitHub profile URL (must be github.com)"); |
| 33 | } |
| 34 | |
| 35 | const segments = url.pathname.split("/").filter(Boolean); |
| 36 | // Only allow `https://github.com/<username>` (optional trailing slash is fine) |
| 37 | if (segments.length !== 1) { |
| 38 | throw new Error( |
| 39 | "Invalid GitHub profile URL (must be a profile URL like https://github.com/username)" |
| 40 | ); |
| 41 | } |
| 42 | |
| 43 | const username = decodeURIComponent(segments[0] ?? "").trim(); |
| 44 | if (!username || !GITHUB_USERNAME_REGEX.test(username)) { |
| 45 | throw new Error("Invalid GitHub username"); |
| 46 | } |
| 47 | |
| 48 | return username.toLowerCase(); |
| 49 | } |
| 50 | |
| 51 | // Otherwise treat as a username |
| 52 | if (!trimmed || !GITHUB_USERNAME_REGEX.test(trimmed)) { |
| 53 | throw new Error("Invalid GitHub username"); |
| 54 | } |
| 55 | |
| 56 | return trimmed.toLowerCase(); |
| 57 | } |
| 58 | |
| 59 | export async function fetchGithubStats(username: string) { |
| 60 | const query = ` |