// 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] }; } import { readFileSync } from "node:fs"; import * as http from "node:http"; import * as https from "node:https"; import * as tls from "node:tls"; 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"); } /** Recent OxygenFlow runs, newest first. */ flowRuns(owner: string, name: string, limit = 15): Promise { return this.request("GET", `/repos/${owner}/${name}/flow/runs?limit=${limit}`); } /** A run with its jobs. */ flowRun(owner: string, name: string, number: number): Promise { return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}`); } /** A job's log lines after `after` (a line's seq). */ flowLog(owner: string, name: string, number: number, job: string, after = 0): Promise { return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/log?after=${after}&limit=2000`); } /** Run the pipeline of a bookmark's current state, or of one change. */ startFlowRun(owner: string, name: string, target: { bookmark?: string; change?: string }): Promise<{ number: number; url: string }> { return this.request("POST", `/repos/${owner}/${name}/flow/runs`, target); } rerunFlowRun(owner: string, name: string, number: number): Promise<{ number: number; url: string }> { return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/rerun`); } 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`); } /** What the repository takes from and diffuses to (oxygenhub#153). */ diffusion(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/diffusion`); } releases(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/releases`); } createRelease(owner: string, name: string, r: api.NewRelease): Promise { return this.request("POST", `/repos/${owner}/${name}/releases`, r); } tags(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/tags`); } search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> { return this.request("GET", `/search?q=${encodeURIComponent(q)}`); } /** The caller's drops, newest first (oxygenhub#280). */ drops(): Promise { return this.request("GET", "/drops"); } /** Someone's public drops. */ userDrops(user: string): Promise { return this.request("GET", `/users/${encodeURIComponent(user)}/drops`); } /** A drop with each text file's content. */ drop(id: string): Promise { return this.request("GET", `/drops/${id}`); } createDrop(d: api.NewDrop): Promise { return this.request("POST", "/drops", d); } /** Change a drop: its title, description, visibility, or files (content null removes one). */ editDrop(id: string, e: api.DropEdit): Promise { return this.request("PATCH", `/drops/${id}`, e); } deleteDrop(id: string): Promise { return this.request("DELETE", `/drops/${id}`); } /** A copy of a drop, history and all, as the caller's (oxygenhub#349). */ forkDrop(id: string): Promise { return this.request("POST", `/drops/${id}/fork`); } starDrop(id: string, on: boolean): Promise { return this.request(on ? "PUT" : "DELETE", `/drops/${id}/star`); } dropComments(id: string): Promise { return this.request("GET", `/drops/${id}/comments`); } commentDrop(id: string, body: string): Promise { return this.request("POST", `/drops/${id}/comments`, { body }); } deleteDropComment(id: string, n: number): Promise { return this.request("DELETE", `/drops/${id}/comments/${n}`); } /** Approve or reject a job waiting on its approval rules (oxygenflow#57). */ decideFlowJob(owner: string, name: string, number: number, job: string, approve: boolean): Promise { return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/${approve ? "approve" : "reject"}`); } /** Make a queued or running run urgent, with why (oxygenhub#244). */ expediteFlowRun(owner: string, name: string, number: number, reason: string): Promise { return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/expedite`, { reason }); } cancelFlowRun(owner: string, name: string, number: number): Promise { return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/cancel`); } /** The reports a job published (oxygenhub#348). */ jobReports(owner: string, name: string, number: number, job: string): Promise { return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/reports`); } /** Test reports on a bookmark, newest first. */ testReports(owner: string, name: string, bookmark?: string, limit = 1): Promise { const q = new URLSearchParams({ limit: String(limit), ...(bookmark ? { bookmark } : {}) }); return this.request("GET", `/repos/${owner}/${name}/tests?${q}`); } testReport(owner: string, name: string, id: number): Promise { return this.request("GET", `/repos/${owner}/${name}/tests/${id}`); } /** Make a draft ready for review, or turn an open proposal back into a draft (#313). */ setProposalDraft(owner: string, name: string, number: number, draft: boolean): Promise { return this.request("PATCH", `/repos/${owner}/${name}/proposals/${number}`, { draft }); } /** The dashboard's proposals; with `landable`, also what the caller can land now (#311). */ userProposals(landable = false): Promise { return this.request("GET", `/user/proposals${landable ? "?landable=true" : ""}`); } /** What a release's trust page shows: signatures, builds and the audit (#79). */ releaseTrust(owner: string, name: string, tag: string): Promise { return this.request("GET", `/repos/${owner}/${name}/releases/trust/${encodeURIComponent(tag)}`); } orgs(): Promise { return this.request("GET", "/user/orgs"); } createRepository(r: api.NewRepository): Promise { return this.request("POST", "/repos", r); } /** The assistants a new repository under `owner` may ask for its starting files (#347). */ starterAssistants(owner: string): Promise { return this.request("GET", `/user/starter?owner=${encodeURIComponent(owner)}`); } startStarter(owner: string, name: string, r: api.StarterRequest): Promise { return this.request("POST", `/repos/${owner}/${name}/starter`, r); } starterStatus(owner: string, name: string): Promise { return this.request("GET", `/repos/${owner}/${name}/starter`); } /** A file's bytes from the hub (a release asset), with the session's token. */ async download(url: string): Promise { const headers: Record = {}; if (this.token && url.startsWith(this.base + "/")) { headers.authorization = `Bearer ${this.token}`; } const res = await this.fetchImpl(url, { headers }); if (!res.ok) { throw new HubError(res.status, res.statusText, await res.text()); } return new Uint8Array(await res.arrayBuffer()); } } /** A release's trust report (the web's, not in the generated types). */ export interface ReleaseTrust { repository: string; tag: string; title: string; release_url: string; heads: string[]; tag_signer?: { key: string; name: string; email: string; account?: string | null } | null; /** `valid`, `unsigned`, `invalid: …` or `revoked`. */ tag_signature: string; since?: string | null; changes: number; authors: { who: { name: string; email: string; account?: string | null }; changes: number; signed: number; sealed: number; unsigned: number; revoked: number; invalid: number }[]; assets: { name: string; size: number; blake3: string; url: string; build?: { run: number; job: string; run_url: string; same_state_as_tag: boolean } | null }[]; audit: { verdict: "pass" | "warn" | "fail"; title: string; detail: string }[]; generated_ms: number; } /** A release's trust report as Markdown, for a preview beside the code. */ export function trustMarkdown(t: ReleaseTrust): string { const glyph = { pass: "✔", warn: "!", fail: "✘" } as const; const out = [`# Trust: ${t.title || t.tag}`, "", `${t.repository} · tag \`${t.tag}\` · ${t.heads.map((h) => h.slice(0, 12)).join("+")}`, ""]; const signer = t.tag_signer ? `${t.tag_signer.name} <${t.tag_signer.email}>` : ""; out.push(`- Tag signature: **${t.tag_signature}**${signer ? ` by ${signer}` : ""}`); out.push(`- ${t.changes} change${t.changes === 1 ? "" : "s"}${t.since ? ` since ${t.since}` : ""}`, ""); out.push("## Audit", ""); for (const c of t.audit) { out.push(`- ${glyph[c.verdict]} **${c.title}**${c.detail ? ` — ${c.detail}` : ""}`); } if (t.authors.length) { out.push("", "## Authors", "", "| Author | Changes | Signed | Sealed | Unsigned | Revoked | Invalid |", "|---|---:|---:|---:|---:|---:|---:|"); for (const a of t.authors) { out.push(`| ${a.who.account ?? a.who.name} | ${a.changes} | ${a.signed} | ${a.sealed} | ${a.unsigned} | ${a.revoked} | ${a.invalid} |`); } } if (t.assets.length) { out.push("", "## Assets", ""); for (const a of t.assets) { const build = a.build ? `built by [run #${a.build.run}](${a.build.run_url}) ${a.build.job}${a.build.same_state_as_tag ? "" : " (not the tagged state)"}` : "no attested build"; out.push(`- \`${a.name}\` · BLAKE3 \`${a.blake3.slice(0, 16)}…\` · ${build}`); } } out.push("", `[The release](${t.release_url})`, ""); return out.join("\n"); } /** 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 end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : ""; const line = typeof target.line === "number" ? `#L${target.line}${end}` : ""; // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks. return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${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}`; case "diffusion": return `${repo}/diffusion`; 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]) }; } /** * Release notes from history: the changes in `current` that `previous` * does not have, newest first, one line each (the message's subject). */ export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string { const seen = new Set(previous.map((c) => c.hash)); const lines = current .filter((c) => !seen.has(c.hash)) .sort((a, b) => b.when_ms - a.when_ms) .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`); const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:"; return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n"; } /** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */ export function looksPrerelease(tag: string): boolean { return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag); } /** * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a * self-signed certificate (Node's `fetch` takes no CA). The file is read on * each request, so a renewed certificate needs no reload. */ export function fetchTrusting(caFile: string): typeof fetch { return ((input: string | URL | Request, init?: RequestInit) => new Promise((resolve, reject) => { const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url); const secure = url.protocol === "https:"; let ca: string[] | undefined; if (secure) { try { ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")]; } catch (e) { reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`)); return; } } const headers: Record = {}; new Headers(init?.headers).forEach((v, k) => (headers[k] = v)); const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => { const chunks: Buffer[] = []; res.on("data", (c: Buffer) => chunks.push(c)); res.on("error", reject); res.on("end", () => { const status = res.statusCode ?? 0; const out = new Headers(); for (const [k, v] of Object.entries(res.headers)) { if (v !== undefined) { out.set(k, Array.isArray(v) ? v.join(", ") : String(v)); } } const empty = status === 204 || status === 304; resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out })); }); }); req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e }))); if (init?.body !== undefined && init.body !== null) { req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer)); } req.end(); })) as typeof fetch; }