OXYGENHUB
# 486c15b00314 oxygenhub-vscode / src / hub.ts
6.8 KiB · last changed 0.1.1: review comments anchored to atoms through the API; regenerated types 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
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
108
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
109
  }
110
111
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
112
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
113
  }
114
115
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
116
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
117
  }
118
119
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
120
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
121
  }
122
123
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
124
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
125
  }
126
127
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
128
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
129
  }
130
131
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
132
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
133
  }
134
135
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
136
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
137
  }
138
139
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
140
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
141
  }
142
143
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
144
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
145
  }
146
}
147
148
/** Web URLs on the hub for things the remote provider is asked about. */
149
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
150
  const repo = `${base}/${owner}/${name}`;
151
  switch (target.kind) {
152
    case "repository":
153
      return repo;
154
    case "bookmark":
155
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
156
    case "change":
157
      return `${repo}/change/${target.hash}`;
158
    case "file": {
159
      const line = typeof target.line === "number" ? `#L${target.line}` : "";
160
      return `${repo}/file/${encodeURIComponent(String(target.reference))}/${String(target.path)}${line}`;
161
    }
162
    case "proposals":
163
      return `${repo}/proposals`;
164
    case "issues":
165
      return `${repo}/issues`;
166
    case "proposal":
167
      return `${repo}/proposal/${target.number}`;
168
    case "issue":
169
      return `${repo}/issue/${target.number}`;
170
    default:
171
      return repo;
172
  }
173
}
174
175
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
176
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
177
  if (!username || p.author === username) {
178
    return false;
179
  }
180
  if (p.state !== "open") {
181
    return false;
182
  }
183
  const mine = p.approvals.find((a) => a.account === username);
184
  return !mine || !mine.sealed;
185
}