OXYGENHUB
# 5888949525ec oxygenhub-vscode / src / hub.ts
13.5 KiB · last changed Reach self-signed hubs with the remote's CA (0.7.0) 1 month ago source blame history raw
1
// The hub client: typed fetch over /api/v1 (hub spec §12.1) using the
2
// generated types in hubapi.d.ts, plus URL helpers. No vscode imports,
3
// so it is tested with plain Node against a real hub.
4
5
import type * as api from "./hubapi";
6
7
export class HubError extends Error {
8
  constructor(
9
    readonly status: number,
10
    readonly title: string,
11
    readonly detail: string,
12
  ) {
13
    super(`${status} ${title}: ${detail}`);
14
  }
15
}
16
17
/** `https://hub/owner/name` → { base, owner, name }; undefined for anything else. */
18
export function parseRepoUrl(url: string): { base: string; owner: string; name: string } | undefined {
19
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.trim());
20
  if (!m || m[2] === "api") {
21
    return undefined;
22
  }
23
  return { base: m[1], owner: m[2], name: m[3] };
24
}
25
26
import { readFileSync } from "node:fs";
27
import * as http from "node:http";
28
import * as https from "node:https";
29
import * as tls from "node:tls";
30
31
export interface Session {
32
  base: string;
33
  token: string;
34
  username?: string;
35
}
36
37
export class HubClient {
38
  constructor(
39
    readonly base: string,
40
    private readonly token: string | undefined,
41
    private readonly fetchImpl: typeof fetch = fetch,
42
  ) {}
43
44
  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
45
    const headers: Record<string, string> = { accept: "application/json" };
46
    if (this.token) {
47
      headers.authorization = `Bearer ${this.token}`;
48
    }
49
    if (body !== undefined) {
50
      headers["content-type"] = "application/json";
51
    }
52
    const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
53
    if (res.status === 204) {
54
      return undefined as T;
55
    }
56
    const text = await res.text();
57
    if (!res.ok) {
58
      try {
59
        const p = JSON.parse(text) as api.Problem;
60
        throw new HubError(p.status, p.title, p.detail);
61
      } catch (e) {
62
        if (e instanceof HubError) {
63
          throw e;
64
        }
65
        throw new HubError(res.status, res.statusText, text);
66
      }
67
    }
68
    return (text ? JSON.parse(text) : undefined) as T;
69
  }
70
71
  me(): Promise<api.User> {
72
    return this.request("GET", "/user");
73
  }
74
75
  /** The caller's inbox: unread count and newest entries (needs user:read). */
76
  notifications(limit = 50): Promise<api.Inbox> {
77
    return this.request("GET", `/notifications?limit=${limit}`);
78
  }
79
80
  markNotificationRead(id: number): Promise<void> {
81
    return this.request("POST", `/notifications/${id}/read`);
82
  }
83
84
  markAllNotificationsRead(): Promise<void> {
85
    return this.request("POST", "/notifications/read");
86
  }
87
88
  repositories(): Promise<api.Repository[]> {
89
    return this.request("GET", "/repos");
90
  }
91
92
  repository(owner: string, name: string): Promise<api.Repository> {
93
    return this.request("GET", `/repos/${owner}/${name}`);
94
  }
95
96
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
97
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
98
  }
99
100
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
101
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
102
  }
103
104
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
105
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
106
  }
107
108
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
109
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
110
  }
111
112
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
113
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
114
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
115
  }
116
117
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
118
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
119
  }
120
121
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
122
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
123
  }
124
125
  /** The files a proposal changes, target state against projected state. */
126
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
127
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
128
  }
129
130
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
131
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
132
    const headers: Record<string, string> = {};
133
    if (this.token) {
134
      headers.authorization = `Bearer ${this.token}`;
135
    }
136
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
137
    if (res.status === 404) {
138
      return undefined;
139
    }
140
    if (!res.ok) {
141
      throw new HubError(res.status, res.statusText, await res.text());
142
    }
143
    return res.text();
144
  }
145
146
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
147
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
148
  }
149
150
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
151
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
152
  }
153
154
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
155
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
156
  }
157
158
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
159
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
160
  }
161
162
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
163
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
164
  }
165
166
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
167
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
168
  }
169
170
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
171
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
172
  }
173
174
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
175
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
176
  }
177
178
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
179
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
180
  }
181
182
  releases(owner: string, name: string): Promise<api.Release[]> {
183
    return this.request("GET", `/repos/${owner}/${name}/releases`);
184
  }
185
186
  createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> {
187
    return this.request("POST", `/repos/${owner}/${name}/releases`, r);
188
  }
189
190
  tags(owner: string, name: string): Promise<api.Tag[]> {
191
    return this.request("GET", `/repos/${owner}/${name}/tags`);
192
  }
193
194
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
195
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
196
  }
197
}
198
199
/** Web URLs on the hub for things the remote provider is asked about. */
200
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
201
  const repo = `${base}/${owner}/${name}`;
202
  switch (target.kind) {
203
    case "repository":
204
      return repo;
205
    case "bookmark":
206
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
207
    case "change":
208
      return `${repo}/change/${target.hash}`;
209
    case "file": {
210
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
211
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
212
      // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks.
213
      return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${String(target.path)}${line}`;
214
    }
215
    case "proposals":
216
      return `${repo}/proposals`;
217
    case "issues":
218
      return `${repo}/issues`;
219
    case "proposal":
220
      return `${repo}/proposal/${target.number}`;
221
    case "issue":
222
      return `${repo}/issue/${target.number}`;
223
    default:
224
      return repo;
225
  }
226
}
227
228
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
229
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
230
  if (!username || p.author === username) {
231
    return false;
232
  }
233
  if (p.state !== "open") {
234
    return false;
235
  }
236
  const mine = p.approvals.find((a) => a.account === username);
237
  return !mine || !mine.sealed;
238
}
239
240
/** Which proposal, side and file a diff document shows. */
241
export interface DiffRef {
242
  base: string;
243
  owner: string;
244
  name: string;
245
  number: number;
246
  side: "base" | "head";
247
  path: string;
248
}
249
250
/** The query string of a diff document's URI. */
251
export function encodeDiffQuery(r: DiffRef): string {
252
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
253
}
254
255
/** Parse a diff document's query and path back; undefined if it is not one. */
256
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
257
  const q = new URLSearchParams(query);
258
  const number = Number(q.get("number"));
259
  const side = q.get("side");
260
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
261
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
262
    return undefined;
263
  }
264
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
265
}
266
267
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
268
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
269
270
export function hubTarget(url: string): HubTarget {
271
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
272
  if (!m) {
273
    return { kind: "other", url };
274
  }
275
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
276
}
277
278
/**
279
 * Release notes from history: the changes in `current` that `previous`
280
 * does not have, newest first, one line each (the message's subject).
281
 */
282
export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string {
283
  const seen = new Set(previous.map((c) => c.hash));
284
  const lines = current
285
    .filter((c) => !seen.has(c.hash))
286
    .sort((a, b) => b.when_ms - a.when_ms)
287
    .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`);
288
  const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:";
289
  return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n";
290
}
291
292
/** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */
293
export function looksPrerelease(tag: string): boolean {
294
  return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag);
295
}
296
297
/**
298
 * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a
299
 * self-signed certificate (Node's `fetch` takes no CA). The file is read on
300
 * each request, so a renewed certificate needs no reload.
301
 */
302
export function fetchTrusting(caFile: string): typeof fetch {
303
  return ((input: string | URL | Request, init?: RequestInit) =>
304
    new Promise<Response>((resolve, reject) => {
305
      const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
306
      const secure = url.protocol === "https:";
307
      let ca: string[] | undefined;
308
      if (secure) {
309
        try {
310
          ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")];
311
        } catch (e) {
312
          reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`));
313
          return;
314
        }
315
      }
316
      const headers: Record<string, string> = {};
317
      new Headers(init?.headers).forEach((v, k) => (headers[k] = v));
318
      const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => {
319
        const chunks: Buffer[] = [];
320
        res.on("data", (c: Buffer) => chunks.push(c));
321
        res.on("error", reject);
322
        res.on("end", () => {
323
          const status = res.statusCode ?? 0;
324
          const out = new Headers();
325
          for (const [k, v] of Object.entries(res.headers)) {
326
            if (v !== undefined) {
327
              out.set(k, Array.isArray(v) ? v.join(", ") : String(v));
328
            }
329
          }
330
          const empty = status === 204 || status === 304;
331
          resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out }));
332
        });
333
      });
334
      req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e })));
335
      if (init?.body !== undefined && init.body !== null) {
336
        req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer));
337
      }
338
      req.end();
339
    })) as typeof fetch;
340
}