OXYGENHUB
◆ main oxygenhub-vscode / src / hub.ts
22.4 KiB · last changed OxygenHub 0.13.0: Drops in the editor with Share as a Drop (closes #7); Flow approvals, expedite, reports, timings and test results (closes #8); ready/draft, landable, trust reports, asset downloads and new repositories (closes #9) 6 days 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
  /** Recent OxygenFlow runs, newest first. */
89
  flowRuns(owner: string, name: string, limit = 15): Promise<api.FlowRun[]> {
90
    return this.request("GET", `/repos/${owner}/${name}/flow/runs?limit=${limit}`);
91
  }
92
93
  /** A run with its jobs. */
94
  flowRun(owner: string, name: string, number: number): Promise<api.FlowRun> {
95
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}`);
96
  }
97
98
  /** A job's log lines after `after` (a line's seq). */
99
  flowLog(owner: string, name: string, number: number, job: string, after = 0): Promise<api.FlowLogLine[]> {
100
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/log?after=${after}&limit=2000`);
101
  }
102
103
  /** Run the pipeline of a bookmark's current state, or of one change. */
104
  startFlowRun(owner: string, name: string, target: { bookmark?: string; change?: string }): Promise<{ number: number; url: string }> {
105
    return this.request("POST", `/repos/${owner}/${name}/flow/runs`, target);
106
  }
107
108
  rerunFlowRun(owner: string, name: string, number: number): Promise<{ number: number; url: string }> {
109
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/rerun`);
110
  }
111
112
  repositories(): Promise<api.Repository[]> {
113
    return this.request("GET", "/repos");
114
  }
115
116
  repository(owner: string, name: string): Promise<api.Repository> {
117
    return this.request("GET", `/repos/${owner}/${name}`);
118
  }
119
120
  proposals(owner: string, name: string): Promise<api.Proposal[]> {
121
    return this.request("GET", `/repos/${owner}/${name}/proposals`);
122
  }
123
124
  proposal(owner: string, name: string, number: number): Promise<api.Proposal> {
125
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}`);
126
  }
127
128
  createProposal(owner: string, name: string, p: api.NewProposal): Promise<api.Proposal> {
129
    return this.request("POST", `/repos/${owner}/${name}/proposals`, p);
130
  }
131
132
  proposalComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
133
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/comments`);
134
  }
135
136
  /** A comment; with `path` and `line` it is anchored to that line's atom in the projected state. */
137
  commentProposal(owner: string, name: string, number: number, body: string, path?: string, line?: number): Promise<api.Comment> {
138
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/comments`, { body, path: path ?? null, line: line ?? null });
139
  }
140
141
  reviews(owner: string, name: string, number: number): Promise<api.Review[]> {
142
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/reviews`);
143
  }
144
145
  review(owner: string, name: string, number: number, verdict: "comment" | "changes" | "approve", body = ""): Promise<api.Review> {
146
    return this.request("POST", `/repos/${owner}/${name}/proposals/${number}/reviews`, { verdict, body });
147
  }
148
149
  /** The files a proposal changes, target state against projected state. */
150
  proposalFiles(owner: string, name: string, number: number): Promise<api.ProposalFile[]> {
151
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/files`);
152
  }
153
154
  /** A file's text on one side of a proposal; undefined when it does not exist there. */
155
  async proposalContent(owner: string, name: string, number: number, side: "base" | "head", path: string): Promise<string | undefined> {
156
    const headers: Record<string, string> = {};
157
    if (this.token) {
158
      headers.authorization = `Bearer ${this.token}`;
159
    }
160
    const res = await this.fetchImpl(`${this.base}/api/v1/repos/${owner}/${name}/proposals/${number}/content/${side}/${path.split("/").map(encodeURIComponent).join("/")}`, { headers });
161
    if (res.status === 404) {
162
      return undefined;
163
    }
164
    if (!res.ok) {
165
      throw new HubError(res.status, res.statusText, await res.text());
166
    }
167
    return res.text();
168
  }
169
170
  proposalChecks(owner: string, name: string, number: number): Promise<api.Check[]> {
171
    return this.request("GET", `/repos/${owner}/${name}/proposals/${number}/checks`);
172
  }
173
174
  issues(owner: string, name: string, state: "open" | "closed" | "all" = "open"): Promise<api.Issue[]> {
175
    return this.request("GET", `/repos/${owner}/${name}/issues?state=${state}`);
176
  }
177
178
  issue(owner: string, name: string, number: number): Promise<api.Issue> {
179
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}`);
180
  }
181
182
  createIssue(owner: string, name: string, title: string, body = ""): Promise<api.Issue> {
183
    return this.request("POST", `/repos/${owner}/${name}/issues`, { title, body });
184
  }
185
186
  issueComments(owner: string, name: string, number: number): Promise<api.Comment[]> {
187
    return this.request("GET", `/repos/${owner}/${name}/issues/${number}/comments`);
188
  }
189
190
  commentIssue(owner: string, name: string, number: number, body: string): Promise<api.Comment> {
191
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}/comments`, { body });
192
  }
193
194
  setIssueState(owner: string, name: string, number: number, state: "open" | "closed", reason = ""): Promise<api.Issue> {
195
    return this.request("POST", `/repos/${owner}/${name}/issues/${number}`, { state, reason });
196
  }
197
198
  history(owner: string, name: string, reference: string, limit = 50): Promise<api.History> {
199
    return this.request("GET", `/repos/${owner}/${name}/history/${encodeURIComponent(reference)}?limit=${limit}`);
200
  }
201
202
  bookmarks(owner: string, name: string): Promise<api.Bookmark[]> {
203
    return this.request("GET", `/repos/${owner}/${name}/bookmarks`);
204
  }
205
206
  /** What the repository takes from and diffuses to (oxygenhub#153). */
207
  diffusion(owner: string, name: string): Promise<api.Diffusion> {
208
    return this.request("GET", `/repos/${owner}/${name}/diffusion`);
209
  }
210
211
  releases(owner: string, name: string): Promise<api.Release[]> {
212
    return this.request("GET", `/repos/${owner}/${name}/releases`);
213
  }
214
215
  createRelease(owner: string, name: string, r: api.NewRelease): Promise<api.Release> {
216
    return this.request("POST", `/repos/${owner}/${name}/releases`, r);
217
  }
218
219
  tags(owner: string, name: string): Promise<api.Tag[]> {
220
    return this.request("GET", `/repos/${owner}/${name}/tags`);
221
  }
222
223
  search(q: string): Promise<{ kind: string; repository: string; number: number; title: string }[]> {
224
    return this.request("GET", `/search?q=${encodeURIComponent(q)}`);
225
  }
226
227
  /** The caller's drops, newest first (oxygenhub#280). */
228
  drops(): Promise<api.Drop[]> {
229
    return this.request("GET", "/drops");
230
  }
231
232
  /** Someone's public drops. */
233
  userDrops(user: string): Promise<api.Drop[]> {
234
    return this.request("GET", `/users/${encodeURIComponent(user)}/drops`);
235
  }
236
237
  /** A drop with each text file's content. */
238
  drop(id: string): Promise<api.Drop> {
239
    return this.request("GET", `/drops/${id}`);
240
  }
241
242
  createDrop(d: api.NewDrop): Promise<api.Drop> {
243
    return this.request("POST", "/drops", d);
244
  }
245
246
  /** Change a drop: its title, description, visibility, or files (content null removes one). */
247
  editDrop(id: string, e: api.DropEdit): Promise<api.Drop> {
248
    return this.request("PATCH", `/drops/${id}`, e);
249
  }
250
251
  deleteDrop(id: string): Promise<void> {
252
    return this.request("DELETE", `/drops/${id}`);
253
  }
254
255
  /** A copy of a drop, history and all, as the caller's (oxygenhub#349). */
256
  forkDrop(id: string): Promise<api.Drop> {
257
    return this.request("POST", `/drops/${id}/fork`);
258
  }
259
260
  starDrop(id: string, on: boolean): Promise<api.DropStars> {
261
    return this.request(on ? "PUT" : "DELETE", `/drops/${id}/star`);
262
  }
263
264
  dropComments(id: string): Promise<api.DropComment[]> {
265
    return this.request("GET", `/drops/${id}/comments`);
266
  }
267
268
  commentDrop(id: string, body: string): Promise<api.DropComment> {
269
    return this.request("POST", `/drops/${id}/comments`, { body });
270
  }
271
272
  deleteDropComment(id: string, n: number): Promise<void> {
273
    return this.request("DELETE", `/drops/${id}/comments/${n}`);
274
  }
275
276
  /** Approve or reject a job waiting on its approval rules (oxygenflow#57). */
277
  decideFlowJob(owner: string, name: string, number: number, job: string, approve: boolean): Promise<unknown> {
278
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/${approve ? "approve" : "reject"}`);
279
  }
280
281
  /** Make a queued or running run urgent, with why (oxygenhub#244). */
282
  expediteFlowRun(owner: string, name: string, number: number, reason: string): Promise<unknown> {
283
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/expedite`, { reason });
284
  }
285
286
  cancelFlowRun(owner: string, name: string, number: number): Promise<unknown> {
287
    return this.request("POST", `/repos/${owner}/${name}/flow/runs/${number}/cancel`);
288
  }
289
290
  /** The reports a job published (oxygenhub#348). */
291
  jobReports(owner: string, name: string, number: number, job: string): Promise<api.Report[]> {
292
    return this.request("GET", `/repos/${owner}/${name}/flow/runs/${number}/jobs/${encodeURIComponent(job)}/reports`);
293
  }
294
295
  /** Test reports on a bookmark, newest first. */
296
  testReports(owner: string, name: string, bookmark?: string, limit = 1): Promise<api.TestReport[]> {
297
    const q = new URLSearchParams({ limit: String(limit), ...(bookmark ? { bookmark } : {}) });
298
    return this.request("GET", `/repos/${owner}/${name}/tests?${q}`);
299
  }
300
301
  testReport(owner: string, name: string, id: number): Promise<api.TestReportDetail> {
302
    return this.request("GET", `/repos/${owner}/${name}/tests/${id}`);
303
  }
304
305
  /** Make a draft ready for review, or turn an open proposal back into a draft (#313). */
306
  setProposalDraft(owner: string, name: string, number: number, draft: boolean): Promise<api.Proposal> {
307
    return this.request("PATCH", `/repos/${owner}/${name}/proposals/${number}`, { draft });
308
  }
309
310
  /** The dashboard's proposals; with `landable`, also what the caller can land now (#311). */
311
  userProposals(landable = false): Promise<api.UserProposals> {
312
    return this.request("GET", `/user/proposals${landable ? "?landable=true" : ""}`);
313
  }
314
315
  /** What a release's trust page shows: signatures, builds and the audit (#79). */
316
  releaseTrust(owner: string, name: string, tag: string): Promise<ReleaseTrust> {
317
    return this.request("GET", `/repos/${owner}/${name}/releases/trust/${encodeURIComponent(tag)}`);
318
  }
319
320
  orgs(): Promise<api.Organisation[]> {
321
    return this.request("GET", "/user/orgs");
322
  }
323
324
  createRepository(r: api.NewRepository): Promise<api.Repository> {
325
    return this.request("POST", "/repos", r);
326
  }
327
328
  /** The assistants a new repository under `owner` may ask for its starting files (#347). */
329
  starterAssistants(owner: string): Promise<api.StarterAssistants> {
330
    return this.request("GET", `/user/starter?owner=${encodeURIComponent(owner)}`);
331
  }
332
333
  startStarter(owner: string, name: string, r: api.StarterRequest): Promise<api.StarterStatus> {
334
    return this.request("POST", `/repos/${owner}/${name}/starter`, r);
335
  }
336
337
  starterStatus(owner: string, name: string): Promise<api.StarterStatus> {
338
    return this.request("GET", `/repos/${owner}/${name}/starter`);
339
  }
340
341
  /** A file's bytes from the hub (a release asset), with the session's token. */
342
  async download(url: string): Promise<Uint8Array> {
343
    const headers: Record<string, string> = {};
344
    if (this.token && url.startsWith(this.base + "/")) {
345
      headers.authorization = `Bearer ${this.token}`;
346
    }
347
    const res = await this.fetchImpl(url, { headers });
348
    if (!res.ok) {
349
      throw new HubError(res.status, res.statusText, await res.text());
350
    }
351
    return new Uint8Array(await res.arrayBuffer());
352
  }
353
}
354
355
/** A release's trust report (the web's, not in the generated types). */
356
export interface ReleaseTrust {
357
  repository: string;
358
  tag: string;
359
  title: string;
360
  release_url: string;
361
  heads: string[];
362
  tag_signer?: { key: string; name: string; email: string; account?: string | null } | null;
363
  /** `valid`, `unsigned`, `invalid: …` or `revoked`. */
364
  tag_signature: string;
365
  since?: string | null;
366
  changes: number;
367
  authors: { who: { name: string; email: string; account?: string | null }; changes: number; signed: number; sealed: number; unsigned: number; revoked: number; invalid: number }[];
368
  assets: { name: string; size: number; blake3: string; url: string; build?: { run: number; job: string; run_url: string; same_state_as_tag: boolean } | null }[];
369
  audit: { verdict: "pass" | "warn" | "fail"; title: string; detail: string }[];
370
  generated_ms: number;
371
}
372
373
/** A release's trust report as Markdown, for a preview beside the code. */
374
export function trustMarkdown(t: ReleaseTrust): string {
375
  const glyph = { pass: "✔", warn: "!", fail: "✘" } as const;
376
  const out = [`# Trust: ${t.title || t.tag}`, "", `${t.repository} · tag \`${t.tag}\` · ${t.heads.map((h) => h.slice(0, 12)).join("+")}`, ""];
377
  const signer = t.tag_signer ? `${t.tag_signer.name} <${t.tag_signer.email}>` : "";
378
  out.push(`- Tag signature: **${t.tag_signature}**${signer ? ` by ${signer}` : ""}`);
379
  out.push(`- ${t.changes} change${t.changes === 1 ? "" : "s"}${t.since ? ` since ${t.since}` : ""}`, "");
380
  out.push("## Audit", "");
381
  for (const c of t.audit) {
382
    out.push(`- ${glyph[c.verdict]} **${c.title}**${c.detail ? ` — ${c.detail}` : ""}`);
383
  }
384
  if (t.authors.length) {
385
    out.push("", "## Authors", "", "| Author | Changes | Signed | Sealed | Unsigned | Revoked | Invalid |", "|---|---:|---:|---:|---:|---:|---:|");
386
    for (const a of t.authors) {
387
      out.push(`| ${a.who.account ?? a.who.name} | ${a.changes} | ${a.signed} | ${a.sealed} | ${a.unsigned} | ${a.revoked} | ${a.invalid} |`);
388
    }
389
  }
390
  if (t.assets.length) {
391
    out.push("", "## Assets", "");
392
    for (const a of t.assets) {
393
      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";
394
      out.push(`- \`${a.name}\` · BLAKE3 \`${a.blake3.slice(0, 16)}…\` · ${build}`);
395
    }
396
  }
397
  out.push("", `[The release](${t.release_url})`, "");
398
  return out.join("\n");
399
}
400
401
/** Web URLs on the hub for things the remote provider is asked about. */
402
export function hubUrl(base: string, owner: string, name: string, target: { kind: string; [k: string]: unknown }): string {
403
  const repo = `${base}/${owner}/${name}`;
404
  switch (target.kind) {
405
    case "repository":
406
      return repo;
407
    case "bookmark":
408
      return `${repo}/tree/${encodeURIComponent(String(target.name))}`;
409
    case "change":
410
      return `${repo}/change/${target.hash}`;
411
    case "file": {
412
      const end = typeof target.endLine === "number" && target.endLine !== target.line ? `-L${target.endLine}` : "";
413
      const line = typeof target.line === "number" ? `#L${target.line}${end}` : "";
414
      // A state address (`hash+hash`) keeps its `+`, as the hub writes permalinks.
415
      return `${repo}/file/${encodeURIComponent(String(target.reference)).replace(/%2B/g, "+")}/${String(target.path)}${line}`;
416
    }
417
    case "proposals":
418
      return `${repo}/proposals`;
419
    case "issues":
420
      return `${repo}/issues`;
421
    case "proposal":
422
      return `${repo}/proposal/${target.number}`;
423
    case "issue":
424
      return `${repo}/issue/${target.number}`;
425
    case "diffusion":
426
      return `${repo}/diffusion`;
427
    default:
428
      return repo;
429
  }
430
}
431
432
/** Which of the proposals need the signed-in user: not theirs, and not yet sealed by them. */
433
export function needsMe(p: import("./hubapi").Proposal, username: string | undefined): boolean {
434
  if (!username || p.author === username) {
435
    return false;
436
  }
437
  if (p.state !== "open") {
438
    return false;
439
  }
440
  const mine = p.approvals.find((a) => a.account === username);
441
  return !mine || !mine.sealed;
442
}
443
444
/** Which proposal, side and file a diff document shows. */
445
export interface DiffRef {
446
  base: string;
447
  owner: string;
448
  name: string;
449
  number: number;
450
  side: "base" | "head";
451
  path: string;
452
}
453
454
/** The query string of a diff document's URI. */
455
export function encodeDiffQuery(r: DiffRef): string {
456
  return new URLSearchParams({ hub: r.base, owner: r.owner, name: r.name, number: String(r.number), side: r.side }).toString();
457
}
458
459
/** Parse a diff document's query and path back; undefined if it is not one. */
460
export function decodeDiffQuery(query: string, path: string): DiffRef | undefined {
461
  const q = new URLSearchParams(query);
462
  const number = Number(q.get("number"));
463
  const side = q.get("side");
464
  const [base, owner, name] = [q.get("hub"), q.get("owner"), q.get("name")];
465
  if (!base || !owner || !name || !Number.isInteger(number) || number < 1 || (side !== "base" && side !== "head")) {
466
    return undefined;
467
  }
468
  return { base, owner, name, number, side, path: path.replace(/^\/+/, "") };
469
}
470
471
/** What a hub page URL points at, for opening it in the editor instead of a browser. */
472
export type HubTarget = { kind: "proposal" | "issue"; base: string; owner: string; name: string; number: number } | { kind: "other"; url: string };
473
474
export function hubTarget(url: string): HubTarget {
475
  const m = /^(https?:\/\/[^/]+)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(proposal|issue)\/(\d+)(?:[/?#].*)?$/.exec(url);
476
  if (!m) {
477
    return { kind: "other", url };
478
  }
479
  return { kind: m[4] as "proposal" | "issue", base: m[1], owner: m[2], name: m[3], number: Number(m[5]) };
480
}
481
482
/**
483
 * Release notes from history: the changes in `current` that `previous`
484
 * does not have, newest first, one line each (the message's subject).
485
 */
486
export function releaseNotes(current: api.ChangeSummary[], previous: api.ChangeSummary[], sinceTag?: string): string {
487
  const seen = new Set(previous.map((c) => c.hash));
488
  const lines = current
489
    .filter((c) => !seen.has(c.hash))
490
    .sort((a, b) => b.when_ms - a.when_ms)
491
    .map((c) => `- ${c.message.split("\n")[0].trim()} (${c.hash.slice(0, 12)})`);
492
  const head = sinceTag ? `Changes since ${sinceTag}:` : "Changes:";
493
  return lines.length ? `${head}\n\n${lines.join("\n")}\n` : "No changes since the last release.\n";
494
}
495
496
/** Whether a tag name reads as a pre-release (`v1.0-rc1`, `2.0.0-beta.2`, `alpha`). */
497
export function looksPrerelease(tag: string): boolean {
498
  return /(^|[-.+_])(alpha|beta|rc|pre|preview|dev)\d*([-.+_]|$)/i.test(tag) || /-(a|b|rc)\d+$/i.test(tag);
499
}
500
501
/**
502
 * A `fetch` that also trusts the CA certificate in `caFile`, for a hub with a
503
 * self-signed certificate (Node's `fetch` takes no CA). The file is read on
504
 * each request, so a renewed certificate needs no reload.
505
 */
506
export function fetchTrusting(caFile: string): typeof fetch {
507
  return ((input: string | URL | Request, init?: RequestInit) =>
508
    new Promise<Response>((resolve, reject) => {
509
      const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
510
      const secure = url.protocol === "https:";
511
      let ca: string[] | undefined;
512
      if (secure) {
513
        try {
514
          ca = [...tls.rootCertificates, readFileSync(caFile, "utf8")];
515
        } catch (e) {
516
          reject(new Error(`cannot read the hub's CA file ${caFile}: ${(e as Error).message}`));
517
          return;
518
        }
519
      }
520
      const headers: Record<string, string> = {};
521
      new Headers(init?.headers).forEach((v, k) => (headers[k] = v));
522
      const req = (secure ? https : http).request(url, { method: init?.method ?? "GET", headers, ca }, (res) => {
523
        const chunks: Buffer[] = [];
524
        res.on("data", (c: Buffer) => chunks.push(c));
525
        res.on("error", reject);
526
        res.on("end", () => {
527
          const status = res.statusCode ?? 0;
528
          const out = new Headers();
529
          for (const [k, v] of Object.entries(res.headers)) {
530
            if (v !== undefined) {
531
              out.set(k, Array.isArray(v) ? v.join(", ") : String(v));
532
            }
533
          }
534
          const empty = status === 204 || status === 304;
535
          resolve(new Response(empty ? null : Buffer.concat(chunks), { status, headers: out }));
536
        });
537
      });
538
      req.on("error", (e) => reject(Object.assign(new Error(`fetch failed: ${e.message}`), { cause: e })));
539
      if (init?.body !== undefined && init.body !== null) {
540
        req.write(typeof init.body === "string" ? init.body : Buffer.from(init.body as ArrayBuffer));
541
      }
542
      req.end();
543
    })) as typeof fetch;
544
}