From b33d8fb41bf25faeeaf69829097685fa0ea32de4 Mon Sep 17 00:00:00 2001 From: Bulat Yapparov Date: Mon, 16 Nov 2026 23:28:21 +0000 Subject: [PATCH] feat(github): issue dependencies API (blocked_by / blocking) Adds GitHub's issue dependency endpoints: - GET/POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by (POST body { issue_id }), DELETE .../blocked_by/{issue_id} - GET /repos/{owner}/{repo}/issues/{number}/dependencies/blocking Edges may cross repositories. Reads need issues read on the path issue and lists omit related issues the caller cannot see; writes need issues write. Unknown or invisible issues return 404; a self-reference, a duplicate edge, a malformed id or more than 50 relationships return 422. Issue objects carry issue_dependencies_summary (open counts plus totals). Seeding edges and the issue_dependencies webhook are not included yet. Closes #9 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Br5cbz3i7Y5PaRdx3DUfXx --- .../src/__tests__/issue-dependencies.test.ts | 184 ++++++++++++++++++ packages/@emulators/github/src/entities.ts | 6 + packages/@emulators/github/src/helpers.ts | 19 ++ packages/@emulators/github/src/index.ts | 2 + .../github/src/routes/issue-dependencies.ts | 102 ++++++++++ packages/@emulators/github/src/store.ts | 6 + packages/github-emulator/README.md | 2 + 7 files changed, 321 insertions(+) create mode 100644 packages/@emulators/github/src/__tests__/issue-dependencies.test.ts create mode 100644 packages/@emulators/github/src/routes/issue-dependencies.ts diff --git a/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts new file mode 100644 index 000000000..a647c21e4 --- /dev/null +++ b/packages/@emulators/github/src/__tests__/issue-dependencies.test.ts @@ -0,0 +1,184 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + Hono, + Store, + WebhookDispatcher, + authMiddleware, + createApiErrorHandler, + createErrorHandler, + type TokenMap, +} from "@emulators/core"; +import { githubPlugin, seedFromConfig } from "../index.js"; +import { getGitHubStore } from "../store.js"; +import { MAX_ISSUE_DEPENDENCIES } from "../routes/issue-dependencies.js"; + +const base = "http://localhost:4000"; + +type Issue = { + id: number; + number: number; + issue_dependencies_summary: { + blocked_by: number; + blocking: number; + total_blocked_by: number; + total_blocking: number; + }; +}; + +function createTestApp() { + const store = new Store(); + const tokenMap: TokenMap = new Map([ + ["octocat-token", { login: "octocat", id: 1, scopes: ["repo", "user"] }], + ["hubot-token", { login: "hubot", id: 2, scopes: ["repo", "user"] }], + ]); + const app = new Hono(); + app.onError(createApiErrorHandler()); + app.use("*", createErrorHandler()); + app.use("*", authMiddleware(tokenMap)); + githubPlugin.register(app as any, store, new WebhookDispatcher(), base, tokenMap); + githubPlugin.seed?.(store, base); + seedFromConfig(store, base, { + users: [{ login: "octocat" }, { login: "hubot" }], + repos: [ + { owner: "octocat", name: "alpha" }, + { owner: "octocat", name: "beta" }, + { owner: "hubot", name: "secret", private: true }, + ], + }); + return { app, store }; +} + +describe("GitHub issue dependencies", () => { + let app: Hono; + let store: Store; + + const call = (path: string, init: { method?: string; token?: string | null; body?: unknown } = {}) => { + const headers: Record = {}; + const token = init.token === undefined ? "octocat-token" : init.token; + if (token) headers.Authorization = `Bearer ${token}`; + if (init.body !== undefined) headers["Content-Type"] = "application/json"; + return app.request(`${base}${path}`, { + method: init.method ?? "GET", + headers, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + }); + }; + + const createIssue = async (repo: string, token = "octocat-token"): Promise => { + const res = await call(`/repos/${repo}/issues`, { method: "POST", token, body: { title: `Issue in ${repo}` } }); + expect(res.status).toBe(201); + return (await res.json()) as Issue; + }; + + const addBlocker = (repo: string, number: number, issueId: unknown, token?: string | null) => + call(`/repos/${repo}/issues/${number}/dependencies/blocked_by`, { + method: "POST", + token, + body: { issue_id: issueId }, + }); + + beforeEach(() => { + ({ app, store } = createTestApp()); + }); + + it("adds, lists in both directions and removes an edge across repositories", async () => { + const blocked = await createIssue("octocat/alpha"); + const blocker = await createIssue("octocat/beta"); + + const added = await addBlocker("octocat/alpha", blocked.number, blocker.id); + expect(added.status).toBe(201); + expect(((await added.json()) as Issue).id).toBe(blocker.id); + + const blockedBy = (await ( + await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`) + ).json()) as Issue[]; + expect(blockedBy.map((issue) => issue.id)).toEqual([blocker.id]); + const blocking = (await ( + await call(`/repos/octocat/beta/issues/${blocker.number}/dependencies/blocking`) + ).json()) as Issue[]; + expect(blocking.map((issue) => issue.id)).toEqual([blocked.id]); + + const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue) + .issue_dependencies_summary; + expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 1, total_blocking: 0 }); + + const removed = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, { + method: "DELETE", + }); + expect(removed.status).toBe(200); + expect(((await removed.json()) as Issue).id).toBe(blocker.id); + expect(await (await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`)).json()).toEqual( + [], + ); + const again = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by/${blocker.id}`, { + method: "DELETE", + }); + expect(again.status).toBe(404); + }); + + it("counts only open issues in blocked_by and blocking, and all in the totals", async () => { + const blocked = await createIssue("octocat/alpha"); + const open = await createIssue("octocat/alpha"); + const closed = await createIssue("octocat/alpha"); + await addBlocker("octocat/alpha", blocked.number, open.id); + await addBlocker("octocat/alpha", blocked.number, closed.id); + await call(`/repos/octocat/alpha/issues/${closed.number}`, { method: "PATCH", body: { state: "closed" } }); + + const summary = ((await (await call(`/repos/octocat/alpha/issues/${blocked.number}`)).json()) as Issue) + .issue_dependencies_summary; + expect(summary).toEqual({ blocked_by: 1, blocking: 0, total_blocked_by: 2, total_blocking: 0 }); + }); + + it("rejects a self-reference, a duplicate edge and a malformed id with 422", async () => { + const blocked = await createIssue("octocat/alpha"); + const blocker = await createIssue("octocat/alpha"); + expect((await addBlocker("octocat/alpha", blocked.number, blocked.id)).status).toBe(422); + expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201); + expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(422); + expect((await addBlocker("octocat/alpha", blocked.number, "not-a-number")).status).toBe(422); + }); + + it("returns 404 for an unknown issue, an unknown issue id and an issue the caller cannot see", async () => { + const blocked = await createIssue("octocat/alpha"); + const hidden = await createIssue("hubot/secret", "hubot-token"); + expect((await call("/repos/octocat/alpha/issues/999/dependencies/blocked_by")).status).toBe(404); + expect((await addBlocker("octocat/alpha", blocked.number, 999_999)).status).toBe(404); + expect((await addBlocker("octocat/alpha", blocked.number, hidden.id)).status).toBe(404); + expect((await call(`/repos/hubot/secret/issues/${hidden.number}/dependencies/blocking`)).status).toBe(404); + }); + + it("omits related issues the caller cannot see from lists", async () => { + const blocked = await createIssue("octocat/alpha"); + const hidden = await createIssue("hubot/secret", "hubot-token"); + getGitHubStore(store).issueDependencies.insert({ blocked_issue_id: blocked.id, blocking_issue_id: hidden.id }); + + const asOctocat = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`); + expect(await asOctocat.json()).toEqual([]); + const asHubot = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by`, { + token: "hubot-token", + }); + expect(((await asHubot.json()) as Issue[]).map((issue) => issue.id)).toEqual([hidden.id]); + }); + + it("requires authentication to add an edge", async () => { + const blocked = await createIssue("octocat/alpha"); + const blocker = await createIssue("octocat/alpha"); + expect((await addBlocker("octocat/alpha", blocked.number, blocker.id, null)).status).toBe(401); + }); + + it("paginates and caps each issue at the GitHub relationship limit", async () => { + const blocked = await createIssue("octocat/alpha"); + const blockers: Issue[] = []; + for (let i = 0; i <= MAX_ISSUE_DEPENDENCIES; i++) blockers.push(await createIssue("octocat/beta")); + for (const blocker of blockers.slice(0, MAX_ISSUE_DEPENDENCIES)) { + expect((await addBlocker("octocat/alpha", blocked.number, blocker.id)).status).toBe(201); + } + expect((await addBlocker("octocat/alpha", blocked.number, blockers[MAX_ISSUE_DEPENDENCIES]!.id)).status).toBe(422); + + const page = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=20&page=3`); + expect(((await page.json()) as Issue[]).length).toBe(10); + expect(page.headers.get("Link")).toContain('rel="first"'); + const all = await call(`/repos/octocat/alpha/issues/${blocked.number}/dependencies/blocked_by?per_page=100`); + expect(((await all.json()) as Issue[]).length).toBe(MAX_ISSUE_DEPENDENCIES); + }); +}); diff --git a/packages/@emulators/github/src/entities.ts b/packages/@emulators/github/src/entities.ts index be4e8f08e..dc5d091b7 100644 --- a/packages/@emulators/github/src/entities.ts +++ b/packages/@emulators/github/src/entities.ts @@ -237,6 +237,12 @@ export interface GitHubIssueEvent extends Entity { rename: { from: string; to: string } | null; } +/** A directed "blocked by" edge: `blocked_issue_id` cannot proceed until `blocking_issue_id` is done. */ +export interface GitHubIssueDependency extends Entity { + blocked_issue_id: number; + blocking_issue_id: number; +} + export interface GitHubBranch extends Entity { repo_id: number; name: string; diff --git a/packages/@emulators/github/src/helpers.ts b/packages/@emulators/github/src/helpers.ts index 963172c35..352f2e6d7 100644 --- a/packages/@emulators/github/src/helpers.ts +++ b/packages/@emulators/github/src/helpers.ts @@ -384,6 +384,25 @@ export function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: str timeline_url: `${repoUrl}/issues/${issue.number}/timeline`, performed_via_github_app: null, author_association: computeAuthorAssociation(store, issue.user_id, issue.repo_id), + issue_dependencies_summary: issueDependenciesSummary(issue, store), + }; +} + +/** Counts as GitHub reports them: `blocked_by` and `blocking` count open issues, the totals count all. */ +function issueDependenciesSummary(issue: GitHubIssue, store: GitHubStore) { + const blockers = store.issueDependencies + .findBy("blocked_issue_id", issue.id) + .map((edge) => store.issues.get(edge.blocking_issue_id)) + .filter((other): other is GitHubIssue => !!other); + const blocked = store.issueDependencies + .findBy("blocking_issue_id", issue.id) + .map((edge) => store.issues.get(edge.blocked_issue_id)) + .filter((other): other is GitHubIssue => !!other); + return { + blocked_by: blockers.filter((other) => other.state === "open").length, + blocking: blocked.filter((other) => other.state === "open").length, + total_blocked_by: blockers.length, + total_blocking: blocked.length, }; } diff --git a/packages/@emulators/github/src/index.ts b/packages/@emulators/github/src/index.ts index 82f475fbc..61630f9aa 100644 --- a/packages/@emulators/github/src/index.ts +++ b/packages/@emulators/github/src/index.ts @@ -18,6 +18,7 @@ import { generateNodeId } from "./helpers.js"; import { usersRoutes } from "./routes/users.js"; import { reposRoutes } from "./routes/repos.js"; import { issuesRoutes } from "./routes/issues.js"; +import { issueDependenciesRoutes } from "./routes/issue-dependencies.js"; import { pullsRoutes } from "./routes/pulls.js"; import { commentsRoutes } from "./routes/comments.js"; import { reviewsRoutes } from "./routes/reviews.js"; @@ -700,6 +701,7 @@ export const githubPlugin: ServicePlugin = { usersRoutes(ctx); reposRoutes(ctx); issuesRoutes(ctx); + issueDependenciesRoutes(ctx); pullsRoutes(ctx); commentsRoutes(ctx); reviewsRoutes(ctx); diff --git a/packages/@emulators/github/src/routes/issue-dependencies.ts b/packages/@emulators/github/src/routes/issue-dependencies.ts new file mode 100644 index 000000000..b41a9eff8 --- /dev/null +++ b/packages/@emulators/github/src/routes/issue-dependencies.ts @@ -0,0 +1,102 @@ +import type { Context, RouteContext } from "@emulators/core"; +import { ApiError, parseJsonBody, parsePagination, setLinkHeader } from "@emulators/core"; +import type { AuthUser } from "@emulators/core"; +import { getGitHubStore } from "../store.js"; +import type { GitHubStore } from "../store.js"; +import type { GitHubIssue, GitHubRepo } from "../entities.js"; +import { assertIssueWrite, assertRepoPermission, notFoundResponse } from "../route-helpers.js"; +import { formatIssue, lookupRepo } from "../helpers.js"; + +/** GitHub limits each issue to 50 relationships of each kind. */ +export const MAX_ISSUE_DEPENDENCIES = 50; + +type Direction = "blocked_by" | "blocking"; + +function canRead(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): boolean { + try { + assertRepoPermission(gh, authUser, repo, "issues"); + return repo.has_issues; + } catch { + return false; + } +} + +/** The issue in the path, visible to the caller, or 404 as on GitHub. */ +function pathIssue(gh: GitHubStore, c: Context, required: "read" | "write"): { repo: GitHubRepo; issue: GitHubIssue } { + const repo = lookupRepo(gh, c.req.param("owner")!, c.req.param("repo")!); + if (!repo) throw notFoundResponse(); + if (required === "write") assertIssueWrite(gh, c.get("authUser"), repo); + else assertRepoPermission(gh, c.get("authUser"), repo, "issues"); + if (!repo.has_issues) throw notFoundResponse(); + const issueNumber = Number(c.req.param("issue_number")); + if (!Number.isInteger(issueNumber)) throw notFoundResponse(); + const issue = gh.issues.findBy("repo_id", repo.id).find((i) => i.number === issueNumber && !i.is_pull_request); + if (!issue) throw notFoundResponse(); + return { repo, issue }; +} + +/** The other end of an edge, addressed by its issue id; it may live in another repository. */ +function issueById(gh: GitHubStore, authUser: AuthUser | undefined, raw: unknown): GitHubIssue { + const id = typeof raw === "string" && /^\d+$/.test(raw) ? Number(raw) : raw; + if (typeof id !== "number" || !Number.isInteger(id)) throw new ApiError(422, "Validation failed"); + const issue = gh.issues.get(id); + const repo = issue ? gh.repos.get(issue.repo_id) : undefined; + if (!issue || issue.is_pull_request || !repo || !canRead(gh, authUser, repo)) throw notFoundResponse(); + return issue; +} + +function related(gh: GitHubStore, issue: GitHubIssue, direction: Direction): GitHubIssue[] { + const edges = + direction === "blocked_by" + ? gh.issueDependencies.findBy("blocked_issue_id", issue.id).map((edge) => edge.blocking_issue_id) + : gh.issueDependencies.findBy("blocking_issue_id", issue.id).map((edge) => edge.blocked_issue_id); + return edges.map((id) => gh.issues.get(id)).filter((other): other is GitHubIssue => !!other); +} + +export function issueDependenciesRoutes({ app, store, baseUrl }: RouteContext): void { + const gh = getGitHubStore(store); + + const list = (direction: Direction) => (c: Context) => { + const { issue } = pathIssue(gh, c, "read"); + const authUser = c.get("authUser"); + const visible = related(gh, issue, direction).filter((other) => { + const repo = gh.repos.get(other.repo_id); + return !!repo && canRead(gh, authUser, repo); + }); + const { page, per_page } = parsePagination(c); + setLinkHeader(c, visible.length, page, per_page); + const start = (page - 1) * per_page; + return c.json(visible.slice(start, start + per_page).map((other) => formatIssue(other, gh, baseUrl))); + }; + + app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", list("blocked_by")); + app.get("/repos/:owner/:repo/issues/:issue_number/dependencies/blocking", list("blocking")); + + app.post("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by", async (c) => { + const { issue } = pathIssue(gh, c, "write"); + const body = (await parseJsonBody(c)) as { issue_id?: unknown }; + const blocking = issueById(gh, c.get("authUser"), body.issue_id); + if (blocking.id === issue.id) throw new ApiError(422, "Validation failed"); + const existing = gh.issueDependencies.findBy("blocked_issue_id", issue.id); + if (existing.some((edge) => edge.blocking_issue_id === blocking.id)) throw new ApiError(422, "Validation failed"); + if ( + existing.length >= MAX_ISSUE_DEPENDENCIES || + gh.issueDependencies.findBy("blocking_issue_id", blocking.id).length >= MAX_ISSUE_DEPENDENCIES + ) { + throw new ApiError(422, "Validation failed"); + } + gh.issueDependencies.insert({ blocked_issue_id: issue.id, blocking_issue_id: blocking.id }); + return c.json(formatIssue(blocking, gh, baseUrl), 201); + }); + + app.delete("/repos/:owner/:repo/issues/:issue_number/dependencies/blocked_by/:issue_id", (c) => { + const { issue } = pathIssue(gh, c, "write"); + const blocking = issueById(gh, c.get("authUser"), c.req.param("issue_id")); + const edge = gh.issueDependencies + .findBy("blocked_issue_id", issue.id) + .find((candidate) => candidate.blocking_issue_id === blocking.id); + if (!edge) throw notFoundResponse(); + gh.issueDependencies.delete(edge.id); + return c.json(formatIssue(blocking, gh, baseUrl)); + }); +} diff --git a/packages/@emulators/github/src/store.ts b/packages/@emulators/github/src/store.ts index a069391cf..fbbcd43df 100644 --- a/packages/@emulators/github/src/store.ts +++ b/packages/@emulators/github/src/store.ts @@ -14,6 +14,7 @@ import type { GitHubComment, GitHubReview, GitHubIssueEvent, + GitHubIssueDependency, GitHubBranch, GitHubBranchProtection, GitHubRef, @@ -53,6 +54,7 @@ export interface GitHubStore { comments: Collection; reviews: Collection; issueEvents: Collection; + issueDependencies: Collection; branches: Collection; branchProtections: Collection; refs: Collection; @@ -93,6 +95,10 @@ export function getGitHubStore(store: Store): GitHubStore { comments: store.collection("github.comments", ["repo_id"]), reviews: store.collection("github.reviews", ["repo_id", "pull_number"]), issueEvents: store.collection("github.issue_events", ["repo_id", "issue_number"]), + issueDependencies: store.collection("github.issue_dependencies", [ + "blocked_issue_id", + "blocking_issue_id", + ]), branches: store.collection("github.branches", ["repo_id"]), branchProtections: store.collection("github.branch_protections", ["repo_id"]), refs: store.collection("github.refs", ["repo_id"]), diff --git a/packages/github-emulator/README.md b/packages/github-emulator/README.md index 2c675c8c8..86f535f42 100644 --- a/packages/github-emulator/README.md +++ b/packages/github-emulator/README.md @@ -20,6 +20,8 @@ try { Tokens are checked as GitHub checks them: a bearer token that the seed did not configure and the emulator did not issue (for example one issued before `reset()`) gets `401 Bad credentials`. Upstream emulate treats such a token as the default user; set `strict_scopes: false` in the seed to restore that. Private repositories answer `404` to callers who cannot see them. +Issue dependencies follow GitHub's REST API: `GET`/`POST /repos/{owner}/{repo}/issues/{number}/dependencies/blocked_by`, `DELETE .../dependencies/blocked_by/{issue_id}` and `GET .../dependencies/blocking`, across repositories, with GitHub's 50-relationship limit. Issue objects carry `issue_dependencies_summary`. + The default seed is synthetic. Configure `seed` and `tokens` for your tests. The instance provides `url`, `generatedSecrets`, `reset()`, and `close()`; tokens are resolved to seeded user IDs. Reset clears dynamic credentials and replays fixture state while preserving generated App keys. After installing the tarball, `npx github-emulator --help` lists CLI options. It listens on loopback port 4200 by default and accepts `--port`, `--host`, `--base-url`, and `--config` for JSON configuration.