import { env } from "cloudflare:workers"; import { all, first } from "./db"; import { branchSha, listRefs } from "./git/refs"; import { withStore } from "./git/store"; import { renderMarkdown } from "./markdown"; import { REPO_SELECT } from "./repos"; import type { RepoRow } from "~/lib/types"; const DAY_MS = 24 * 60 * 60 * 1000; const GRAPH_WEEKS = 52; const WEEK_DAYS = 7; const README_NAMES = new Set(["readme.md", "readme.markdown"]); const MAX_README_BYTES = 256 * 1024; const README_CACHE_TTL_SECONDS = 60 * 60 * 24 * 7; const decoder = new TextDecoder(); export type ContributionBreakdown = { commits: number; pulls: number; issues: number; reviews: number; other: number }; export type ContributionDay = { date: string; count: number; breakdown: ContributionBreakdown | null; repos: string[]; }; const MAX_DAY_REPOS = 3; const MIN_GRAPH_YEAR = 1970; type Category = keyof ContributionBreakdown; function categoryOf(kind: string): Category { if (kind === "commit") return "commits"; if (kind.startsWith("pull_")) return "pulls"; if (kind.startsWith("issue_")) return "issues"; if (kind === "comment" || kind.startsWith("review")) return "reviews"; return "other"; } /** Verified addresses of a user; commits authored with any of them count as theirs. */ const VERIFIED_EMAILS = `SELECT email FROM users WHERE account_id = ?1 AND email_verified_at IS NOT NULL UNION SELECT email FROM user_emails WHERE user_id = ?1 AND verified_at IS NOT NULL`; type GraphRow = { day: string; kind: string; repo: string; events: number }; function graphRange(year: number | null, now: number): { start: number; end: number } { if (year === null) { const today = new Date(now); const midnight = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); return { start: midnight - (GRAPH_WEEKS * WEEK_DAYS + today.getUTCDay()) * DAY_MS, end: now }; } const first = Date.UTC(year, 0, 1); const last = Math.min(Date.UTC(year + 1, 0, 1) - 1, now); return { start: first - new Date(first).getUTCDay() * DAY_MS, end: last }; } /** * Daily contributions (public repos unless `includePrivate`) for the last year or one calendar `year`, oldest first, * aligned to whole weeks, with a per-day breakdown for hover cards. Commits come from each repo's * default-branch index, attributed by author email to the user's verified addresses at query time (so * email changes apply immediately and pushes by someone else still credit the author); forks don't count. * Everything else is the user's own activity. */ export async function contributionGraph( accountId: string, includePrivate: boolean, year: number | null = null, ): Promise { const now = Date.now(); const range = graphRange(year, now); const start = new Date(range.start); const endDay = new Date(range.end).toISOString().slice(0, 10); const [activity, commits] = await Promise.all([ all( `SELECT strftime('%Y-%m-%d', ac.created_at / 1000, 'unixepoch') AS day, ac.kind, a.name || '/' || r.name AS repo, COUNT(*) AS events FROM activity ac JOIN repos r ON r.id = ac.repo_id JOIN accounts a ON a.id = r.owner_id WHERE ac.actor_id = ? AND ac.created_at >= ? AND ac.created_at <= ? AND ac.kind NOT IN ('view', 'push') AND (? = 1 OR r.visibility = 'public') GROUP BY day, ac.kind, repo`, accountId, range.start, range.end, includePrivate ? 1 : 0, ), all( `SELECT d.day, 'commit' AS kind, a.name || '/' || r.name AS repo, SUM(d.commits) AS events FROM commit_email_days d JOIN repos r ON r.id = d.repo_id JOIN accounts a ON a.id = r.owner_id WHERE d.email IN (${VERIFIED_EMAILS}) AND d.day >= ?2 AND d.day <= ?4 AND r.fork_of_id IS NULL AND r.status = 'ready' AND (?3 = 1 OR r.visibility = 'public') GROUP BY d.day, repo`, accountId, start.toISOString().slice(0, 10), includePrivate ? 1 : 0, endDay, ), ]); const rows = [...activity, ...commits]; const byDay = new Map }>(); for (const row of rows) { const entry = byDay.get(row.day) ?? { count: 0, breakdown: { commits: 0, pulls: 0, issues: 0, reviews: 0, other: 0 }, repoEvents: new Map(), }; const category = categoryOf(row.kind); entry.count += row.events; entry.breakdown[category] += row.events; entry.repoEvents.set(row.repo, (entry.repoEvents.get(row.repo) ?? 0) + row.events); byDay.set(row.day, entry); } const days: ContributionDay[] = []; for (let time = range.start; time <= range.end; time += DAY_MS) { const date = new Date(time).toISOString().slice(0, 10); const entry = byDay.get(date); days.push({ date, count: entry?.count ?? 0, breakdown: entry?.breakdown ?? null, repos: entry ? [...entry.repoEvents.entries()] .sort((left, right) => right[1] - left[1]) .slice(0, MAX_DAY_REPOS) .map(([name]) => name) : [], }); } return days; } /** Renders README.md from the public `/` repo, cached in KV by commit. */ export async function profileReadme(accountName: string): Promise { const repo = await first( `${REPO_SELECT} WHERE a.name = ?1 AND r.name = ?1 AND r.visibility = 'public' AND r.status = 'ready'`, accountName, ); if (!repo) return null; const refs = await listRefs(repo); const sha = branchSha(refs, repo.default_branch); if (!sha) return null; const cacheKey = `profile-readme:${repo.id}:${sha}`; const cached = await env.KV.get(cacheKey); if (cached !== null) return cached || null; const html = await withStore(repo.artifacts_name, async (store) => { const commit = await store.commit(sha); if (!commit) return ""; const entries = await store.listTree(commit.treeSha, ""); const entry = entries.find( (candidate) => candidate.type !== "tree" && README_NAMES.has(candidate.name.toLowerCase()), ); if (!entry) return ""; const bytes = await store.blob(entry.sha); if (!bytes || bytes.byteLength > MAX_README_BYTES) return ""; return renderMarkdown(decoder.decode(bytes), { owner: repo.owner_name, repo: repo.name, ref: repo.default_branch, basePath: "", }); }); await env.KV.put(cacheKey, html, { expirationTtl: README_CACHE_TTL_SECONDS }); return html || null; } /** * Calendar years, newest first, from the earliest contribution through this year. Commit history may be * backfilled to any date, so this is driven by the data rather than the account's age. */ export async function contributionYears(accountId: string, includePrivate: boolean): Promise { const row = await first<{ commit_day: string | null; activity_at: number | null }>( `SELECT (SELECT MIN(d.day) FROM commit_email_days d JOIN repos r ON r.id = d.repo_id WHERE d.email IN (${VERIFIED_EMAILS}) AND r.fork_of_id IS NULL AND r.status = 'ready' AND (?2 = 1 OR r.visibility = 'public')) AS commit_day, (SELECT MIN(ac.created_at) FROM activity ac JOIN repos r ON r.id = ac.repo_id WHERE ac.actor_id = ?1 AND ac.kind NOT IN ('view', 'push') AND (?2 = 1 OR r.visibility = 'public')) AS activity_at`, accountId, includePrivate ? 1 : 0, ); const current = new Date().getUTCFullYear(); const candidates = [ row?.commit_day ? Number(row.commit_day.slice(0, 4)) : current, row?.activity_at ? new Date(row.activity_at).getUTCFullYear() : current, ]; const earliest = Math.max(MIN_GRAPH_YEAR, Math.min(current, ...candidates)); return Array.from({ length: current - earliest + 1 }, (_, index) => current - index); }