|
| 1 | +import fs from "node:fs"; |
| 2 | +import path from "node:path"; |
| 3 | + |
| 4 | +const githubToken = process.env.GITHUB_TOKEN; |
| 5 | +if (!githubToken) { |
| 6 | + console.error("❌ GITHUB_TOKEN environment variable is required."); |
| 7 | + process.exit(1); |
| 8 | +} |
| 9 | + |
| 10 | +const TARGET_REPOS = 250; |
| 11 | +const PER_PAGE = 100; |
| 12 | + |
| 13 | +function daysAgoIso(days) { |
| 14 | + const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000); |
| 15 | + return date.toISOString().slice(0, 10); |
| 16 | +} |
| 17 | + |
| 18 | +const TREND_WINDOWS = [ |
| 19 | + { |
| 20 | + label: "7d-hot", |
| 21 | + query: `is:public archived:false pushed:>=${daysAgoIso(7)} stars:>=200`, |
| 22 | + sort: "updated", |
| 23 | + pages: 3, |
| 24 | + }, |
| 25 | + { |
| 26 | + label: "14d-rising", |
| 27 | + query: `is:public archived:false pushed:>=${daysAgoIso(14)} stars:>=100`, |
| 28 | + sort: "updated", |
| 29 | + pages: 3, |
| 30 | + }, |
| 31 | + { |
| 32 | + label: "30d-active", |
| 33 | + query: `is:public archived:false pushed:>=${daysAgoIso(30)} stars:>=50`, |
| 34 | + sort: "updated", |
| 35 | + pages: 4, |
| 36 | + }, |
| 37 | + { |
| 38 | + label: "fallback-popular", |
| 39 | + query: "is:public archived:false stars:>=1000", |
| 40 | + sort: "stars", |
| 41 | + pages: 3, |
| 42 | + }, |
| 43 | +]; |
| 44 | + |
| 45 | +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 46 | + |
| 47 | +function getErrorMessage(error) { |
| 48 | + if (error && typeof error === "object" && "message" in error) { |
| 49 | + return String(error.message); |
| 50 | + } |
| 51 | + return String(error); |
| 52 | +} |
| 53 | + |
| 54 | +function parseRateLimitReset(response) { |
| 55 | + const resetHeader = response.headers.get("x-ratelimit-reset"); |
| 56 | + if (!resetHeader) return null; |
| 57 | + const resetEpochSeconds = Number(resetHeader); |
| 58 | + if (!Number.isFinite(resetEpochSeconds)) return null; |
| 59 | + const waitMs = Math.max(0, resetEpochSeconds * 1000 - Date.now()); |
| 60 | + return waitMs; |
| 61 | +} |
| 62 | + |
| 63 | +async function fetchPage(windowConfig, page) { |
| 64 | + const url = new URL("https://api.github.com/search/repositories"); |
| 65 | + url.searchParams.set("q", windowConfig.query); |
| 66 | + url.searchParams.set("sort", windowConfig.sort); |
| 67 | + url.searchParams.set("order", "desc"); |
| 68 | + url.searchParams.set("per_page", String(PER_PAGE)); |
| 69 | + url.searchParams.set("page", String(page)); |
| 70 | + |
| 71 | + const response = await fetch(url, { |
| 72 | + headers: { |
| 73 | + Authorization: `Bearer ${githubToken}`, |
| 74 | + Accept: "application/vnd.github+json", |
| 75 | + "X-GitHub-Api-Version": "2022-11-28", |
| 76 | + "User-Agent": "RepoMind-Weekly-Repo-Catalog", |
| 77 | + }, |
| 78 | + }); |
| 79 | + |
| 80 | + if (response.status === 403) { |
| 81 | + const waitMs = parseRateLimitReset(response) ?? 60_000; |
| 82 | + const waitSeconds = Math.ceil(waitMs / 1000); |
| 83 | + console.warn(`⏳ Rate limited. Waiting ${waitSeconds}s before retrying...`); |
| 84 | + await sleep(waitMs + 1_000); |
| 85 | + return fetchPage(windowConfig, page); |
| 86 | + } |
| 87 | + |
| 88 | + if (!response.ok) { |
| 89 | + throw new Error(`GitHub API error ${response.status}: ${response.statusText}`); |
| 90 | + } |
| 91 | + |
| 92 | + const payload = await response.json(); |
| 93 | + return Array.isArray(payload?.items) ? payload.items : []; |
| 94 | +} |
| 95 | + |
| 96 | +function normalizeRepo(repo) { |
| 97 | + return { |
| 98 | + owner: repo?.owner?.login ?? "", |
| 99 | + repo: repo?.name ?? "", |
| 100 | + stars: Number(repo?.stargazers_count ?? 0), |
| 101 | + description: typeof repo?.description === "string" ? repo.description : null, |
| 102 | + topics: Array.isArray(repo?.topics) |
| 103 | + ? repo.topics.filter((topic) => typeof topic === "string" && topic.trim().length > 0) |
| 104 | + : [], |
| 105 | + language: typeof repo?.language === "string" ? repo.language : null, |
| 106 | + }; |
| 107 | +} |
| 108 | + |
| 109 | +function isValidRepo(repo) { |
| 110 | + return ( |
| 111 | + typeof repo.owner === "string" && |
| 112 | + repo.owner.trim().length > 0 && |
| 113 | + typeof repo.repo === "string" && |
| 114 | + repo.repo.trim().length > 0 |
| 115 | + ); |
| 116 | +} |
| 117 | + |
| 118 | +async function fetchTrendingRepos() { |
| 119 | + const collected = []; |
| 120 | + const seen = new Set(); |
| 121 | + |
| 122 | + console.log("🚀 Building weekly trending repository catalog..."); |
| 123 | + |
| 124 | + for (const windowConfig of TREND_WINDOWS) { |
| 125 | + console.log(`\n🔍 Window: ${windowConfig.label}`); |
| 126 | + |
| 127 | + for (let page = 1; page <= windowConfig.pages; page += 1) { |
| 128 | + if (collected.length >= TARGET_REPOS) { |
| 129 | + break; |
| 130 | + } |
| 131 | + |
| 132 | + try { |
| 133 | + const items = await fetchPage(windowConfig, page); |
| 134 | + if (items.length === 0) { |
| 135 | + console.log(` • page ${page}: no results, moving on`); |
| 136 | + break; |
| 137 | + } |
| 138 | + |
| 139 | + let addedThisPage = 0; |
| 140 | + |
| 141 | + for (const item of items) { |
| 142 | + const normalized = normalizeRepo(item); |
| 143 | + if (!isValidRepo(normalized)) continue; |
| 144 | + |
| 145 | + const key = `${normalized.owner.toLowerCase()}/${normalized.repo.toLowerCase()}`; |
| 146 | + if (seen.has(key)) continue; |
| 147 | + |
| 148 | + seen.add(key); |
| 149 | + collected.push(normalized); |
| 150 | + addedThisPage += 1; |
| 151 | + |
| 152 | + if (collected.length >= TARGET_REPOS) { |
| 153 | + break; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + console.log(` • page ${page}: +${addedThisPage}, total=${collected.length}`); |
| 158 | + await sleep(1_000); |
| 159 | + } catch (error) { |
| 160 | + console.error(` ❌ failed on page ${page}: ${getErrorMessage(error)}`); |
| 161 | + break; |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + if (collected.length >= TARGET_REPOS) { |
| 166 | + break; |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + const finalSet = collected.slice(0, TARGET_REPOS); |
| 171 | + |
| 172 | + if (finalSet.length === 0) { |
| 173 | + throw new Error("No repositories collected from GitHub search windows."); |
| 174 | + } |
| 175 | + |
| 176 | + const dataDir = path.resolve(process.cwd(), "public/data"); |
| 177 | + fs.mkdirSync(dataDir, { recursive: true }); |
| 178 | + |
| 179 | + const outputPath = path.resolve(dataDir, "top-repos.json"); |
| 180 | + fs.writeFileSync(outputPath, `${JSON.stringify(finalSet, null, 2)}\n`); |
| 181 | + |
| 182 | + console.log(`\n✅ Wrote ${finalSet.length} repositories to ${outputPath}`); |
| 183 | +} |
| 184 | + |
| 185 | +fetchTrendingRepos().catch((error) => { |
| 186 | + console.error("❌ Failed to refresh trending repository catalog:", getErrorMessage(error)); |
| 187 | + process.exit(1); |
| 188 | +}); |
0 commit comments