OXYGENHUB

Coverage / src/hub.ts 95.1%

353 of 371 lines run, 24 of 59 functions, 70 of 98 branches · run #22 on main · run missed

10×
// The hub client: typed fetch over /api/v1 (hub spec §12.1) using the
20×
// generated types in hubapi.d.ts, plus URL helpers. No vscode imports,
30×
// so it is tested with plain Node against a real hub.
41×
5
import type * as api from "./hubapi";
61×
70×
export class HubError extends Error {
80×
  constructor(
90×
    readonly status: number,
100×
    readonly title: string,
110×
    readonly detail: string,
120×
  ) {
130×
    super(`${status} ${title}: ${detail}`);
140×
  }
153×
}
163×
173×
/** `https://hub/owner/name` → { base, owner, name }; undefined for anything else. */
183×
export function parseRepoUrl(url: string): { base: string; owner: string; name: string } | undefined {
193×
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.trim());
203×
  if (!m || m[2] === "api") {
210×
    return undefined;
220×
  }
233×
  return { base: m[1], owner: m[2], name: m[3] };
241×
}
251×
261×
import { readFileSync } from "node:fs";
271×
import * as http from "node:http";
281×
import * as https from "node:https";
291×
import * as tls from "node:tls";
301×
311×
export interface Session {
321×
  base: string;
331×
  token: string;
341×
  username?: string;
351×
}
361×
371×
export class HubClient {
381×
  constructor(
391×
    readonly base: string,
401×
    private readonly token: string | undefined,
411×
    private readonly fetchImpl: typeof fetch = fetch,
421×
  ) {}
431×
441×
  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
451×
    const headers: Record<string, string> = { accept: "application/json" };
461×
    if (this.token) {
471×
      headers.authorization = `Bearer ${this.token}`;
481×
    }
491×
    if (body !== undefined) {
501×
      headers["content-type"] = "application/json";
511×
    }
521×
    const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
531×
    if (res.status === 204) {
541×
      return undefined as T;
551×
    }
561×
    const text = await res.text();
571×
    if (!res.ok) {
581×
      try {
591×
        const p = JSON.parse(text) as api.Problem;
601×
        throw new HubError(p.status, p.title, p.detail);
611×
      } catch (e) {
621×
        if (e instanceof HubError) {
631×
          throw e;
641×
        }
651×
        throw new HubError(res.status, res.statusText, text);
661×
      }
671×
    }
681×
    return (text ? JSON.parse(text) : undefined) as T;
691×
  }
701×
711×
  me(): Promise<api.User> {
721×
    return this.request("GET", "/user");
731×
  }
741×
751×
  /** The caller's inbox: unread count and newest entries (needs user:read). */
761×
  notifications(limit = 50): Promise<api.Inbox> {
771×
    return this.request("GET", `/notifications?limit=${limit}`);
781×
  }
791×
801×
  markNotificationRead(id: number): Promise<void> {
811×
    return this.request("POST", `/notifications/${id}/read`);
821×
  }
831×
841×
  markAllNotificationsRead(): Promise<void> {
851×
    return this.request("POST", "/notifications/read");
861×
  }
871×
881×
  /** Recent OxygenFlow runs, newest first. */
891×
  flowRuns(owner: string, name: string, limit = 15): Promise<api.FlowRun[]> {
901×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs?limit=${limit}`);
911×
  }
921×
931×
  /** A run with its jobs. */
941×
  flowRun(owner: string, name: string, number: number): Promise<api.FlowRun> {
951×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}`);
961×
  }
971×
981×
  /** A job's log lines after `after` (a line's seq). */
991×
  flowLog(owner: string, name: string, number: number, job: string, after = 0): Promise<api.FlowLogLine[]> {
1001×
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/log?after=${after}&limit=2000`);
1011×
  }
1021×
1031×
  /** Run the pipeline of a bookmark's current state, or of one change. */
1041×
  startFlowRun(owner: string, name: string, target: { bookmark?: string; change?: string }): Promise<{ number: number; url: string }> {
1051×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs`, target);
1061×
  }
1071×
1081×
  rerunFlowRun(owner: string, name: string, number: number): Promise<{ number: number; url: string }> {
1091×
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/rerun`);
1101×
  }
1111×
1121×
  repositories(): Promise<api.Repository[]> {
1131×
    return this.request("GET", "/repos");
1141×
  }
1151×
1161×
  repository(owner: string, name: string): Promise<api.Repository> {
1171×
    return this.request("GET", `/repos/${owner}/${name}`);
1181×
  }
1191×
1201×
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
1211×
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
1221×
  }
1231×
1241×
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
1251×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
1261×
  }
1271×
1281×
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
1291×
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
1301×
  }
1311×
1321×
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
1331×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
1341×
  }
1351×
1361×
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
1371×
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
1381×
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
1391×
  }
1401×
1411×
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
1421×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
1431×
  }
1441×
1451×
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
1461×
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
1471×
  }
1481×
1491×
  /** The files a proposal changes, target state against projected state. */
1501×
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
1511×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
1521×
  }
1531×
1541×
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
1551×
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
1561×
    const headers: Record<string, string> = {};
1571×
    if (this.token) {
1581×
      headers.authorization = `Bearer ${this.token}`;
1591×
    }
1601×
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
1611×
    if (res.status === 404) {
1621×
      return undefined;
1631×
    }
1641×
    if (!res.ok) {
1651×
      throw new HubError(res.status, res.statusText, await res.text());
1661×
    }
1671×
    return res.text();
1681×
  }
1691×
1701×
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
1711×
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
1721×
  }
1731×
1741×
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
1751×
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
1761×
  }
1771×
1781×
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
1791×
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
1801×
  }
1811×
1821×
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
1831×
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
1841×
  }
1851×
1861×
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
1871×
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
1881×
  }
1891×
1901×
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
1911×
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
1921×
  }
1931×
1941×
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
1951×
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
1961×
  }
1971×
1981×
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
1991×
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
2001×
  }
2011×
2021×
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
2031×
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
2041×
  }
2051×
2061×
  /** What the repository takes from and diffuses to (oxygenhub#153). */
2071×
  diffusion(owner: string, name: string): Promise<api.Diffusion> {
2081×
    return this.request("GET", `/repos/${owner}/${name}/diffusion`);
2091×
  }
2101×
2111×
  releases(owner: string, name: string): Promise<api.Release[]> {
2121×
    return this.request("GET", `/repos/${owner}/${name}/releases`);
2131×
  }
2141×
2151×
  createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> {
2161×
    return this.request("POST", `/repos/${owner}/${name}/releases`, r);
2171×
  }
2181×
2191×
  tags(owner: string, name: string): Promise<api.Tag[]> {
2201×
    return this.request("GET", `/repos/${owner}/${name}/tags`);
2211×
  }
2221×
2231×
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
2241×
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
2251×
  }
2261×
}
2271×
2281×
/** Web URLs on the hub for things the remote provider is asked about. */
2291×
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
2301×
  const repo = `${base}/${owner}/${name}`;
2311×
  switch (target.kind) {
2321×
    case "repository":
2331×
      return repo;
2341×
    case "bookmark":
2351×
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
2361×
    case "change":
2371×
      return `${repo}/change/${target.hash}`;
2381×
    case "file": {
2390×
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
2400×
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
2410×
      // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks.
2420×
      return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${String(target.path)}${line}`;
2430×
    }
2441×
    case "proposals":
2451×
      return `${repo}/proposals`;
2461×
    case "issues":
2471×
      return `${repo}/issues`;
2481×
    case "proposal":
2491×
      return `${repo}/proposal/${target.number}`;
2501×
    case "issue":
2511×
      return `${repo}/issue/${target.number}`;
2521×
    case "diffusion":
2531×
      return `${repo}/diffusion`;
2541×
    default:
2551×
      return repo;
2561×
  }
2571×
}
2583×
2593×
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
2603×
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
2615×
  if (!username || p.author === username) {
2621×
    return false;
2631×
  }
2645×
  if (p.state !== "open") {
2651×
    return false;
2661×
  }
2673×
  const mine = p.approvals.find((a) => a.account === username);
2685×
  return !mine || !mine.sealed;
2691×
}
2701×
2711×
/** Which proposal, side and file a diff document shows. */
2721×
export interface DiffRef {
2731×
  base: string;
2741×
  owner: string;
2751×
  name: string;
2761×
  number: number;
2771×
  side: "base" | "head";
2781×
  path: string;
2791×
}
2801×
2811×
/** The query string of a diff document's URI. */
2821×
export function encodeDiffQuery(r: DiffRef): string {
2831×
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
2844×
}
2854×
2864×
/** Parse a diff document's query and path back; undefined if it is not one. */
2874×
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
2884×
  const q = new URLSearchParams(query);
2894×
  const number = Number(q.get("number"));
2904×
  const side = q.get("side");
2914×
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
2924×
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
2933×
    return undefined;
2943×
  }
2954×
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
2964×
}
2973×
2983×
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
2993×
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
3003×
3013×
export function hubTarget(url: string): HubTarget {
3024×
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
3034×
  if (!m) {
3042×
    return { kind: "other", url };
3052×
  }
3064×
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
3074×
}
3083×
3093×
/**
3103×
 * Release notes from history: the changes in `current` that `previous`
3113×
 * does not have, newest first, one line each (the message's subject).
3123×
 */
3133×
export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string {
3143×
  const seen = new Set(previous.map((c) => c.hash));
3153×
  const lines = current
3163×
    .filter((c) => !seen.has(c.hash))
3173×
    .sort((a, b) => b.when_ms - a.when_ms)
3183×
    .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`);
3193×
  const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:";
3203×
  return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n";
32110×
}
32210×
32310×
/** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */
32410×
export function looksPrerelease(tag: string): boolean {
32510×
  return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag);
32610×
}
3273×
3283×
/**
3293×
 * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a
3303×
 * self-signed certificate (Node's `fetch` takes no CA). The file is read on
3313×
 * each request, so a renewed certificate needs no reload.
3323×
 */
3333×
export function fetchTrusting(caFile: string): typeof fetch {
3342×
  return ((input: string | URL | Request, init?: RequestInit) =>
3354×
    new Promise<Response>((resolve, reject) => {
3364×
      const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
3374×
      const secure = url.protocol === "https:";
3384×
      let ca: string[] | undefined;
3394×
      if (secure) {
3404×
        try {
3414×
          ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")];
3424×
        } catch (e) {
3431×
          reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`));
3441×
          return;
3451×
        }
3464×
      }
3473×
      const headers: Record<string, string> = {};
3484×
      new Headers(init?.headers).forEach((v, k) => (headers[k] = v));
3494×
      const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => {
3503×
        const chunks: Buffer[] = [];
3513×
        res.on("data", (c: Buffer) => chunks.push(c));
3523×
        res.on("error", reject);
3533×
        res.on("end", () => {
3543×
          const status = res.statusCode ?? 0;
3553×
          const out = new Headers();
3563×
          for (const [k, v] of Object.entries(res.headers)) {
35713×
            if (v !== undefined) {
35813×
              out.set(k, Array.isArray(v) ? v.join(", ") : String(v));
35913×
            }
36013×
          }
3613×
          const empty = status === 204 || status === 304;
3623×
          resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out }));
3633×
        });
3644×
      });
3654×
      req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e })));
3664×
      if (init?.body !== undefined && init.body !== null) {
3671×
        req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer));
3681×
      }
3694×
      req.end();
3702×
    })) as typeof fetch;
3712×
}