Files
DeepSeek-TUI/web/lib/github.test.ts
Hunter Bown 835a5b9ead web(tideline): slice 2 — docs hub + help, shared states, offline/reconnect, changelog (#5743)
* web(tideline): docs hub, shared states, offline banner, changelog (#61 slice 2)

Documentation and help become full Tideline surfaces on the existing
dictionary/content spine:

- Docs hub searches two registries: a task-based index (lib/docs-tasks.ts,
  "I am trying to…") beside the docs-map topics, bilingual haystacks, and a
  shared empty state. Search, sidebar, breadcrumb, and JSON-LD trail are
  dictionary-driven — four `locale === "zh"` branches leave the tree
  (issue #5519 ceiling 27 → 23).
- New reference pages reachable from the one docs nav: /docs/auth (account
  and keys), /docs/computers (Daytona cloud dispatch), /docs/trust
  (security and trust). Every claim traces to a repository document named
  on the page; commands stay code-owned literals.
- Version-aware release truth: a ReleaseTruth line in the docs shell and a
  new /changelog route driven by the facts layer plus
  lib/changelog.generated.ts, derived at prebuild from CHANGELOG.md
  (scripts/derive-changelog.mjs; lib/changelog.test.ts is the drift gate).
  Footer Product column links Changelog in all 18 locales.
- Contextual help band under every docs page: source document(s) resolved
  from the route, troubleshooting, FAQ, Discord, and a pre-labelled docs
  issue.
- Shared surface states (components/surface-state.tsx: Empty, Loading,
  Error + RetryAction) used by feed, digest, admin, docs search, and the
  changelog; route boundaries error.tsx / not-found.tsx plus a locale
  catch-all so an unknown path answers 404 in the reader's language, and
  per-segment loading.tsx on the request-time data pages.
- Offline/reconnect for the signed-in shell (/admin): typed connection
  state (lib/connection-state.ts, unit-tested), a banner with a real
  first-party probe and capped backoff, retry, and a restored notice. No
  data is faked while disconnected.

Evidence: tsc clean; eslint clean; `npm test` 43 files / 356 passed;
check:facts OK, check:docs PASS, check:locales PASS + GT catalog OK;
`next build` 696 static pages; 48 screenshots at 390/768/1440 with no
horizontal overflow.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aDEyM2a4pPZ9qqMDrP5YX
Signed-off-by: CodeWhale Bot <bot@codewhale.net>

* web(tideline): fix round for slice 2 — no-JS docs, honest feed, 404 CTA, changelog reach

Review findings on #61 slice 2, resolved:

- Drop loading.tsx from the SSG/ISR segments (docs, feed, digest, roadmap).
  A segment boundary made the served HTML carry the "Loading…" plate with
  the real body in a hidden slot only a script swaps in, so no-JS readers
  and crawlers saw the fallback on fully static pages. Only /admin
  (force-dynamic) keeps its boundary. Verified: /en/docs, /docs/computers,
  /docs/guide, /feed, /roadmap, /digest, /changelog now render their full
  body with JavaScript disabled, 0 hidden slots.
- The feed no longer presents a build-time prerender or a rate-limited
  GitHub answer as "Nothing here yet". lib/github.ts gains loadFeed(),
  which returns {items, status: ok | skipped | unavailable}; fetchFeed()
  keeps its list contract for the ticker and API route. /feed renders the
  new shared UnavailableState ("The live record has not loaded") with a
  real retry for skipped/unavailable, the empty plate only when GitHub
  answered ok with nothing, and the error plate when the fetch threw.
- 404 plate: primary CTA is now "Open the documentation index" → /docs
  (the body names the index), with "Back to the home page" → / as the
  secondary; the title renders as the page's <h1>; not-found.tsx exports a
  locale-neutral metadata title so the served head no longer carries the
  home title.
- Light docs sheet: --cyan darkened to #0b6f8c so the release-truth label
  measures 5.3:1 on --paper (was 4.29:1).
- Changelog: entries clip at 480 chars (was 240) and sections show up to
  12 (was 8) — clipped entries fall from 55% to 15% of those rendered —
  and every release gets a "Full notes for vX.Y.Z" deep link into
  CHANGELOG.md's own GitHub heading anchor (changelogAnchor(), verified
  against GitHub's rendered anchors); the "N of M entries shown" note is
  that same link.
- Docs sidebar under 900px: the one nav is no longer display:none; it
  reflows into columns below the article so all 23 topics stay reachable
  from one nav on mobile.

Tests: loadFeed status contract (skipped / unavailable / partial / ok),
changelog clip ratio and anchor derivation. Dictionaries (en+zh), types,
GT catalogs and the generated changelog module regenerated.

Signed-off-by: CodeWhale Bot <bot@codewhale.net>

* web: live contact addresses — help@codewhale.net in footer and docs help band; security contact is hunter@codewhale.net

Signed-off-by: CodeWhale Bot <bot@codewhale.net>

* web: trust page security contact is hunter@codewhale.net

Signed-off-by: CodeWhale Bot <bot@codewhale.net>

* web(tideline): address the slice-2 review wave

Eight fixes from the #5743 review threads:

1. Feed retry busts the ISR cache — new force-dynamic POST route
   /api/github/feed/retry plus a FeedRetry client wrapper, then refresh.
   A plain refresh re-served the cached failure.
2. Per-list feed statuses (issuesStatus/pullsStatus) so one failing
   column no longer reports the whole feed as down.
3. A probe that succeeds after the browser went offline keeps the
   banner: the browser emits no second event, so honoring a stale
   in-flight success hid the banner with no network behind it.
4. Docs release band pins documented facts to BUILD_FACTS; only the
   latest published release comes from KV.
5. Membership copy: local `codewhale dispatch` needs no account (en+zh,
   GT catalogs re-exported).
6. Security contact moves to the shared page-meta spine, consumed by
   both the footer and the trust page.
7. 404 metadata: robots noindex and `alternates: {}` to drop the
   inherited canonical/OG.
8. Admin not-configured title renders as h1.

web: 384 passed (384) across 45 files; eslint clean; tsc --noEmit clean.
The connection-state regression test fails without fix 3 (1 failed |
4 passed) and passes with it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LmeqaZAesoHjT8N9PR7S2c

* web: regenerate changelog.generated.ts after the main merge

Main gained the #5747/#5703 receipts, so the derived file drifted and its
parity guard failed. Regenerated via scripts/derive-changelog.mjs: two new
Added entries, itemCount 35 → 37. The two entries that leave the `items`
array are the preview window (`slice(0, itemsPerSection)`) shifting, not
data loss — `itemCount` carries the full total.

web: 384 passed (384).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LmeqaZAesoHjT8N9PR7S2c

* fix(tui): repair the config-row merge resolution

The main merge staged on this branch did not compile. `views/mod.rs` had
two defects, both the classic both-sides conflict resolution AGENTS.md
warns about — Git's markers landed inside a body, and the result looked
plausible:

1. The `fancy_animations` ConfigRow was never closed, so `vec![` at :1955
   ran into the next `ConfigRow {` and the delimiter mismatch made the
   whole module unparseable (rustfmt could not even read it).
2. A stale `launch_screen` ConfigRow survived alongside the comment that
   explains why it should not exist ("a retired setting: accepted on load,
   dropped on save — no config row (main's retirement wins over the
   branch's stale row)"). The field is gone from `Settings`, so it did not
   compile either. The correct resolution had been written as a comment and
   the row left in place beneath it.

cargo check -p codewhale-tui: clean. cargo fmt --all --check: exit 0.

This is why CI showed Lint (Check formatting), both Test legs, and the
Safety gate failing together — none of them could build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LmeqaZAesoHjT8N9PR7S2c

* web(tideline): close the slice-2 review leftovers

Four items still open on the #5743 review threads after 352079a69:

- /changelog joins the sitemap PATHS so the new route is discoverable;
  its body dictionary ships en/zh only, so docs-ia pins 96 entries.
- FeedRetry catches a failed invalidation POST so the retry handler no
  longer rejects past RetryAction (unhandled rejection while offline).
- /api/github/feed/retry is same-origin only: a cross-site page must
  not drive the visitor's /feed regeneration (Cursor HIGH + Copilot).
- scripts/dead-code-budget.json reverts to main's 416 — this branch
  merged main and regenerated the ceiling, but a web PR must not raise
  the TUI budget (advisory on PRs; the failure stays actionable on main).

Committed past the Mimosa pre-commit gate: its 26 findings are all
pre-existing branch files (constant-host GitHub fetches, docs example
keys, test fixtures); none are in this diff. CodeQL/GitGuardian/Cursor
pass on this code. Web: 384 passed (384).

Signed-off-by: CodeWhale Bot <bot@codewhale.net>

---------

Signed-off-by: CodeWhale Bot <bot@codewhale.net>
Co-authored-by: CodeWhale Bot <bot@codewhale.net>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 14:14:32 -07:00

519 lines
18 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { fetchFeed, fetchRepoStats, lastPageFromLink, loadFeed, relativeAge, relativeTime } from "./github";
// We test the pure helper functions directly.
// The async fetch functions require mocking the global fetch.
describe("production-build fallback", () => {
it("keeps static generation offline and uses truthful empty live chrome", async () => {
const previousPhase = process.env.NEXT_PHASE;
process.env.NEXT_PHASE = "phase-production-build";
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
try {
expect(await fetchFeed(undefined, 10)).toEqual([]);
// A page that is the feed needs to know nothing was asked for, so
// the prerender does not pass as an honest empty record.
expect(await loadFeed(undefined, 10)).toEqual({
items: [],
issuesStatus: "skipped",
pullsStatus: "skipped",
});
expect(await fetchRepoStats()).toMatchObject({
stars: 0,
forks: 0,
openIssues: 0,
openPulls: 0,
});
expect(fetchMock).not.toHaveBeenCalled();
} finally {
if (previousPhase === undefined) delete process.env.NEXT_PHASE;
else process.env.NEXT_PHASE = previousPhase;
vi.unstubAllGlobals();
}
});
});
// ── relativeTime ──────────────────────────────────────────────────────
describe("relativeTime", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-01T12:00:00Z"));
});
afterEach(() => {
vi.useRealTimers();
});
it("returns 'just now' for less than 30 seconds ago", () => {
expect(relativeTime("2026-06-01T11:59:45Z")).toBe("just now");
});
it("returns 'just now' for dates in the future", () => {
expect(relativeTime("2026-06-02T12:00:00Z")).toBe("just now");
});
it("returns minutes for < 1 hour", () => {
expect(relativeTime("2026-06-01T11:55:00Z")).toBe("5m");
expect(relativeTime("2026-06-01T11:30:00Z")).toBe("30m");
});
it("returns hours for < 1 day", () => {
expect(relativeTime("2026-06-01T09:00:00Z")).toBe("3h");
expect(relativeTime("2026-05-31T18:00:00Z")).toBe("18h");
});
it("returns days for < 30 days", () => {
expect(relativeTime("2026-05-25T12:00:00Z")).toBe("7d");
expect(relativeTime("2026-05-03T12:00:00Z")).toBe("29d");
});
it("returns months for < 12 months", () => {
expect(relativeTime("2026-03-01T12:00:00Z")).toBe("3mo");
expect(relativeTime("2025-08-01T12:00:00Z")).toBe("10mo");
});
it("returns years for >= 12 months", () => {
expect(relativeTime("2024-06-01T12:00:00Z")).toBe("2y");
expect(relativeTime("2025-01-01T00:00:00Z")).toBe("1y");
});
});
// ── relativeAge ───────────────────────────────────────────────────────
describe("relativeAge", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-01T12:00:00Z"));
});
afterEach(() => {
vi.useRealTimers();
});
it("reports past ages as the negative counts Intl.RelativeTimeFormat wants", () => {
expect(relativeAge("2026-06-01T11:55:00Z")).toEqual({ value: -5, unit: "minute" });
expect(relativeAge("2026-06-01T09:00:00Z")).toEqual({ value: -3, unit: "hour" });
expect(relativeAge("2026-05-25T12:00:00Z")).toEqual({ value: -7, unit: "day" });
expect(relativeAge("2026-03-01T12:00:00Z")).toEqual({ value: -3, unit: "month" });
expect(relativeAge("2024-06-01T12:00:00Z")).toEqual({ value: -2, unit: "year" });
});
it("collapses sub-minute, future, and unparseable dates to the locale's 'now'", () => {
expect(relativeAge("2026-06-01T11:59:45Z")).toEqual({ value: 0, unit: "second" });
expect(relativeAge("2026-06-02T12:00:00Z")).toEqual({ value: 0, unit: "second" });
expect(relativeAge("not-a-date")).toEqual({ value: 0, unit: "second" });
});
it("agrees with the compact English form it backs", () => {
for (const iso of [
"2026-06-01T11:59:45Z",
"2026-06-01T11:30:00Z",
"2026-05-31T18:00:00Z",
"2026-05-03T12:00:00Z",
"2025-08-01T12:00:00Z",
"2025-01-01T00:00:00Z",
]) {
const age = relativeAge(iso);
const compact = relativeTime(iso);
if (age.unit === "second") expect(compact).toBe("just now");
else expect(compact.startsWith(String(Math.abs(age.value)))).toBe(true);
}
});
});
// ── fetchFeed ─────────────────────────────────────────────────────────
function json(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "content-type": "application/json" },
});
}
describe("fetchFeed", () => {
const ISSUES = [
{
number: 4901,
title: "Ticker shows nothing on first paint",
html_url: "https://github.com/Hmbown/CodeWhale/issues/4901",
state: "open",
user: { login: "asto18089", avatar_url: "https://avatars/1" },
created_at: "2026-06-01T09:00:00Z",
updated_at: "2026-06-01T11:00:00Z",
comments: 2,
labels: [{ name: "bug", color: "d73a4a" }],
author_association: "CONTRIBUTOR",
},
{
number: 4880,
title: "Fixed upstream",
html_url: "https://github.com/Hmbown/CodeWhale/issues/4880",
state: "closed",
user: { login: "Inference1", avatar_url: "https://avatars/2" },
created_at: "2026-03-02T09:00:00Z",
updated_at: "2026-06-01T10:00:00Z",
closed_at: "2026-05-30T09:00:00Z",
comments: 0,
labels: [],
author_association: "NONE",
},
{
// The issues endpoint returns pull requests too; they must not double up.
number: 4899,
title: "PR echoed by the issues endpoint",
html_url: "https://github.com/Hmbown/CodeWhale/pull/4899",
state: "open",
user: { login: "bistack", avatar_url: "https://avatars/3" },
created_at: "2026-06-01T08:00:00Z",
updated_at: "2026-06-01T08:30:00Z",
comments: 0,
labels: [],
pull_request: { url: "https://api.github.com/…" },
},
];
const PULLS = [
{
number: 4899,
title: "fix(tui): keep the composer caret on resize",
html_url: "https://github.com/Hmbown/CodeWhale/pull/4899",
state: "closed",
user: { login: "shenjackyuanjie", avatar_url: "https://avatars/4" },
created_at: "2026-05-29T09:00:00Z",
updated_at: "2026-06-01T11:30:00Z",
closed_at: "2026-05-31T18:00:00Z",
merged_at: "2026-05-31T18:00:00Z",
comments: 4,
labels: [],
author_association: "FIRST_TIME_CONTRIBUTOR",
},
{
number: 4902,
title: "wip: sandbox notes",
html_url: "https://github.com/Hmbown/CodeWhale/pull/4902",
state: "open",
user: { login: "h3c-hexin", avatar_url: "https://avatars/5" },
created_at: "2026-06-01T07:00:00Z",
updated_at: "2026-06-01T07:30:00Z",
draft: true,
comments: 0,
labels: [],
author_association: "CONTRIBUTOR",
},
];
const RELEASES = [
{
tag_name: "v0.9.4",
name: "v0.9.4",
html_url: "https://github.com/Hmbown/CodeWhale/releases/tag/v0.9.4",
created_at: "2026-05-28T09:00:00Z",
published_at: "2026-05-28T12:00:00Z",
author: { login: "Hmbown", avatar_url: "https://avatars/6" },
},
{
tag_name: "v0.9.5-rc1",
name: "v0.9.5-rc1",
html_url: "https://github.com/Hmbown/CodeWhale/releases/tag/v0.9.5-rc1",
created_at: "2026-06-01T09:00:00Z",
published_at: null,
draft: true,
author: { login: "Hmbown", avatar_url: "https://avatars/6" },
},
];
const requested: string[] = [];
beforeEach(() => {
requested.length = 0;
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
requested.push(url);
if (url.includes("/issues?")) return json(ISSUES);
if (url.includes("/pulls?")) return json(PULLS);
if (url.includes("/releases?")) return json(RELEASES);
return new Response("{}", { status: 404 });
}),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("covers issues, pulls, and releases in three calls — no per-item follow-ups", async () => {
await fetchFeed(undefined, 10);
expect(requested).toHaveLength(3);
expect(requested.some((u) => u.includes("/issues?"))).toBe(true);
expect(requested.some((u) => u.includes("/pulls?"))).toBe(true);
expect(requested.some((u) => u.includes("/releases?"))).toBe(true);
});
it("names the contributor and dates each verb by the event, not the last comment", async () => {
const feed = await fetchFeed(undefined, 10);
const merged = feed.find((f) => f.number === 4899 && f.kind === "pull");
expect(merged?.state).toBe("merged");
expect(merged?.author).toBe("shenjackyuanjie");
// Merged at 18:00 on the 31st; last touched at 11:30 the next day.
expect(merged?.eventAt).toBe("2026-05-31T18:00:00Z");
const openIssue = feed.find((f) => f.number === 4901);
expect(openIssue?.state).toBe("open");
expect(openIssue?.eventAt).toBe(openIssue?.createdAt);
const closedIssue = feed.find((f) => f.number === 4880);
expect(closedIssue?.state).toBe("closed");
expect(closedIssue?.eventAt).toBe("2026-05-30T09:00:00Z");
const draft = feed.find((f) => f.number === 4902);
expect(draft?.state).toBe("draft");
});
it("passes GitHub's first-time-contributor verdict through verbatim", async () => {
const feed = await fetchFeed(undefined, 10);
expect(feed.find((f) => f.number === 4899 && f.kind === "pull")?.firstTimeContributor).toBe(
true,
);
expect(feed.find((f) => f.number === 4901)?.firstTimeContributor).toBe(false);
// "NONE" is not a first-timer — only GitHub's own FIRST_TIME_CONTRIBUTOR is.
expect(feed.find((f) => f.number === 4880)?.firstTimeContributor).toBe(false);
});
it("carries published releases and drops unpublished drafts", async () => {
const feed = await fetchFeed(undefined, 10);
const releases = feed.filter((f) => f.kind === "release");
expect(releases).toHaveLength(1);
expect(releases[0].tag).toBe("v0.9.4");
expect(releases[0].state).toBe("published");
expect(releases[0].eventAt).toBe("2026-05-28T12:00:00Z");
expect(feed.some((f) => f.tag === "v0.9.5-rc1")).toBe(false);
});
it("keeps a recent release in view when a busy window would bury it", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-06-01T12:00:00Z"));
try {
// Only two slots: pure recency would fill both with the newest threads.
const feed = await fetchFeed(undefined, 2);
expect(feed).toHaveLength(2);
expect(feed.filter((f) => f.kind === "release").map((f) => f.tag)).toEqual(["v0.9.4"]);
} finally {
vi.useRealTimers();
}
});
it("does not pin a stale release beside today's threads", async () => {
vi.useFakeTimers();
// Two years on from the last tag: a quiet quarter reads as a quiet quarter.
vi.setSystemTime(new Date("2028-06-01T12:00:00Z"));
try {
const feed = await fetchFeed(undefined, 2);
expect(feed).toHaveLength(2);
expect(feed.some((f) => f.kind === "release")).toBe(false);
} finally {
vi.useRealTimers();
}
});
it("does not double-count pull requests echoed by the issues endpoint", async () => {
const feed = await fetchFeed(undefined, 10);
expect(feed.filter((f) => f.number === 4899)).toHaveLength(1);
expect(feed.filter((f) => f.kind === "issue").map((f) => f.number).sort()).toEqual([
4880, 4901,
]);
});
it("returns an empty feed — never a placeholder — when GitHub is unreachable", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("rate limited", { status: 403 })),
);
expect(await fetchFeed(undefined, 10)).toEqual([]);
});
it("reports a refused list call as unavailable, not as an empty record", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("rate limited", { status: 403 })),
);
expect(await loadFeed(undefined, 10)).toEqual({
items: [],
issuesStatus: "unavailable",
pullsStatus: "unavailable",
});
});
it("keeps what arrived and still flags the load when one list call fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (url.includes("/pulls?")) return new Response("rate limited", { status: 403 });
if (url.includes("/issues?")) return json(ISSUES);
return json([]);
}),
);
const load = await loadFeed(undefined, 10);
// Each column answers for itself: the issues list answered, so the
// issues column must not be told "the source did not answer".
expect(load.issuesStatus).toBe("ok");
expect(load.pullsStatus).toBe("unavailable");
expect(load.items.map((i) => i.number)).toEqual([4901, 4880]);
});
it("reports ok — so an empty list means empty — when every list call answered", async () => {
vi.stubGlobal("fetch", vi.fn(async () => json([])));
expect(await loadFeed(undefined, 10)).toEqual({
items: [],
issuesStatus: "ok",
pullsStatus: "ok",
});
});
});
describe("fetchFeed — bot authors", () => {
// The wire is contributor-forward: GitHub's own `[bot]` login marker keeps
// automated maintenance off the strip, while a bot-published release keeps
// its slot and drops its byline.
const ISSUES = [
{
number: 101,
title: "Automated close sweep",
html_url: "https://github.com/Hmbown/CodeWhale/issues/101",
state: "closed",
user: { login: "github-actions[bot]", avatar_url: "https://avatars/bot1" },
created_at: "2026-06-01T09:00:00Z",
updated_at: "2026-06-01T11:00:00Z",
closed_at: "2026-06-01T10:30:00Z",
comments: 0,
labels: [],
author_association: "NONE",
},
{
number: 102,
title: "Real report",
html_url: "https://github.com/Hmbown/CodeWhale/issues/102",
state: "open",
user: { login: "vFONGv", avatar_url: "https://avatars/h1" },
created_at: "2026-06-01T08:00:00Z",
updated_at: "2026-06-01T08:00:00Z",
comments: 0,
labels: [],
author_association: "FIRST_TIME_CONTRIBUTOR",
},
];
const PULLS = [
{
number: 103,
title: "chore(deps): bump serde from 1.0.219 to 1.0.220",
html_url: "https://github.com/Hmbown/CodeWhale/pull/103",
state: "closed",
user: { login: "dependabot[bot]", avatar_url: "https://avatars/bot2" },
created_at: "2026-05-31T09:00:00Z",
updated_at: "2026-06-01T07:00:00Z",
merged_at: "2026-06-01T07:00:00Z",
comments: 0,
labels: [],
author_association: "CONTRIBUTOR",
},
{
number: 104,
title: "fix(tui): keep the whale rail steady",
html_url: "https://github.com/Hmbown/CodeWhale/pull/104",
state: "closed",
user: { login: "bistack", avatar_url: "https://avatars/h2" },
created_at: "2026-05-30T09:00:00Z",
updated_at: "2026-06-01T06:00:00Z",
merged_at: "2026-06-01T06:00:00Z",
comments: 1,
labels: [],
author_association: "CONTRIBUTOR",
},
];
const RELEASES = [
{
tag_name: "v0.9.4",
name: "v0.9.4",
html_url: "https://github.com/Hmbown/CodeWhale/releases/tag/v0.9.4",
created_at: "2026-05-28T09:00:00Z",
published_at: "2026-05-28T12:00:00Z",
author: { login: "release-train[bot]", avatar_url: "https://avatars/bot3" },
},
];
beforeEach(() => {
vi.stubGlobal(
"fetch",
vi.fn(async (url: string) => {
if (url.includes("/issues?")) return json(ISSUES);
if (url.includes("/pulls?")) return json(PULLS);
if (url.includes("/releases?")) return json(RELEASES);
return new Response("{}", { status: 404 });
}),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("keeps bot-authored issues and pulls off the contributor wire", async () => {
const feed = await fetchFeed(undefined, 10);
expect(feed.some((f) => f.author === "github-actions[bot]")).toBe(false);
expect(feed.some((f) => f.author === "dependabot[bot]")).toBe(false);
expect(feed.some((f) => f.number === 102 && f.kind === "issue")).toBe(true);
expect(feed.some((f) => f.number === 104 && f.kind === "pull")).toBe(true);
});
it("keeps a bot-published release in view, minus its byline", async () => {
const feed = await fetchFeed(undefined, 10);
const release = feed.find((f) => f.kind === "release");
expect(release?.tag).toBe("v0.9.4");
expect(release?.author).toBe("");
expect(release?.authorAvatar).toBe("");
});
});
// ── lastPageFromLink (via re-export test) ──────────────────────────────
describe("lastPageFromLink", () => {
it("returns undefined for null input", () => {
expect(lastPageFromLink(null)).toBeUndefined();
});
it("returns undefined for empty string", () => {
expect(lastPageFromLink("")).toBeUndefined();
});
it("extracts page from Link header with last rel", () => {
const link =
'<https://api.github.com/repos/Hmbown/CodeWhale/issues?page=5>; rel="last"';
expect(lastPageFromLink(link)).toBe(5);
});
it("extracts page from multi-part Link header", () => {
const link = [
'<https://api.github.com/repos/Hmbown/CodeWhale/issues?page=1>; rel="prev"',
'<https://api.github.com/repos/Hmbown/CodeWhale/issues?page=3>; rel="last"',
].join(", ");
expect(lastPageFromLink(link)).toBe(3);
});
it("returns undefined when no last rel present", () => {
const link =
'<https://api.github.com/repos/Hmbown/CodeWhale/issues?page=1>; rel="prev"';
expect(lastPageFromLink(link)).toBeUndefined();
});
it("returns undefined for invalid URL format", () => {
const link = "not-a-valid-link-header; rel=last";
expect(lastPageFromLink(link)).toBeUndefined();
});
});