OXYGENHUB
# bf73998c5198 oxygenhub-vscode / src / hub.ts
8.8 KiB · last changed Proposals in native diff editors (0.2.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
export interface Session {
27
  base: string;
28
  token: string;
29
  username?: string;
30
}
31
32
export class HubClient {
33
  constructor(
34
    readonly base: string,
35
    private readonly token: string | undefined,
36
    private readonly fetchImpl: typeof fetch = fetch,
37
  ) {}
38
39
  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
40
    const headers: Record<string, string> = { accept: "application/json" };
41
    if (this.token) {
42
      headers.authorization = `Bearer ${this.token}`;
43
    }
44
    if (body !== undefined) {
45
      headers["content-type"] = "application/json";
46
    }
47
    const res = await this.fetchImpl(`${this.base}/api/v1${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
48
    if (res.status === 204) {
49
      return undefined as T;
50
    }
51
    const text = await res.text();
52
    if (!res.ok) {
53
      try {
54
        const p = JSON.parse(text) as api.Problem;
55
        throw new HubError(p.status, p.title, p.detail);
56
      } catch (e) {
57
        if (e instanceof HubError) {
58
          throw e;
59
        }
60
        throw new HubError(res.status, res.statusText, text);
61
      }
62
    }
63
    return (text ? JSON.parse(text) : undefined) as T;
64
  }
65
66
  me(): Promise<api.User> {
67
    return this.request("GET", "/user");
68
  }
69
70
  repositories(): Promise<api.Repository[]> {
71
    return this.request("GET", "/repos");
72
  }
73
74
  repository(owner: string, name: string): Promise<api.Repository> {
75
    return this.request("GET", `/repos/${owner}/${name}`);
76
  }
77
78
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
79
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
80
  }
81
82
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
83
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
84
  }
85
86
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
87
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
88
  }
89
90
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
91
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
92
  }
93
94
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
95
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
96
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
97
  }
98
99
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
100
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
101
  }
102
103
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
104
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
105
  }
106
107
  /** The files a proposal changes, target state against projected state. */
108
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
109
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
110
  }
111
112
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
113
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
114
    const headers: Record<string, string> = {};
115
    if (this.token) {
116
      headers.authorization = `Bearer ${this.token}`;
117
    }
118
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
119
    if (res.status === 404) {
120
      return undefined;
121
    }
122
    if (!res.ok) {
123
      throw new HubError(res.status, res.statusText, await res.text());
124
    }
125
    return res.text();
126
  }
127
128
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
129
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
130
  }
131
132
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
133
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
134
  }
135
136
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
137
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
138
  }
139
140
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
141
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
142
  }
143
144
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
145
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
146
  }
147
148
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
149
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
150
  }
151
152
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
153
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
154
  }
155
156
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
157
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
158
  }
159
160
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
161
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
162
  }
163
164
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
165
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
166
  }
167
}
168
169
/** Web URLs on the hub for things the remote provider is asked about. */
170
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
171
  const repo = `${base}/${owner}/${name}`;
172
  switch (target.kind) {
173
    case "repository":
174
      return repo;
175
    case "bookmark":
176
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
177
    case "change":
178
      return `${repo}/change/${target.hash}`;
179
    case "file": {
180
      const line = typeof target.line === "number" ? `#L${target.line}` : "";
181
      return `${repo}/file/${encodeURIComponent(String(target.reference))}/${String(target.path)}${line}`;
182
    }
183
    case "proposals":
184
      return `${repo}/proposals`;
185
    case "issues":
186
      return `${repo}/issues`;
187
    case "proposal":
188
      return `${repo}/proposal/${target.number}`;
189
    case "issue":
190
      return `${repo}/issue/${target.number}`;
191
    default:
192
      return repo;
193
  }
194
}
195
196
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
197
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
198
  if (!username || p.author === username) {
199
    return false;
200
  }
201
  if (p.state !== "open") {
202
    return false;
203
  }
204
  const mine = p.approvals.find((a) => a.account === username);
205
  return !mine || !mine.sealed;
206
}
207
208
/** Which proposal, side and file a diff document shows. */
209
export interface DiffRef {
210
  base: string;
211
  owner: string;
212
  name: string;
213
  number: number;
214
  side: "base" | "head";
215
  path: string;
216
}
217
218
/** The query string of a diff document's URI. */
219
export function encodeDiffQuery(r: DiffRef): string {
220
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
221
}
222
223
/** Parse a diff document's query and path back; undefined if it is not one. */
224
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
225
  const q = new URLSearchParams(query);
226
  const number = Number(q.get("number"));
227
  const side = q.get("side");
228
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
229
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
230
    return undefined;
231
  }
232
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
233
}