diff --git a/README.md b/README.md index f7aed93..70c8ab3 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ GIF_OUTPUT_PATH="output/commit-man.gif" \ npm run build && npm run generate:gif ``` -Never commit or paste access tokens into issues, commits, or README files. The generator requests the most recent 365 days of contribution data; the available information depends on the token and contribution visibility. +Never commit or paste access tokens into issues, commits, or README files. The garden history starts on the fixed date `2025-10-12` and extends through the current date. Previously displayed days are retained and new dates extend the garden to the right, so the SVG and GIF canvas grow over time rather than dropping the oldest cells. Available contribution information still depends on the token and contribution visibility. ### Publish and embed the GIF on your profile diff --git a/src/contributions.ts b/src/contributions.ts index 04f8d00..7b8b013 100644 --- a/src/contributions.ts +++ b/src/contributions.ts @@ -50,6 +50,15 @@ const CONTRIBUTION_QUERY = ` const MAX_REQUEST_ATTEMPTS = 3; const RETRY_DELAYS_MS = [250, 500] as const; +// Keep each request comfortably under GitHub's one-year contribution-range limit. +const MAX_RANGE_DAYS_PER_REQUEST = 364; + +/** + * The first Sunday at or before the start of the originally displayed window. + * Keep this fixed so existing contribution cells never fall off the left side. + * The garden grows horizontally as newer dates are added. + */ +export const CONTRIBUTION_HISTORY_START_DATE = "2025-10-12"; export function flattenContributionWeeks(weeks: ContributionWeek[]): ContributionDay[] { return weeks.flatMap((week) => week.contributionDays).sort((a, b) => a.date.localeCompare(b.date)); @@ -64,29 +73,56 @@ export async function fetchGitHubContributions( if (!token.trim()) throw new Error("A GitHub token is required."); const to = new Date(now); - const from = new Date(to); - from.setUTCDate(from.getUTCDate() - 364); - - const response = await requestContributionCalendar(username, token, { - query: CONTRIBUTION_QUERY, - variables: { - username, - from: from.toISOString(), - to: to.toISOString(), - }, - }); - - const payload = (await response.json()) as ContributionCalendarResponse; - if (payload.errors?.length) { - throw new Error(`GitHub GraphQL error: ${payload.errors.map((error) => error.message).join("; ")}`); + const historyStart = new Date(`${CONTRIBUTION_HISTORY_START_DATE}T00:00:00.000Z`); + if (to.getTime() < historyStart.getTime()) { + throw new Error("The requested end date is earlier than the contribution history start date."); } - const weeks = payload.data?.user?.contributionsCollection?.contributionCalendar?.weeks; - if (!weeks) { - throw new Error(`Could not read a contribution calendar for GitHub user "${username}". Check that the username exists and is accessible.`); + const contributionDays = new Map(); + const endDate = to.toISOString().slice(0, 10); + let chunkFrom = historyStart; + + while (chunkFrom.getTime() <= to.getTime()) { + const maxChunkTo = new Date(chunkFrom); + maxChunkTo.setUTCDate(maxChunkTo.getUTCDate() + MAX_RANGE_DAYS_PER_REQUEST); + maxChunkTo.setUTCHours(23, 59, 59, 999); + const chunkTo = maxChunkTo.getTime() < to.getTime() ? maxChunkTo : to; + + const response = await requestContributionCalendar(username, token, { + query: CONTRIBUTION_QUERY, + variables: { + username, + from: chunkFrom.toISOString(), + to: chunkTo.toISOString(), + }, + }); + + const payload = (await response.json()) as ContributionCalendarResponse; + if (payload.errors?.length) { + throw new Error(`GitHub GraphQL error: ${payload.errors.map((error) => error.message).join("; ")}`); + } + + const weeks = payload.data?.user?.contributionsCollection?.contributionCalendar?.weeks; + if (!weeks) { + throw new Error(`Could not read a contribution calendar for GitHub user "${username}". Check that the username exists and is accessible.`); + } + + for (const day of flattenContributionWeeks(weeks)) { + // GraphQL may return complete calendar weeks around a requested range. + // Keep only the fixed history window, then de-duplicate overlapping weeks. + if (day.date >= CONTRIBUTION_HISTORY_START_DATE && day.date <= endDate) { + contributionDays.set(day.date, day); + } + } + + if (chunkTo.getTime() >= to.getTime()) break; + + chunkFrom = new Date(chunkTo); + chunkFrom.setUTCDate(chunkFrom.getUTCDate() + 1); + chunkFrom.setUTCHours(0, 0, 0, 0); } - return flattenContributionWeeks(weeks); + return [...contributionDays.values()].sort((a, b) => a.date.localeCompare(b.date)); } async function requestContributionCalendar( diff --git a/tests/contributions.test.ts b/tests/contributions.test.ts index 500cb22..8dd4ba9 100644 --- a/tests/contributions.test.ts +++ b/tests/contributions.test.ts @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { fetchGitHubContributions } from "../src/contributions.js"; +import { + CONTRIBUTION_HISTORY_START_DATE, + fetchGitHubContributions, +} from "../src/contributions.js"; const payload = { data: { @@ -11,7 +14,7 @@ const payload = { { contributionDays: [ { - date: "2026-10-12", + date: "2026-06-12", contributionCount: 2, contributionLevel: "FIRST_QUARTILE", }, @@ -24,6 +27,63 @@ const payload = { }, }; +test("keeps a fixed history start and requests long histories in one-year-safe chunks", async () => { + const originalFetch = globalThis.fetch; + const requestedVariables: Array<{ username: string; from: string; to: string }> = []; + + globalThis.fetch = (async (_input, init) => { + const body = JSON.parse(String(init?.body)) as { + variables: { username: string; from: string; to: string }; + }; + const responseDate = requestedVariables.length === 0 ? "2025-10-12" : "2026-10-15"; + requestedVariables.push(body.variables); + + return new Response(JSON.stringify({ + data: { + user: { + contributionsCollection: { + contributionCalendar: { + weeks: [{ + contributionDays: [{ + date: responseDate, + contributionCount: 2, + contributionLevel: "FIRST_QUARTILE", + }], + }], + }, + }, + }, + }, + }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + }) as typeof fetch; + + const now = new Date("2026-10-15T12:34:56.000Z"); + + try { + const days = await fetchGitHubContributions("codelovingcat", "test-token", now); + + assert.deepEqual(days.map((day) => day.date), ["2025-10-12", "2026-10-15"]); + assert.equal(requestedVariables.length, 2); + assert.deepEqual(requestedVariables, [ + { + username: "codelovingcat", + from: `${CONTRIBUTION_HISTORY_START_DATE}T00:00:00.000Z`, + to: "2026-10-11T23:59:59.999Z", + }, + { + username: "codelovingcat", + from: "2026-10-12T00:00:00.000Z", + to: now.toISOString(), + }, + ]); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("retries a temporary 502 response and then returns contribution data", async () => { const originalFetch = globalThis.fetch; let calls = 0; @@ -38,10 +98,10 @@ test("retries a temporary 502 response and then returns contribution data", asyn }) as typeof fetch; try { - const days = await fetchGitHubContributions("codelovingcat", "test-token", new Date("2026-10-12T12:00:00Z")); + const days = await fetchGitHubContributions("codelovingcat", "test-token", new Date("2026-06-12T12:00:00Z")); assert.equal(calls, 3); assert.equal(days.length, 1); - assert.equal(days[0]?.date, "2026-10-12"); + assert.equal(days[0]?.date, "2026-06-12"); assert.equal(days[0]?.contributionCount, 2); } finally { globalThis.fetch = originalFetch; @@ -59,7 +119,7 @@ test("does not retry permanent client errors such as unauthorized", async () => try { await assert.rejects( - fetchGitHubContributions("codelovingcat", "invalid-token", new Date("2026-10-12T12:00:00Z")), + fetchGitHubContributions("codelovingcat", "invalid-token", new Date("2026-06-12T12:00:00Z")), /\(401\) after 1 attempt/, ); assert.equal(calls, 1);