| 1 | import { readFileSync, readdirSync, statSync } from "node:fs"; |
| 2 | import { join } from "node:path"; |
| 3 | import { renderToStaticMarkup } from "react-dom/server"; |
| 4 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 5 | import { authorsBetween, creditedPairs, releaseCredits } from "../scripts/repo-activity-lib.mjs"; |
| 6 | import ContributePage from "../app/[locale]/contribute/page"; |
| 7 | import HomePage from "../app/[locale]/page"; |
| 8 | import { readAsOf } from "../components/project-pulse"; |
| 9 | import { GET as factsRoute } from "../app/api/facts/route"; |
| 10 | import { ALL_LOCALES } from "./i18n/config"; |
| 11 | import { getContribute } from "./i18n/dictionaries"; |
| 12 | import { pluralCategoriesFor, pluralCategory, pluralText } from "./i18n/plural"; |
| 13 | import { |
| 14 | LIVE_RECORD_MAX_AGE_MS, |
| 15 | isExcluded, |
| 16 | liveRecord, |
| 17 | parseExclusions, |
| 18 | readRepoActivity, |
| 19 | releaseAuthors, |
| 20 | repoActivityView, |
| 21 | } from "./repo-activity"; |
| 22 | |
| 23 | vi.mock("next/navigation", () => ({ redirect: vi.fn(), notFound: vi.fn(), usePathname: () => "/en", useRouter: () => ({}) })); |
| 24 | |
| 25 | const webRoot = new URL("../", import.meta.url); |
| 26 | const snapshot = JSON.parse(readFileSync(new URL("data/repo-stats-snapshot.json", webRoot), "utf8")) as Record<string, unknown>; |
| 27 | const exclusionsFile = JSON.parse(readFileSync(new URL("data/contributor-exclusions.json", webRoot), "utf8")) as { |
| 28 | confirmed: boolean; |
| 29 | logins: { login: string; reason: string }[]; |
| 30 | suffixes: { suffix: string; reason: string }[]; |
| 31 | }; |
| 32 | |
| 33 | const avatar = (login: string) => `https://avatars.githubusercontent.com/${login}`; |
| 34 | const pull = (number: number, login: string, mergedAt: string) => ({ |
| 35 | number, |
| 36 | title: `change ${number}`, |
| 37 | url: `https://github.com/example/repo/pull/${number}`, |
| 38 | login, |
| 39 | avatar: avatar(login), |
| 40 | mergedAt, |
| 41 | firstTime: false, |
| 42 | }); |
| 43 | |
| 44 | type Page = (props: { params: Promise<{ locale: string }> }) => Promise<unknown> | unknown; |
| 45 | const render = async (page: Page, locale: string) => |
| 46 | renderToStaticMarkup((await page({ params: Promise.resolve({ locale }) })) as never); |
| 47 | |
| 48 | afterEach(() => { |
| 49 | vi.unstubAllGlobals(); |
| 50 | vi.restoreAllMocks(); |
| 51 | }); |
| 52 | |
| 53 | describe("pages with every GitHub call failing", () => { |
| 54 | beforeEach(() => { |
| 55 | vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("network down"); })); |
| 56 | vi.spyOn(console, "error").mockImplementation(() => {}); |
| 57 | }); |
| 58 | |
| 59 | it.each(["en", "zh", "ar"])("render the home page and /contribute in %s with no zero and no empty number", async (locale) => { |
| 60 | for (const page of [HomePage, ContributePage]) { |
| 61 | const html = await render(page as Page, locale); |
| 62 | expect(html).toContain("<h1"); |
| 63 | const numbers = [...html.matchAll(/class="[^"]*\btabular\b[^"]*"[^>]*>([^<]*)</g)].map((match) => match[1].trim()); |
| 64 | expect(numbers.length).toBeGreaterThan(0); |
| 65 | for (const number of numbers) { |
| 66 | expect(number).not.toBe(""); |
| 67 | expect(number).not.toBe("0"); |
| 68 | } |
| 69 | expect(html).not.toContain("api.github.com"); |
| 70 | } |
| 71 | }); |
| 72 | |
| 73 | it("shows the merged people, their faces and the milestones block on /contribute", async () => { |
| 74 | const html = await render(ContributePage as Page, "en"); |
| 75 | const view = repoActivityView(); |
| 76 | expect(view?.count).toBeGreaterThan(0); |
| 77 | expect(html).toContain(`${view?.count} GitHub accounts had pull requests merged in the last 30 days.`); |
| 78 | expect(html).toContain('id="milestones"'); |
| 79 | const person = view?.people[0]; |
| 80 | expect(html).toContain(`alt="${person?.login}"`); |
| 81 | expect(html).toContain(view!.pulls[0].url); |
| 82 | }); |
| 83 | |
| 84 | it("announces the read date of the count and the milestone progress to assistive technology", async () => { |
| 85 | const html = await render(ContributePage as Page, "en"); |
| 86 | const asOf = readAsOf(String(snapshot.readAt), "en"); |
| 87 | expect(asOf).toBeTruthy(); |
| 88 | expect(html).toMatch(new RegExp(`<p class="page-meta tabular" title="${asOf}">[^<]+<span class="sr-only"> ${asOf}</span></p>`)); |
| 89 | const progress = html.match(/<span class="tide-progress"[\s\S]*?<\/dd>/g) ?? []; |
| 90 | expect(progress.length).toBeGreaterThan(0); |
| 91 | for (const block of progress) { |
| 92 | expect(block).toContain(`title="${asOf}"`); |
| 93 | expect(block).toContain(`<span class="sr-only">, ${asOf}</span></span></dd>`); |
| 94 | } |
| 95 | expect(html).not.toMatch(/<p[^>]*aria-label=/); |
| 96 | }); |
| 97 | }); |
| 98 | |
| 99 | describe("no browser call to GitHub", () => { |
| 100 | const sources: string[] = []; |
| 101 | for (const dir of ["components", "app", "lib"]) { |
| 102 | const walk = (path: string) => { |
| 103 | for (const name of readdirSync(path)) { |
| 104 | const full = join(path, name); |
| 105 | if (statSync(full).isDirectory()) walk(full); |
| 106 | else if (/\.(ts|tsx)$/.test(name) && !name.endsWith(".test.ts") && !name.endsWith(".test.tsx")) sources.push(full); |
| 107 | } |
| 108 | }; |
| 109 | walk(new URL(`${dir}/`, webRoot).pathname); |
| 110 | } |
| 111 | |
| 112 | it("keeps GitHub API URLs out of every client component", () => { |
| 113 | const clientSources = sources.filter((path) => /^\s*["']use client["']/m.test(readFileSync(path, "utf8"))); |
| 114 | expect(clientSources.length).toBeGreaterThan(0); |
| 115 | for (const path of clientSources) { |
| 116 | const source = readFileSync(path, "utf8"); |
| 117 | expect(source, path).not.toContain("api.github.com"); |
| 118 | expect(source, path).not.toMatch(/\/repos\/codewhale-hq/); |
| 119 | } |
| 120 | }); |
| 121 | |
| 122 | it("has no GitHub feed route left", () => { |
| 123 | expect(() => statSync(new URL("app/api/github/feed/route.ts", webRoot))).toThrow(); |
| 124 | }); |
| 125 | }); |
| 126 | |
| 127 | describe("the contributor exclusion list", () => { |
| 128 | it("is public data with a reason for every entry and starts unconfirmed", () => { |
| 129 | expect(exclusionsFile.confirmed).toBe(false); |
| 130 | for (const entry of [...exclusionsFile.logins, ...exclusionsFile.suffixes]) expect(entry.reason.length).toBeGreaterThan(10); |
| 131 | }); |
| 132 | |
| 133 | it("removes bots from the count and the people", () => { |
| 134 | const fixture = { |
| 135 | readAt: "2026-11-11T00:00:00Z", |
| 136 | windowDays: 30, |
| 137 | merged: [ |
| 138 | pull(1, "alice", "2026-11-10T00:00:00Z"), |
| 139 | pull(2, "dependabot[bot]", "2026-11-09T00:00:00Z"), |
| 140 | pull(3, "github-actions[bot]", "2026-11-09T00:00:00Z"), |
| 141 | pull(4, "some-new-app[bot]", "2026-11-08T00:00:00Z"), |
| 142 | pull(5, "bob", "2026-11-07T00:00:00Z"), |
| 143 | pull(6, "alice", "2026-11-06T00:00:00Z"), |
| 144 | pull(7, "old", "2026-09-01T00:00:00Z"), |
| 145 | ], |
| 146 | milestones: [], |
| 147 | releases: [], |
| 148 | }; |
| 149 | const activity = readRepoActivity({ readAt: fixture.readAt, activity: fixture }); |
| 150 | expect(activity).not.toBeNull(); |
| 151 | const view = repoActivityView(activity, parseExclusions(exclusionsFile)); |
| 152 | expect(view?.count).toBe(2); |
| 153 | expect(view?.people.map((person) => person.login)).toEqual(["alice", "bob"]); |
| 154 | expect(view?.pulls.map((item) => item.number)).toEqual([1, 5, 6]); |
| 155 | expect(repoActivityView(activity, parseExclusions({}))?.count).toBe(5); |
| 156 | expect(isExcluded("Dependabot[bot]", parseExclusions(exclusionsFile))).toBe(true); |
| 157 | expect(isExcluded("alice", parseExclusions(exclusionsFile))).toBe(false); |
| 158 | }); |
| 159 | |
| 160 | it("flips the noun from accounts to people with one switch", () => { |
| 161 | const t = getContribute("en"); |
| 162 | expect(pluralText(t.mergedAccountsCount, 3, "en")).toBe("3 GitHub accounts had pull requests merged in the last 30 days."); |
| 163 | expect(pluralText(t.mergedPeopleCount, 3, "en")).toBe("3 people had pull requests merged in the last 30 days."); |
| 164 | expect(parseExclusions({ confirmed: true }).confirmed).toBe(true); |
| 165 | expect(parseExclusions(exclusionsFile).confirmed).toBe(false); |
| 166 | }); |
| 167 | }); |
| 168 | |
| 169 | describe("the committed snapshot", () => { |
| 170 | it("reads as activity with merged pull requests, milestones and release credits", () => { |
| 171 | const activity = readRepoActivity(); |
| 172 | expect(activity?.merged.length).toBeGreaterThan(0); |
| 173 | expect(activity?.milestones.length).toBeGreaterThan(0); |
| 174 | expect(activity?.releases.length).toBeGreaterThan(0); |
| 175 | for (const release of activity!.releases) expect(releaseAuthors(release.tag)?.length).toBeGreaterThan(0); |
| 176 | }); |
| 177 | |
| 178 | it("is unknown, never a partial, when any part is malformed", () => { |
| 179 | expect(readRepoActivity(null)).toBeNull(); |
| 180 | expect(readRepoActivity({ readAt: snapshot.readAt })).toBeNull(); |
| 181 | const activity = snapshot.activity as { merged: unknown[] }; |
| 182 | expect(readRepoActivity({ ...snapshot, activity: { ...activity, merged: [...activity.merged, { number: 1 }] } })).toBeNull(); |
| 183 | expect(readRepoActivity({ ...snapshot, readAt: "not a date" })).toBeNull(); |
| 184 | }); |
| 185 | }); |
| 186 | |
| 187 | describe("release-scoped authors", () => { |
| 188 | const releases = [ |
| 189 | { tag_name: "v2", html_url: "https://github.com/example/repo/releases/tag/v2", published_at: "2026-02-10T12:00:00Z" }, |
| 190 | { tag_name: "v1", html_url: "https://github.com/example/repo/releases/tag/v1", published_at: "2026-02-01T12:00:00Z" }, |
| 191 | { tag_name: "v0", html_url: "https://github.com/example/repo/releases/tag/v0", published_at: "2026-01-15T12:00:00Z" }, |
| 192 | ]; |
| 193 | const pulls = [ |
| 194 | pull(1, "before", "2026-01-20T00:00:00Z"), |
| 195 | pull(2, "at-previous-tag", "2026-02-01T12:00:00Z"), |
| 196 | pull(3, "just-after-previous", "2026-02-01T12:00:01Z"), |
| 197 | pull(4, "middle", "2026-02-05T00:00:00Z"), |
| 198 | pull(5, "middle", "2026-02-06T00:00:00Z"), |
| 199 | pull(6, "at-tag", "2026-02-10T12:00:00Z"), |
| 200 | pull(7, "after", "2026-02-10T12:00:01Z"), |
| 201 | ]; |
| 202 | |
| 203 | it("returns exactly the authors merged after the previous tag and up to this one", () => { |
| 204 | expect(authorsBetween(pulls, "2026-02-01T12:00:00Z", "2026-02-10T12:00:00Z").map((person) => person.login)).toEqual([ |
| 205 | "just-after-previous", |
| 206 | "middle", |
| 207 | "at-tag", |
| 208 | ]); |
| 209 | const credits = releaseCredits(creditedPairs(releases), () => pulls); |
| 210 | expect(credits.map((credit) => credit.tag)).toEqual(["v2", "v1"]); |
| 211 | expect(credits[0].authors.map((person) => person.login)).toEqual(["just-after-previous", "middle", "at-tag"]); |
| 212 | expect(credits[1].authors.map((person) => person.login)).toEqual(["before", "at-previous-tag"]); |
| 213 | }); |
| 214 | |
| 215 | it("ignores drafts and prereleases when choosing the previous tag", () => { |
| 216 | const withDraft = [{ ...releases[1], tag_name: "v1-rc", draft: true }, ...releases]; |
| 217 | expect(creditedPairs(withDraft).map((pair) => `${pair.release.tag_name}<-${pair.previous.tag_name}`)).toEqual(["v2<-v1", "v1<-v0"]); |
| 218 | }); |
| 219 | }); |
| 220 | |
| 221 | describe("the live record", () => { |
| 222 | const readAt = "2026-11-11T00:00:00.000Z"; |
| 223 | const at = Date.parse(readAt); |
| 224 | |
| 225 | it("is fresh for seven days and stale after", () => { |
| 226 | expect(liveRecord({ readAt }, at).fresh).toBe(true); |
| 227 | expect(liveRecord({ readAt }, at + LIVE_RECORD_MAX_AGE_MS).fresh).toBe(true); |
| 228 | expect(liveRecord({ readAt }, at + LIVE_RECORD_MAX_AGE_MS + 1).fresh).toBe(false); |
| 229 | expect(liveRecord({ readAt }, at - 1).fresh).toBe(false); |
| 230 | expect(liveRecord({ readAt: "nope" }, at)).toMatchObject({ readAt: null, fresh: false }); |
| 231 | expect(liveRecord(null, at)).toMatchObject({ readAt: null, fresh: false }); |
| 232 | }); |
| 233 | |
| 234 | it("is served by /api/facts", async () => { |
| 235 | const response = await factsRoute(); |
| 236 | const body = (await response.json()) as { liveRecord: { source: string; readAt: string; fresh: boolean } }; |
| 237 | expect(body.liveRecord.readAt).toBe(snapshot.readAt); |
| 238 | expect(body.liveRecord.source).toBeTruthy(); |
| 239 | expect(typeof body.liveRecord.fresh).toBe("boolean"); |
| 240 | }); |
| 241 | }); |
| 242 | |
| 243 | describe("plural-aware count sentences", () => { |
| 244 | const counts = [0, 1, 2, 3, 5, 11, 100]; |
| 245 | |
| 246 | it("picks the right category in Arabic, Russian and English", () => { |
| 247 | expect(counts.map((n) => pluralCategory("ar", n))).toEqual(["zero", "one", "two", "few", "few", "many", "other"]); |
| 248 | expect(counts.map((n) => pluralCategory("ru", n))).toEqual(["many", "one", "few", "few", "many", "many", "many"]); |
| 249 | expect(counts.map((n) => pluralCategory("en", n))).toEqual(["other", "one", "other", "other", "other", "other", "other"]); |
| 250 | }); |
| 251 | |
| 252 | it("fills the keyed form for each count and keeps the number in it", () => { |
| 253 | for (const locale of ["ar", "ru", "en"]) { |
| 254 | const forms = getContribute(locale).mergedAccountsCount; |
| 255 | for (const n of counts) { |
| 256 | const text = pluralText(forms, n, locale, "en-US"); |
| 257 | expect(text).toContain(String(n)); |
| 258 | expect(text).not.toContain("{n}"); |
| 259 | expect(text).toBe((forms[pluralCategory(locale, n)] ?? forms.other).replace("{n}", String(n))); |
| 260 | } |
| 261 | } |
| 262 | expect(pluralText(getContribute("ru").mergedAccountsCount, 2, "ru", "en-US")).toContain("2 аккаунтов"); |
| 263 | expect(pluralText(getContribute("ru").mergedAccountsCount, 21, "ru", "en-US")).toContain("21 аккаунта"); |
| 264 | expect(pluralText(getContribute("en").mergedAccountsCount, 1, "en")).toBe("1 GitHub account had a pull request merged in the last 30 days."); |
| 265 | }); |
| 266 | |
| 267 | it("falls back to other when a locale lacks a form", () => { |
| 268 | expect(pluralText({ other: "{n} things" }, 1, "en")).toBe("1 things"); |
| 269 | expect(pluralText({ other: "{n} things" }, 3, "xx-invalid-locale-!", "en")).toBe("3 things"); |
| 270 | }); |
| 271 | |
| 272 | it("gives every routed locale every category it needs, with {n} in each", () => { |
| 273 | for (const locale of ALL_LOCALES.map((entry) => entry.code)) { |
| 274 | const t = getContribute(locale); |
| 275 | for (const forms of [t.mergedAccountsCount, t.mergedPeopleCount]) { |
| 276 | for (const category of pluralCategoriesFor(locale)) { |
| 277 | expect(forms[category], `${locale} ${category}`).toContain("{n}"); |
| 278 | } |
| 279 | } |
| 280 | } |
| 281 | expect(pluralCategoriesFor("ar")).toEqual(["zero", "one", "two", "few", "many", "other"]); |
| 282 | }); |
| 283 | }); |
| 284 |