// The hub client: typed fetch over /api/v1 (hub spec §12.1) using the // generated types in hubapi.d.ts, plus URL helpers. No vscode imports, // so it is tested with plain Node against a real hub. import type * as api from "./hubapi"; export class HubError extends Error { constructor( readonly status: number, readonly title: string, readonly detail: string, ) { super(`${status} ${title}: ${detail}`); } } /** `https://hub/owner/name` → { base, owner, name }; undefined for anything else. */ export function parseRepoUrl(url: string): { base: string; owner: string; name: string } | undefined { const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.trim()); if (!m || m[2] === "api") { return undefined; } return { base: m[1], owner: m[2], name: m[3] }; } export interface Session { base: string; token: string; username?: string; } export class HubClient { constructor( readonly base: string, private readonly token: string | undefined, private readonly fetchImpl: typeof fetch = fetch, ) {} private async request(method: string, path: string, body?: unknown): Promise { const headers: Record = { accept: "application/json" }; if (this.token) { headers.authorization = `Bearer ${this.token}`; } if (body !== undefined) { headers["content-type"] = "application/json"; } const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }); if (res.status === 204) { return undefined as T; } const text = await res.text(); if (!res.ok) { try { const p = JSON.parse(text) as api.Problem; throw new HubError(p.status, p.title, p.detail); } catch (e) { if (e instanceof HubError) { throw e; } throw new HubError(res.status, res.statusText, text); } } return (text ? JSON.parse(text) : undefined) as T; } me(): Promise { return this.request("GET", "/user"); } /** The caller's inbox: unread count and newest entries (needs user:read). */ notifications(limit = 50): Promise { return this.request("GET", `/notifications?limit=${limit}`); } markNotificationRead(id: number): Promise { return this.request("POST", `/notifications/${id}/read`); } markAllNotificationsRead(): Promise { return this.request("POST", "/notifications/read"); } repositories(): Promise { return this.request("GET", "/repos"); } repository(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}`); } proposals(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals`); } proposal(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`); } createProposal(owner: string, name: string, p: api.NewProposal): Promise { return this.request("POST", `/repos/${owner}/${name}/proposals`, p); } proposalComments(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`); } /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */ commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise { return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null }); } reviews(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`); } review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise { return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body }); } /** The files a proposal changes, target state against projected state. */ proposalFiles(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`); } /** A file's text on one side of a proposal; undefined when it does not exist there. */ async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise { const headers: Record = {}; if (this.token) { headers.authorization = `Bearer ${this.token}`; } const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers }); if (res.status === 404) { return undefined; } if (!res.ok) { throw new HubError(res.status, res.statusText, await res.text()); } return res.text(); } proposalChecks(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`); } issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise { return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`); } issue(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/issues/${number}`); } createIssue(owner: string, name: string, title: string, body = ""): Promise { return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body }); } issueComments(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`); } commentIssue(owner: string, name: string, number: number, body: string): Promise { return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body }); } setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise { return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason }); } history(owner: string, name: string, reference: string, limit = 50): Promise { return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`); } bookmarks(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/bookmarks`); } search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> { return this.request("GET", `/search?q=${encodeURIComponent(q)}`); } } /** Web URLs on the hub for things the remote provider is asked about. */ export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string { const repo = `${base}/${owner}/${name}`; switch (target.kind) { case "repository": return repo; case "bookmark": return `${repo}/tree/${encodeURIComponent(String(target.name))}`; case "change": return `${repo}/change/${target.hash}`; case "file": { const line = typeof target.line === "number" ? `#L${target.line}` : ""; return `${repo}/file/${encodeURIComponent(String(target.reference))}/${String(target.path)}${line}`; } case "proposals": return `${repo}/proposals`; case "issues": return `${repo}/issues`; case "proposal": return `${repo}/proposal/${target.number}`; case "issue": return `${repo}/issue/${target.number}`; default: return repo; } } /** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */ export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean { if (!username || p.author === username) { return false; } if (p.state !== "open") { return false; } const mine = p.approvals.find((a) => a.account === username); return !mine || !mine.sealed; } /** Which proposal, side and file a diff document shows. */ export interface DiffRef { base: string; owner: string; name: string; number: number; side: "base" | "head"; path: string; } /** The query string of a diff document's URI. */ export function encodeDiffQuery(r: DiffRef): string { return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString(); } /** Parse a diff document's query and path back; undefined if it is not one. */ export function decodeDiffQuery(query: string, path: string): DiffRef | undefined { const q = new URLSearchParams(query); const number = Number(q.get("number")); const side = q.get("side"); const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")]; if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) { return undefined; } return { base, owner, name, number, side, path: path.replace(/^\/+/, "") }; } /** What a hub page URL points at, for opening it in the editor instead of a browser. */ export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string }; export function hubTarget(url: string): HubTarget { const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url); if (!m) { return { kind: "other", url }; } return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) }; }