@vite-hub/forge 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4186 @@
1
+ import { $ as toDate, B as milestoneId, C as createListing, D as forgeIterable, F as latestCommentOf, G as requireIssueOrPull, H as rateLimitOf, J as sleep, K as requireThread, L as memo, M as isFirstPage, N as isSecondaryRateLimit, O as getManyConcurrently, P as iteratePages, Q as teamOrg, S as createFetcher, T as degradesToWarning, U as rateLimitPart, V as phased, W as rateLimitReset, X as summariseChecks, Y as soleMergeMethod, a as ForgeApiError, at as versionAtLeast, b as anySignal, c as InsufficientScopeError, ct as isNamespaceRef, d as NotFoundError, et as toFileStatus, f as RateLimitedError, g as UnsupportedOperationError, i as ForbiddenError, it as toWarning, j as hostOf, l as MergeBlockedError, lt as isResolvedThread, n as BranchMovedError, nt as toPage, o as ForgeError, p as ReadOnlyError, pt as reactionContent, q as resolveToken, rt as toPullStats, s as ForgeTimeoutError, st as REACTION_CONTENTS, t as AuthenticationRequiredError, tt as toMergeError, u as MergeConflictError, v as abortable, x as checkRunState, y as actorLogin } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
+ import { C as verb, S as toFileContent, T as githubShapedWeb, _ as reviewState, a as verifyHmacSignature, b as supportOnly, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, h as isSha, j as signRs256Jwt, l as defineForgeProvider, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf, w as OWNER_NAME, y as splitMessage } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
+ import { t as toAuthorAssociation } from "./association-Ds6Tgs0W-Cu9_YCGq.js";
4
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/web-tS2yAE66.mjs
5
+ const RESERVED_PATHS = [
6
+ "about",
7
+ "account",
8
+ "apps",
9
+ "codespaces",
10
+ "collections",
11
+ "contact",
12
+ "customer-stories",
13
+ "dashboard",
14
+ "enterprise",
15
+ "enterprises",
16
+ "events",
17
+ "explore",
18
+ "features",
19
+ "gist",
20
+ "issues",
21
+ "join",
22
+ "login",
23
+ "logout",
24
+ "marketplace",
25
+ "new",
26
+ "notifications",
27
+ "organizations",
28
+ "orgs",
29
+ "pricing",
30
+ "pulls",
31
+ "search",
32
+ "security",
33
+ "settings",
34
+ "signup",
35
+ "site",
36
+ "sponsors",
37
+ "stars",
38
+ "topics",
39
+ "trending",
40
+ "users",
41
+ "watching"
42
+ ];
43
+ const REFERENCES = {
44
+ threads: [{
45
+ prefix: "#",
46
+ kind: "issue"
47
+ }, {
48
+ prefix: "GH-",
49
+ kind: "issue",
50
+ sameRepo: true
51
+ }],
52
+ repo: OWNER_NAME,
53
+ commits: true
54
+ };
55
+ function isGheCom(host) {
56
+ return /^api\.[^.]+\.ghe\.com$/.test(host);
57
+ }
58
+ /** The web host for an API host: `api.github.com` and `api.<name>.ghe.com` drop the `api.` prefix. */
59
+ function webHost(host) {
60
+ return host === "api.github.com" || isGheCom(host) ? host.slice(4) : host;
61
+ }
62
+ const GITHUB_WEB = {
63
+ forge: "github",
64
+ baseUrl: "https://api.github.com",
65
+ instance: webHost,
66
+ links: ({ baseUrl }) => {
67
+ const host = new URL(baseUrl).host;
68
+ const enterprise = host !== "api.github.com" && !isGheCom(host);
69
+ return githubShapedWeb(enterprise ? baseUrl.replace(/\/api\/v3$/, "") : `https://${webHost(host)}`, {
70
+ pull: "pull",
71
+ discussions: true,
72
+ ...host === "api.github.com" ? { rawOrigin: "https://raw.githubusercontent.com" } : {},
73
+ commentFragment: "issuecomment-",
74
+ file: (at) => `/blob/${encodeURIComponent(at)}`,
75
+ lineFragment: (line) => `L${line}`,
76
+ reserved: RESERVED_PATHS,
77
+ references: REFERENCES
78
+ });
79
+ }
80
+ };
81
+ //#endregion
82
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/github-B3p2LsXc.mjs
83
+ const TOKEN_PREFIXES = [
84
+ ["ghp_", "classic"],
85
+ ["gho_", "classic"],
86
+ ["github_pat_", "fine-grained"],
87
+ ["ghu_", "app-user"],
88
+ ["ghs_", "installation"]
89
+ ];
90
+ /** The kind of a GitHub token, from its `kind` or the prefix of `token`; `undefined` when neither tells. */
91
+ function tokenKindOf(auth, token = typeof auth.token === "string" ? auth.token : void 0) {
92
+ return auth.kind ?? (token === void 0 ? void 0 : TOKEN_PREFIXES.find(([prefix]) => token.startsWith(prefix))?.[1]);
93
+ }
94
+ const JWT_LIFETIME_SECONDS = 540;
95
+ const REFRESH_MARGIN_MS = 6e4;
96
+ function createAppCredentials(auth, context) {
97
+ let jwt;
98
+ const tokens = /* @__PURE__ */ new Map();
99
+ const exchanges = /* @__PURE__ */ new Map();
100
+ async function appJwt() {
101
+ if (jwt && jwt.expiresAt > Date.now() + REFRESH_MARGIN_MS) return jwt.value;
102
+ const now = Math.floor(Date.now() / 1e3);
103
+ const value = signRs256Jwt(auth.privateKey, {
104
+ iss: String(auth.appId),
105
+ iat: now - 60,
106
+ exp: now + JWT_LIFETIME_SECONDS
107
+ });
108
+ const entry = {
109
+ value,
110
+ expiresAt: (now + JWT_LIFETIME_SECONDS) * 1e3
111
+ };
112
+ jwt = entry;
113
+ value.catch(() => {
114
+ if (jwt === entry) jwt = void 0;
115
+ });
116
+ return value;
117
+ }
118
+ const fetcher = createFetcher({
119
+ ...context,
120
+ authHeaders: async () => ({ authorization: `Bearer ${await appJwt()}` })
121
+ });
122
+ async function installationTokenDetails(installationId, options) {
123
+ options?.signal?.throwIfAborted();
124
+ const cached = tokens.get(installationId);
125
+ if (cached && cached.expiresAt.getTime() > Date.now() + REFRESH_MARGIN_MS) return cached;
126
+ let exchange = exchanges.get(installationId);
127
+ if (!exchange) {
128
+ exchange = fetcher.json(`/app/installations/${installationId}/access_tokens`, { method: "POST" }).then(({ data }) => {
129
+ const token = {
130
+ token: data.token,
131
+ expiresAt: new Date(data.expires_at),
132
+ permissions: data.permissions ?? {},
133
+ repositorySelection: data.repository_selection
134
+ };
135
+ tokens.set(installationId, token);
136
+ return token;
137
+ });
138
+ const forget = () => exchanges.delete(installationId);
139
+ exchange.then(forget, forget);
140
+ exchanges.set(installationId, exchange);
141
+ }
142
+ return abortable(exchange, options?.signal);
143
+ }
144
+ return {
145
+ appJwt,
146
+ installationTokenDetails,
147
+ installationToken: async (installationId, options) => (await installationTokenDetails(installationId, options)).token
148
+ };
149
+ }
150
+ function createAuthHeaders(auth, credentials) {
151
+ if (!auth || auth.type === "anonymous") return async () => ({});
152
+ if (auth.type === "token") return async () => ({ authorization: `Bearer ${await resolveToken(auth)}` });
153
+ const app = credentials;
154
+ const installationId = auth.installationId;
155
+ if (installationId === void 0) return async () => ({ authorization: `Bearer ${await app.appJwt()}` });
156
+ return async () => ({ authorization: `Bearer ${await app.installationToken(String(installationId))}` });
157
+ }
158
+ /** Native GitHub event names per normalised kind, for hook subscriptions. */
159
+ const GITHUB_NATIVE_EVENTS = {
160
+ comment: [
161
+ "issue_comment",
162
+ "commit_comment",
163
+ "discussion_comment"
164
+ ],
165
+ review: ["pull_request_review"],
166
+ review_comment: ["pull_request_review_comment"],
167
+ state_change: [
168
+ "issues",
169
+ "pull_request",
170
+ "discussion"
171
+ ],
172
+ label: [
173
+ "issues",
174
+ "pull_request",
175
+ "label"
176
+ ],
177
+ assignment: ["issues", "pull_request"],
178
+ push: ["push"],
179
+ ref: ["create", "delete"],
180
+ repo: ["repository", "public"],
181
+ installation: ["installation", "installation_repositories"],
182
+ membership: [
183
+ "member",
184
+ "membership",
185
+ "organization",
186
+ "team"
187
+ ],
188
+ release: ["release"],
189
+ star: ["star"],
190
+ fork: ["fork"],
191
+ wiki: ["gollum"],
192
+ issue_type: ["issues"]
193
+ };
194
+ /** Normalised kinds and actions GitHub deliveries translate into. */
195
+ const GITHUB_WEBHOOK_EVENTS = [
196
+ {
197
+ kind: "comment",
198
+ action: "created"
199
+ },
200
+ {
201
+ kind: "comment",
202
+ action: "edited"
203
+ },
204
+ {
205
+ kind: "comment",
206
+ action: "deleted"
207
+ },
208
+ {
209
+ kind: "review",
210
+ action: "submitted"
211
+ },
212
+ {
213
+ kind: "review_comment",
214
+ action: "created"
215
+ },
216
+ {
217
+ kind: "review_comment",
218
+ action: "edited"
219
+ },
220
+ {
221
+ kind: "review_comment",
222
+ action: "deleted"
223
+ },
224
+ {
225
+ kind: "state_change",
226
+ action: "opened"
227
+ },
228
+ {
229
+ kind: "state_change",
230
+ action: "closed"
231
+ },
232
+ {
233
+ kind: "state_change",
234
+ action: "reopened"
235
+ },
236
+ {
237
+ kind: "state_change",
238
+ action: "merged"
239
+ },
240
+ {
241
+ kind: "state_change",
242
+ action: "ready_for_review"
243
+ },
244
+ {
245
+ kind: "state_change",
246
+ action: "converted_to_draft"
247
+ },
248
+ {
249
+ kind: "label",
250
+ action: "labelled"
251
+ },
252
+ {
253
+ kind: "label",
254
+ action: "unlabelled"
255
+ },
256
+ {
257
+ kind: "assignment",
258
+ action: "assigned"
259
+ },
260
+ {
261
+ kind: "assignment",
262
+ action: "unassigned"
263
+ },
264
+ {
265
+ kind: "assignment",
266
+ action: "review_requested"
267
+ },
268
+ { kind: "push" },
269
+ {
270
+ kind: "ref",
271
+ action: "created"
272
+ },
273
+ {
274
+ kind: "ref",
275
+ action: "deleted"
276
+ },
277
+ {
278
+ kind: "repo",
279
+ action: "renamed"
280
+ },
281
+ {
282
+ kind: "repo",
283
+ action: "transferred"
284
+ },
285
+ {
286
+ kind: "repo",
287
+ action: "archived"
288
+ },
289
+ {
290
+ kind: "repo",
291
+ action: "unarchived"
292
+ },
293
+ {
294
+ kind: "repo",
295
+ action: "edited"
296
+ },
297
+ { kind: "installation" },
298
+ { kind: "membership" },
299
+ {
300
+ kind: "release",
301
+ action: "created"
302
+ },
303
+ {
304
+ kind: "release",
305
+ action: "published"
306
+ },
307
+ {
308
+ kind: "release",
309
+ action: "edited"
310
+ },
311
+ {
312
+ kind: "release",
313
+ action: "deleted"
314
+ },
315
+ {
316
+ kind: "release",
317
+ action: "other"
318
+ },
319
+ {
320
+ kind: "star",
321
+ action: "created"
322
+ },
323
+ {
324
+ kind: "star",
325
+ action: "deleted"
326
+ },
327
+ {
328
+ kind: "fork",
329
+ action: "created"
330
+ },
331
+ {
332
+ kind: "wiki",
333
+ action: "created"
334
+ },
335
+ {
336
+ kind: "wiki",
337
+ action: "edited"
338
+ },
339
+ {
340
+ kind: "issue_type",
341
+ action: "typed"
342
+ },
343
+ {
344
+ kind: "issue_type",
345
+ action: "untyped"
346
+ }
347
+ ];
348
+ const FORGE = "github";
349
+ function toActor(instance, user) {
350
+ if (!user?.login) return;
351
+ return {
352
+ forge: FORGE,
353
+ instance,
354
+ login: user.login,
355
+ id: String(user.id ?? user.login),
356
+ name: user.name ?? void 0,
357
+ avatarUrl: user.avatar_url,
358
+ url: user.html_url,
359
+ typeRaw: user.type,
360
+ isBotHint: user.type === "Bot" || user.login.endsWith("[bot]"),
361
+ ...user.type === "Bot" && user.login.endsWith("[bot]") ? { app: { slug: user.login.slice(0, -5) } } : {}
362
+ };
363
+ }
364
+ function toUser(instance, user) {
365
+ return {
366
+ ...toActor(instance, user),
367
+ bio: user.bio ?? void 0,
368
+ company: user.company ?? void 0,
369
+ location: user.location ?? void 0,
370
+ websiteUrl: user.blog || void 0,
371
+ createdAt: toDate(user.created_at),
372
+ followers: user.followers,
373
+ following: user.following,
374
+ publicRepos: user.public_repos,
375
+ raw: user
376
+ };
377
+ }
378
+ function toRepoRef(instance, repo) {
379
+ const [owner, name] = repo.full_name.split("/");
380
+ return {
381
+ forge: FORGE,
382
+ instance,
383
+ owner: repo.owner?.login ?? owner ?? "",
384
+ name: repo.name ?? name ?? "",
385
+ externalId: repo.id === void 0 ? void 0 : String(repo.id)
386
+ };
387
+ }
388
+ /** Reads `owner` and `name` out of an API repository URL, which search results carry instead of a nested repository. */
389
+ function repoRefFromApiUrl(instance, url) {
390
+ const [, owner, name] = url?.match(/\/repos\/([^/]+)\/([^/]+)$/) ?? [];
391
+ return owner && name ? {
392
+ forge: FORGE,
393
+ instance,
394
+ owner,
395
+ name
396
+ } : void 0;
397
+ }
398
+ const MERGE_COMMIT_TITLES = {
399
+ PR_TITLE: "pull_request_title",
400
+ COMMIT_OR_PR_TITLE: "commit_or_pull_request_title",
401
+ MERGE_MESSAGE: "merge_message"
402
+ };
403
+ const MERGE_COMMIT_MESSAGES = {
404
+ PR_BODY: "pull_request_body",
405
+ PR_TITLE: "pull_request_title",
406
+ COMMIT_MESSAGES: "commit_messages",
407
+ BLANK: "blank"
408
+ };
409
+ function toMergeCommitDefaults(title, message) {
410
+ return title || message ? {
411
+ title: MERGE_COMMIT_TITLES[title ?? ""],
412
+ titleRaw: title,
413
+ message: MERGE_COMMIT_MESSAGES[message ?? ""],
414
+ messageRaw: message
415
+ } : void 0;
416
+ }
417
+ function toMergeCommit(raw) {
418
+ const merge = toMergeCommitDefaults(raw.merge_commit_title, raw.merge_commit_message);
419
+ const squash = toMergeCommitDefaults(raw.squash_merge_commit_title, raw.squash_merge_commit_message);
420
+ return merge || squash ? {
421
+ merge,
422
+ squash
423
+ } : void 0;
424
+ }
425
+ function toRepo(instance, raw) {
426
+ const visibility = raw.visibility === "internal" ? "internal" : raw.private || raw.visibility === "private" ? "private" : "public";
427
+ return {
428
+ ref: toRepoRef(instance, raw),
429
+ description: raw.description ?? void 0,
430
+ defaultBranch: raw.default_branch,
431
+ visibility,
432
+ visibilityRaw: raw.visibility ?? (raw.private === void 0 ? void 0 : raw.private ? "private" : "public"),
433
+ isFork: raw.fork ?? false,
434
+ isArchived: raw.archived ?? false,
435
+ parent: raw.parent ? toRepoRef(instance, raw.parent) : void 0,
436
+ topics: raw.topics ?? [],
437
+ url: raw.html_url,
438
+ cloneUrls: raw.clone_url || raw.ssh_url ? {
439
+ https: raw.clone_url,
440
+ ssh: raw.ssh_url
441
+ } : void 0,
442
+ createdAt: toDate(raw.created_at),
443
+ updatedAt: toDate(raw.updated_at),
444
+ pushedAt: toDate(raw.pushed_at),
445
+ owner: toActor(instance, raw.owner),
446
+ language: raw.language ?? void 0,
447
+ homepage: raw.homepage || void 0,
448
+ licence: raw.license?.spdx_id && raw.license.spdx_id !== "NOASSERTION" ? raw.license.spdx_id : void 0,
449
+ stars: raw.stargazers_count,
450
+ forks: raw.forks_count,
451
+ watchers: raw.subscribers_count,
452
+ mergeMethods: raw.allow_merge_commit === void 0 && raw.allow_squash_merge === void 0 && raw.allow_rebase_merge === void 0 ? void 0 : [
453
+ ...raw.allow_merge_commit ? ["merge"] : [],
454
+ ...raw.allow_squash_merge ? ["squash"] : [],
455
+ ...raw.allow_rebase_merge ? ["rebase"] : []
456
+ ],
457
+ deleteBranchOnMerge: raw.delete_branch_on_merge,
458
+ mergeCommit: toMergeCommit(raw),
459
+ features: raw.has_issues === void 0 ? void 0 : {
460
+ issues: raw.has_issues,
461
+ pullRequests: true,
462
+ discussions: raw.has_discussions ?? false,
463
+ wiki: raw.has_wiki ?? false,
464
+ projects: raw.has_projects ?? false,
465
+ releases: true
466
+ },
467
+ permissions: raw.permissions ? {
468
+ admin: raw.permissions.admin,
469
+ maintain: raw.permissions.maintain ?? raw.permissions.admin,
470
+ push: raw.permissions.push,
471
+ triage: raw.permissions.triage ?? raw.permissions.push,
472
+ pull: raw.permissions.pull
473
+ } : void 0,
474
+ raw
475
+ };
476
+ }
477
+ function toReactions(raw) {
478
+ if (!raw) return;
479
+ const counts = Object.fromEntries(REACTION_CONTENTS.flatMap((name) => raw[name] ? [[name, raw[name]]] : []));
480
+ return {
481
+ total: raw.total_count ?? Object.values(counts).reduce((sum, count) => sum + count, 0),
482
+ counts
483
+ };
484
+ }
485
+ function toMilestone(raw) {
486
+ return raw ? {
487
+ id: String(raw.number ?? raw.id ?? ""),
488
+ title: raw.title,
489
+ state: raw.state === "closed" ? "closed" : "open",
490
+ description: raw.description ?? void 0,
491
+ dueOn: toDate(raw.due_on),
492
+ url: raw.html_url,
493
+ raw
494
+ } : void 0;
495
+ }
496
+ function toIssueType(raw) {
497
+ return raw ? {
498
+ id: raw.node_id,
499
+ name: raw.name,
500
+ description: raw.description || void 0,
501
+ colour: raw.color ?? void 0,
502
+ enabled: raw.is_enabled,
503
+ raw
504
+ } : void 0;
505
+ }
506
+ /** GitHub's `role_name`, or the permission block when a listing reports only that. */
507
+ function toRole(raw) {
508
+ switch (raw.role_name) {
509
+ case "admin":
510
+ case "maintain":
511
+ case "write":
512
+ case "triage":
513
+ case "read": return raw.role_name;
514
+ }
515
+ const permissions = raw.permissions;
516
+ if (!permissions) return "none";
517
+ return permissions.admin ? "admin" : permissions.maintain ? "maintain" : permissions.push ? "write" : permissions.triage ? "triage" : permissions.pull ? "read" : "none";
518
+ }
519
+ function toCollaborator(instance, raw) {
520
+ return {
521
+ actor: toActor(instance, raw),
522
+ role: toRole(raw),
523
+ roleRaw: raw.role_name,
524
+ raw
525
+ };
526
+ }
527
+ function toContributor(instance, raw) {
528
+ if (!("login" in raw)) return {
529
+ name: raw.name || void 0,
530
+ email: raw.email || void 0,
531
+ contributions: raw.contributions,
532
+ raw
533
+ };
534
+ return {
535
+ actor: toActor(instance, raw),
536
+ contributions: raw.contributions,
537
+ raw
538
+ };
539
+ }
540
+ function toContributorStats(instance, raw) {
541
+ return {
542
+ actor: toActor(instance, raw.author),
543
+ commits: raw.total,
544
+ weeks: raw.weeks.map((week) => ({
545
+ week: /* @__PURE__ */ new Date(week.w * 1e3),
546
+ additions: week.a ?? 0,
547
+ deletions: week.d ?? 0,
548
+ commits: week.c ?? 0
549
+ })),
550
+ raw
551
+ };
552
+ }
553
+ function toTeam(instance, org, raw) {
554
+ const parent = raw.parent ? {
555
+ forge: FORGE,
556
+ instance,
557
+ org,
558
+ id: String(raw.parent.id),
559
+ slug: raw.parent.slug
560
+ } : void 0;
561
+ return {
562
+ ref: {
563
+ forge: FORGE,
564
+ instance,
565
+ org,
566
+ id: String(raw.id),
567
+ slug: raw.slug
568
+ },
569
+ name: raw.name,
570
+ description: raw.description ?? void 0,
571
+ permission: raw.permission,
572
+ visibilityRaw: raw.privacy,
573
+ parent,
574
+ url: raw.html_url,
575
+ raw
576
+ };
577
+ }
578
+ function toThreadKind(subjectType) {
579
+ switch (subjectType) {
580
+ case "PullRequest": return "pull_request";
581
+ case "Discussion": return "discussion";
582
+ case "Issue": return "issue";
583
+ default: return;
584
+ }
585
+ }
586
+ function toThreadState(issue) {
587
+ if (issue.merged || issue.merged_at || issue.pull_request?.merged_at) return "merged";
588
+ if (issue.state === "open" || issue.state === "closed") return issue.state;
589
+ return "unknown";
590
+ }
591
+ function numberFromUrl(url) {
592
+ return /\/(?:issues|pulls|commits|discussions)\/([^/?#]+)/.exec(url ?? "")?.[1];
593
+ }
594
+ const REASONS = {
595
+ approval_requested: "approval_requested",
596
+ assign: "assigned",
597
+ author: "author",
598
+ ci_activity: "ci_activity",
599
+ comment: "comment",
600
+ invitation: "invitation",
601
+ manual: "manual",
602
+ mention: "mention",
603
+ review_requested: "review_requested",
604
+ security_alert: "security_alert",
605
+ security_advisory_credit: "security_alert",
606
+ state_change: "state_change",
607
+ subscribed: "subscribed",
608
+ team_mention: "team_mention"
609
+ };
610
+ function toReason(reason) {
611
+ return REASONS[reason] ?? "unknown";
612
+ }
613
+ const SECURITY_SUBJECTS = /* @__PURE__ */ new Set([
614
+ "RepositoryVulnerabilityAlert",
615
+ "RepositoryDependabotAlertsThread",
616
+ "SecretScanningAlert",
617
+ "RepositoryAdvisory"
618
+ ]);
619
+ const SECURITY_SUBJECTS_KIND = {
620
+ RepositoryVulnerabilityAlert: "dependency",
621
+ RepositoryDependabotAlertsThread: "dependency",
622
+ SecretScanningAlert: "secret",
623
+ RepositoryAdvisory: "advisory"
624
+ };
625
+ function lastSegment(url) {
626
+ return /\/([^/?#]+)\/?$/.exec(url ?? "")?.[1];
627
+ }
628
+ function toSubject(instance, raw) {
629
+ const repo = toRepoRef(instance, raw.repository);
630
+ const type = raw.subject.type;
631
+ const kind = toThreadKind(type);
632
+ if (kind) return {
633
+ type: "thread",
634
+ thread: {
635
+ forge: FORGE,
636
+ instance,
637
+ repo,
638
+ kind,
639
+ typeRaw: type,
640
+ number: numberFromUrl(raw.subject.url)
641
+ }
642
+ };
643
+ const sha = type === "Commit" ? numberFromUrl(raw.subject.url) : void 0;
644
+ if (sha) return {
645
+ type: "commit",
646
+ commit: {
647
+ forge: FORGE,
648
+ instance,
649
+ repo,
650
+ sha
651
+ }
652
+ };
653
+ if (type === "Release") return {
654
+ type: "release",
655
+ release: {
656
+ forge: FORGE,
657
+ instance,
658
+ repo,
659
+ id: lastSegment(raw.subject.url) ?? raw.id
660
+ }
661
+ };
662
+ if (SECURITY_SUBJECTS.has(type)) {
663
+ const kind = SECURITY_SUBJECTS_KIND[type];
664
+ return {
665
+ type: "security_alert",
666
+ alert: {
667
+ forge: FORGE,
668
+ instance,
669
+ repo,
670
+ id: lastSegment(raw.subject.url) ?? raw.id,
671
+ ...kind ? { kind } : {}
672
+ }
673
+ };
674
+ }
675
+ if (type === "RepositoryInvitation") return {
676
+ type: "repo",
677
+ repo
678
+ };
679
+ return {
680
+ type: "other",
681
+ typeRaw: type,
682
+ repo,
683
+ id: lastSegment(raw.subject.url),
684
+ url: raw.subject.url ?? void 0
685
+ };
686
+ }
687
+ function toNotification(instance, raw) {
688
+ const subject = toSubject(instance, raw);
689
+ const latestComment = latestCommentOf(subject, raw.subject.latest_comment_url);
690
+ return {
691
+ ref: {
692
+ forge: FORGE,
693
+ instance,
694
+ id: raw.id
695
+ },
696
+ subject,
697
+ subjectTypeRaw: raw.subject.type,
698
+ reason: toReason(raw.reason),
699
+ reasonRaw: raw.reason,
700
+ unread: raw.unread,
701
+ title: raw.subject.title,
702
+ subjectState: "unknown",
703
+ updatedAt: toDate(raw.updated_at) ?? /* @__PURE__ */ new Date(0),
704
+ lastReadAt: toDate(raw.last_read_at),
705
+ url: raw.subject.url ?? raw.url,
706
+ ...latestComment ? { latestComment } : {},
707
+ raw
708
+ };
709
+ }
710
+ function toLabel(raw) {
711
+ return {
712
+ name: raw.name,
713
+ colour: raw.color ?? void 0,
714
+ description: raw.description ?? void 0
715
+ };
716
+ }
717
+ function toLabels(labels) {
718
+ return (labels ?? []).flatMap((label) => {
719
+ if (typeof label === "string") return [{ name: label }];
720
+ return label.name ? [{
721
+ name: label.name,
722
+ colour: label.color ?? void 0,
723
+ description: label.description ?? void 0
724
+ }] : [];
725
+ });
726
+ }
727
+ function toReviewers(instance, raw) {
728
+ const users = (raw.requested_reviewers ?? []).flatMap((user) => {
729
+ const actor = toActor(instance, user);
730
+ return actor ? [{
731
+ actor,
732
+ state: "pending",
733
+ stateRaw: "requested"
734
+ }] : [];
735
+ });
736
+ const teams = (raw.requested_teams ?? []).map((team) => ({
737
+ actor: {
738
+ forge: FORGE,
739
+ instance,
740
+ login: team.slug,
741
+ id: String(team.id),
742
+ name: team.name,
743
+ url: team.html_url,
744
+ typeRaw: "Team",
745
+ isBotHint: false
746
+ },
747
+ state: "pending",
748
+ stateRaw: "requested",
749
+ isTeam: true
750
+ }));
751
+ return [...users, ...teams];
752
+ }
753
+ /** Builds a thread from an issue, a pull request, or a pull request as returned by the issues API. */
754
+ function toThread(ref, raw) {
755
+ const kind = raw.pull_request || raw.head ? "pull_request" : ref.kind;
756
+ return {
757
+ ref: {
758
+ ...ref,
759
+ kind,
760
+ externalId: raw.node_id ?? ref.externalId
761
+ },
762
+ kind,
763
+ title: raw.title,
764
+ body: raw.body ?? void 0,
765
+ state: toThreadState(raw),
766
+ stateRaw: raw.state,
767
+ stateReason: raw.state_reason ?? void 0,
768
+ isDraft: raw.draft ?? false,
769
+ author: toActor(ref.instance, raw.user),
770
+ ...toAuthorAssociation(raw.author_association),
771
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(ref.instance, user) ?? []),
772
+ reviewers: toReviewers(ref.instance, raw),
773
+ labels: toLabels(raw.labels),
774
+ url: raw.html_url,
775
+ createdAt: toDate(raw.created_at),
776
+ updatedAt: toDate(raw.updated_at),
777
+ closedAt: toDate(raw.closed_at),
778
+ mergedAt: toDate(raw.merged_at ?? raw.pull_request?.merged_at),
779
+ mergedBy: toActor(ref.instance, raw.merged_by),
780
+ lastActivityAt: toDate(raw.updated_at),
781
+ locked: raw.locked,
782
+ commentCount: raw.comments,
783
+ milestone: toMilestone(raw.milestone),
784
+ issueType: toIssueType(raw.type),
785
+ reactions: toReactions(raw.reactions),
786
+ branches: raw.head && raw.base ? {
787
+ head: {
788
+ ref: raw.head.ref,
789
+ sha: raw.head.sha,
790
+ repo: raw.head.repo ? toRepoRef(ref.instance, raw.head.repo) : void 0
791
+ },
792
+ base: {
793
+ ref: raw.base.ref,
794
+ sha: raw.base.sha
795
+ },
796
+ mergeCommitSha: raw.merge_commit_sha ?? void 0
797
+ } : void 0,
798
+ stats: toPullStats({
799
+ additions: raw.additions,
800
+ deletions: raw.deletions,
801
+ changedFileCount: raw.changed_files,
802
+ commitCount: raw.commits
803
+ }),
804
+ raw
805
+ };
806
+ }
807
+ function toComment(thread, raw) {
808
+ return {
809
+ ref: {
810
+ forge: FORGE,
811
+ instance: thread.instance,
812
+ thread,
813
+ id: String(raw.id)
814
+ },
815
+ ...commentFields(thread.instance, raw)
816
+ };
817
+ }
818
+ function toCommitComment(commit, raw) {
819
+ return {
820
+ ref: {
821
+ forge: FORGE,
822
+ instance: commit.instance,
823
+ commit,
824
+ id: String(raw.id)
825
+ },
826
+ ...commentFields(commit.instance, raw)
827
+ };
828
+ }
829
+ function commentFields(instance, raw) {
830
+ return {
831
+ body: raw.body ?? "",
832
+ author: toActor(instance, raw.user),
833
+ ...toAuthorAssociation(raw.author_association),
834
+ createdAt: toDate(raw.created_at),
835
+ updatedAt: toDate(raw.updated_at),
836
+ url: raw.html_url,
837
+ reactions: toReactions(raw.reactions),
838
+ raw
839
+ };
840
+ }
841
+ const EVENT_KINDS = {
842
+ "commented": "comment",
843
+ "reviewed": "review",
844
+ "line_commented": "review_comment",
845
+ "review_requested": "assignment",
846
+ "review_request_removed": "assignment",
847
+ "committed": "commit",
848
+ "labeled": "label",
849
+ "unlabeled": "label",
850
+ "closed": "state_change",
851
+ "reopened": "state_change",
852
+ "merged": "state_change",
853
+ "convert_to_draft": "state_change",
854
+ "ready_for_review": "state_change",
855
+ "assigned": "assignment",
856
+ "unassigned": "assignment",
857
+ "mentioned": "mention",
858
+ "cross-referenced": "referenced",
859
+ "referenced": "referenced",
860
+ "reaction": "reaction"
861
+ };
862
+ function toEventKind(event) {
863
+ return EVENT_KINDS[event ?? ""] ?? "other";
864
+ }
865
+ function summarise(entry, kind, actor) {
866
+ const who = actor?.login ?? "someone";
867
+ switch (kind) {
868
+ case "comment": return `${who} commented`;
869
+ case "review": return `${who} reviewed (${entry.state ?? "commented"})`;
870
+ case "review_comment": return `${who} commented on a line`;
871
+ case "commit": return `${entry.author?.name ?? who} committed ${entry.sha?.slice(0, 7) ?? "a commit"}`;
872
+ case "label": return `${who} ${entry.event === "unlabeled" ? "removed" : "added"} label ${entry.label?.name ?? ""}`.trim();
873
+ case "state_change": return `${who} ${entry.event ?? "changed state"}`;
874
+ case "referenced": return `${who} referenced this`;
875
+ case "assignment":
876
+ if (entry.event === "review_requested" || entry.event === "review_request_removed") return `${who} ${entry.event === "review_requested" ? "requested review from" : "removed the review request for"} ${entry.requested_reviewer?.login ?? ""}`.trim();
877
+ return `${who} ${entry.event === "unassigned" ? "unassigned" : "assigned"} ${entry.assignee?.login ?? ""}`.trim();
878
+ default: return `${who} ${entry.event ?? "acted"}`;
879
+ }
880
+ }
881
+ /** A `cross-referenced` entry names the thread that mentioned this one; a `referenced` entry names a commit. */
882
+ function crossReference(instance, thread, entry) {
883
+ const source = entry.source?.issue;
884
+ if (source) {
885
+ const repo = source.repository ? toRepoRef(instance, source.repository) : thread.repo;
886
+ return {
887
+ type: "referenced",
888
+ from: {
889
+ forge: FORGE,
890
+ instance,
891
+ repo,
892
+ kind: source.pull_request ? "pull_request" : "issue",
893
+ number: String(source.number)
894
+ },
895
+ fromRepo: repo
896
+ };
897
+ }
898
+ return entry.commit_id ? {
899
+ type: "referenced",
900
+ from: {
901
+ forge: FORGE,
902
+ instance,
903
+ repo: thread.repo,
904
+ sha: entry.commit_id
905
+ },
906
+ fromRepo: thread.repo
907
+ } : { type: "referenced" };
908
+ }
909
+ function timelineDetail(instance, thread, entry, kind) {
910
+ switch (kind) {
911
+ case "comment": return {
912
+ type: "comment",
913
+ comment: entry.id !== void 0 ? {
914
+ forge: FORGE,
915
+ instance,
916
+ thread,
917
+ id: String(entry.id)
918
+ } : void 0,
919
+ body: entry.body ?? void 0
920
+ };
921
+ case "review": return {
922
+ type: "review",
923
+ state: reviewState(entry.state),
924
+ stateRaw: entry.state,
925
+ body: entry.body ?? void 0,
926
+ review: entry.id !== void 0 ? {
927
+ forge: FORGE,
928
+ instance,
929
+ thread,
930
+ id: String(entry.id)
931
+ } : void 0
932
+ };
933
+ case "label": return entry.label ? {
934
+ type: "label",
935
+ label: entry.label.name
936
+ } : void 0;
937
+ case "assignment": return {
938
+ type: "assignment",
939
+ assignee: toActor(instance, entry.assignee ?? entry.requested_reviewer)
940
+ };
941
+ case "referenced": return crossReference(instance, thread, entry);
942
+ case "state_change": return entry.event === "convert_to_draft" || entry.event === "ready_for_review" ? {
943
+ type: "state_change",
944
+ state: "open",
945
+ draft: entry.event === "convert_to_draft"
946
+ } : {
947
+ type: "state_change",
948
+ state: entry.event === "merged" ? "merged" : entry.event === "closed" ? "closed" : "open",
949
+ reason: entry.state_reason ?? void 0
950
+ };
951
+ default: return;
952
+ }
953
+ }
954
+ function toEvent(instance, thread, entry, source = "poll") {
955
+ const kind = toEventKind(entry.event);
956
+ const actor = toActor(instance, entry.actor ?? entry.user);
957
+ return {
958
+ forge: FORGE,
959
+ instance,
960
+ id: String(entry.node_id ?? entry.id ?? entry.sha ?? `${thread.number ?? ""}-${entry.event}-${entry.created_at}`),
961
+ kind,
962
+ kindRaw: entry.event,
963
+ detail: timelineDetail(instance, thread, entry, kind),
964
+ summary: summarise(entry, kind, actor),
965
+ ...eventTime(toDate(entry.created_at ?? entry.submitted_at ?? entry.author?.date ?? entry.committer?.date), /* @__PURE__ */ new Date(0)),
966
+ actor,
967
+ repo: thread.repo,
968
+ thread,
969
+ source,
970
+ payload: entry
971
+ };
972
+ }
973
+ function statusState(state) {
974
+ return state === "success" ? "success" : state === "pending" ? "pending" : state === "failure" || state === "error" ? "failure" : "unknown";
975
+ }
976
+ const ACTIONS_JOB_URL = /\/actions\/runs\/(\d+)\/job\/\d+$/;
977
+ function toCheckRun(repo, raw) {
978
+ const runId = raw.html_url?.match(ACTIONS_JOB_URL)?.[1];
979
+ return {
980
+ ref: {
981
+ forge: FORGE,
982
+ instance: repo.instance,
983
+ repo,
984
+ id: String(raw.id),
985
+ type: "check_run",
986
+ ...raw.app?.slug ? { app: raw.app.slug } : {}
987
+ },
988
+ name: raw.name,
989
+ state: checkRunState(raw.status, raw.conclusion),
990
+ stateRaw: raw.status,
991
+ conclusionRaw: raw.conclusion ?? void 0,
992
+ url: raw.html_url ?? raw.details_url ?? void 0,
993
+ startedAt: toDate(raw.started_at),
994
+ completedAt: toDate(raw.completed_at),
995
+ ...runId ? { run: {
996
+ forge: FORGE,
997
+ instance: repo.instance,
998
+ repo,
999
+ id: runId
1000
+ } } : {},
1001
+ raw
1002
+ };
1003
+ }
1004
+ function toStatusCheck(repo, raw) {
1005
+ const state = statusState(raw.state);
1006
+ return {
1007
+ ref: {
1008
+ forge: FORGE,
1009
+ instance: repo.instance,
1010
+ repo,
1011
+ id: String(raw.id),
1012
+ type: "status"
1013
+ },
1014
+ name: raw.context,
1015
+ state,
1016
+ stateRaw: raw.state,
1017
+ url: raw.target_url ?? void 0,
1018
+ startedAt: toDate(raw.created_at),
1019
+ completedAt: state === "pending" ? void 0 : toDate(raw.updated_at),
1020
+ raw
1021
+ };
1022
+ }
1023
+ function toRelease(repo, raw) {
1024
+ const ref = {
1025
+ forge: FORGE,
1026
+ instance: repo.instance,
1027
+ repo,
1028
+ id: String(raw.id),
1029
+ tag: raw.tag_name
1030
+ };
1031
+ return {
1032
+ ref,
1033
+ name: raw.name ?? void 0,
1034
+ tag: raw.tag_name,
1035
+ body: raw.body ?? void 0,
1036
+ isDraft: raw.draft,
1037
+ isPrerelease: raw.prerelease,
1038
+ immutable: raw.immutable,
1039
+ author: toActor(repo.instance, raw.author),
1040
+ publishedAt: toDate(raw.published_at),
1041
+ createdAt: toDate(raw.created_at),
1042
+ url: raw.html_url,
1043
+ assets: raw.assets?.map((asset) => ({
1044
+ ...asset.id === void 0 ? {} : { ref: {
1045
+ forge: FORGE,
1046
+ instance: repo.instance,
1047
+ repo,
1048
+ release: ref,
1049
+ id: String(asset.id)
1050
+ } },
1051
+ name: asset.name,
1052
+ url: asset.browser_download_url,
1053
+ size: asset.size,
1054
+ downloadCount: asset.download_count,
1055
+ contentType: asset.content_type
1056
+ })),
1057
+ raw
1058
+ };
1059
+ }
1060
+ function toSeverity(raw) {
1061
+ switch (raw?.toLowerCase()) {
1062
+ case "critical": return "critical";
1063
+ case "high":
1064
+ case "error": return "high";
1065
+ case "medium":
1066
+ case "moderate":
1067
+ case "warning": return "medium";
1068
+ case "low":
1069
+ case "note": return "low";
1070
+ default: return "unknown";
1071
+ }
1072
+ }
1073
+ function alertState(raw) {
1074
+ return raw === "open" ? "open" : raw === "fixed" ? "fixed" : raw === "dismissed" || raw === "auto_dismissed" ? "dismissed" : "unknown";
1075
+ }
1076
+ function toDependabotAlert(repo, raw) {
1077
+ const severityRaw = raw.security_vulnerability?.severity ?? raw.security_advisory?.severity;
1078
+ const pkg = raw.dependency?.package;
1079
+ return {
1080
+ ref: {
1081
+ forge: FORGE,
1082
+ instance: repo.instance,
1083
+ repo,
1084
+ id: String(raw.number),
1085
+ kind: "dependency",
1086
+ severityRaw
1087
+ },
1088
+ kind: "dependency",
1089
+ kindRaw: "dependabot",
1090
+ severity: toSeverity(severityRaw),
1091
+ severityRaw,
1092
+ state: alertState(raw.state),
1093
+ stateRaw: raw.state,
1094
+ title: raw.security_advisory?.summary ?? `Vulnerable dependency ${pkg?.name ?? ""}`.trim(),
1095
+ ...pkg ? { package: {
1096
+ ecosystem: pkg.ecosystem,
1097
+ name: pkg.name,
1098
+ vulnerableRange: raw.security_vulnerability?.vulnerable_version_range,
1099
+ fixedIn: raw.security_vulnerability?.first_patched_version?.identifier
1100
+ } } : {},
1101
+ url: raw.html_url,
1102
+ createdAt: toDate(raw.created_at),
1103
+ updatedAt: toDate(raw.updated_at),
1104
+ dismissedAt: toDate(raw.dismissed_at),
1105
+ raw
1106
+ };
1107
+ }
1108
+ function toCodeScanningAlert(repo, raw) {
1109
+ const severityRaw = raw.rule?.security_severity_level ?? raw.rule?.severity ?? void 0;
1110
+ return {
1111
+ ref: {
1112
+ forge: FORGE,
1113
+ instance: repo.instance,
1114
+ repo,
1115
+ id: String(raw.number),
1116
+ kind: "code_scanning",
1117
+ severityRaw
1118
+ },
1119
+ kind: "code_scanning",
1120
+ kindRaw: raw.tool?.name ?? "code_scanning",
1121
+ severity: toSeverity(severityRaw),
1122
+ severityRaw,
1123
+ state: alertState(raw.state),
1124
+ stateRaw: raw.state,
1125
+ title: raw.rule?.description ?? raw.rule?.name ?? raw.rule?.id ?? "Code scanning alert",
1126
+ url: raw.html_url,
1127
+ createdAt: toDate(raw.created_at),
1128
+ updatedAt: toDate(raw.updated_at),
1129
+ dismissedAt: toDate(raw.dismissed_at),
1130
+ raw
1131
+ };
1132
+ }
1133
+ /** Secret scanning reports no severity. A revoked secret is fixed; any other resolution dismisses the alert. */
1134
+ function toSecretScanningAlert(repo, raw) {
1135
+ const state = raw.state === "open" ? "open" : raw.state === "resolved" ? raw.resolution === "revoked" ? "fixed" : "dismissed" : "unknown";
1136
+ return {
1137
+ ref: {
1138
+ forge: FORGE,
1139
+ instance: repo.instance,
1140
+ repo,
1141
+ id: String(raw.number),
1142
+ kind: "secret"
1143
+ },
1144
+ kind: "secret",
1145
+ kindRaw: raw.secret_type ?? "secret_scanning",
1146
+ severity: "unknown",
1147
+ state,
1148
+ stateRaw: raw.resolution ? `${raw.state}:${raw.resolution}` : raw.state,
1149
+ title: raw.secret_type_display_name ?? raw.secret_type ?? "Secret scanning alert",
1150
+ url: raw.html_url,
1151
+ createdAt: toDate(raw.created_at),
1152
+ updatedAt: toDate(raw.updated_at),
1153
+ dismissedAt: state === "dismissed" ? toDate(raw.resolved_at) : void 0,
1154
+ raw
1155
+ };
1156
+ }
1157
+ /** A private vulnerability report in triage, or a draft, is open; a published advisory is fixed; a closed or withdrawn one is dismissed. */
1158
+ function toRepositoryAdvisory(repo, raw) {
1159
+ const state = raw.state === "triage" || raw.state === "draft" ? "open" : raw.state === "published" ? "fixed" : raw.state === "closed" || raw.state === "withdrawn" ? "dismissed" : "unknown";
1160
+ const severityRaw = raw.severity ?? void 0;
1161
+ const vulnerability = raw.vulnerabilities?.find((item) => item.package?.name);
1162
+ return {
1163
+ ref: {
1164
+ forge: FORGE,
1165
+ instance: repo.instance,
1166
+ repo,
1167
+ id: raw.ghsa_id,
1168
+ kind: "advisory",
1169
+ severityRaw
1170
+ },
1171
+ kind: "advisory",
1172
+ kindRaw: "repository_advisory",
1173
+ severity: toSeverity(severityRaw),
1174
+ severityRaw,
1175
+ state,
1176
+ stateRaw: raw.state,
1177
+ title: raw.summary,
1178
+ ...vulnerability?.package?.name ? { package: {
1179
+ ecosystem: vulnerability.package.ecosystem,
1180
+ name: vulnerability.package.name,
1181
+ vulnerableRange: vulnerability.vulnerable_version_range ?? void 0,
1182
+ fixedIn: vulnerability.patched_versions ?? void 0
1183
+ } } : {},
1184
+ url: raw.html_url,
1185
+ createdAt: toDate(raw.created_at),
1186
+ updatedAt: toDate(raw.updated_at),
1187
+ dismissedAt: state === "dismissed" ? toDate(raw.withdrawn_at ?? raw.closed_at) : void 0,
1188
+ raw
1189
+ };
1190
+ }
1191
+ function toReviewComment(thread, raw, reviewThread) {
1192
+ return {
1193
+ ref: {
1194
+ forge: FORGE,
1195
+ instance: thread.instance,
1196
+ thread,
1197
+ id: String(raw.id)
1198
+ },
1199
+ body: raw.body ?? "",
1200
+ author: toActor(thread.instance, raw.user),
1201
+ path: raw.path,
1202
+ line: raw.line ?? raw.original_line ?? void 0,
1203
+ side: raw.side?.toLowerCase() === "left" ? "left" : raw.side ? "right" : void 0,
1204
+ inReplyTo: raw.in_reply_to_id === null || raw.in_reply_to_id === void 0 ? void 0 : String(raw.in_reply_to_id),
1205
+ thread: reviewThread,
1206
+ createdAt: toDate(raw.created_at),
1207
+ url: raw.html_url,
1208
+ raw
1209
+ };
1210
+ }
1211
+ function toReview(thread, raw, comments) {
1212
+ return {
1213
+ ref: {
1214
+ forge: FORGE,
1215
+ instance: thread.instance,
1216
+ thread,
1217
+ id: String(raw.id)
1218
+ },
1219
+ author: toActor(thread.instance, raw.user),
1220
+ state: reviewState(raw.state),
1221
+ stateRaw: raw.state,
1222
+ body: raw.body || void 0,
1223
+ submittedAt: toDate(raw.submitted_at ?? void 0),
1224
+ comments,
1225
+ url: raw.html_url,
1226
+ raw
1227
+ };
1228
+ }
1229
+ function toWorkflowRun(repo, raw) {
1230
+ return {
1231
+ ref: {
1232
+ forge: FORGE,
1233
+ instance: repo.instance,
1234
+ repo,
1235
+ id: String(raw.id)
1236
+ },
1237
+ name: raw.name || raw.display_title || String(raw.id),
1238
+ state: checkRunState(raw.status ?? "queued", raw.conclusion),
1239
+ stateRaw: raw.status ?? "unknown",
1240
+ number: raw.run_number === void 0 ? void 0 : String(raw.run_number),
1241
+ eventRaw: raw.event,
1242
+ branch: raw.head_branch ?? void 0,
1243
+ sha: raw.head_sha,
1244
+ url: raw.html_url,
1245
+ actor: toActor(repo.instance, raw.actor),
1246
+ createdAt: toDate(raw.created_at),
1247
+ startedAt: toDate(raw.run_started_at),
1248
+ completedAt: raw.status === "completed" ? toDate(raw.updated_at) : void 0,
1249
+ raw
1250
+ };
1251
+ }
1252
+ function toWorkflowJob(run, raw) {
1253
+ return {
1254
+ ref: {
1255
+ forge: FORGE,
1256
+ instance: run.instance,
1257
+ repo: run.repo,
1258
+ id: String(raw.id),
1259
+ run
1260
+ },
1261
+ name: raw.name,
1262
+ state: checkRunState(raw.status ?? "queued", raw.conclusion),
1263
+ stateRaw: raw.status ?? "unknown",
1264
+ url: raw.html_url ?? void 0,
1265
+ startedAt: toDate(raw.started_at),
1266
+ completedAt: toDate(raw.completed_at),
1267
+ raw
1268
+ };
1269
+ }
1270
+ function toChangedFile(raw) {
1271
+ return {
1272
+ path: raw.filename,
1273
+ previousPath: raw.previous_filename,
1274
+ status: toFileStatus(raw.status),
1275
+ statusRaw: raw.status,
1276
+ additions: raw.additions,
1277
+ deletions: raw.deletions,
1278
+ patch: raw.patch,
1279
+ sha: raw.sha
1280
+ };
1281
+ }
1282
+ function toCommit(repo, raw) {
1283
+ return {
1284
+ ref: {
1285
+ forge: FORGE,
1286
+ instance: repo.instance,
1287
+ repo,
1288
+ sha: raw.sha
1289
+ },
1290
+ sha: raw.sha,
1291
+ message: raw.commit.message,
1292
+ author: {
1293
+ actor: toActor(repo.instance, raw.author),
1294
+ name: raw.commit.author?.name,
1295
+ email: raw.commit.author?.email,
1296
+ date: toDate(raw.commit.author?.date)
1297
+ },
1298
+ committer: {
1299
+ actor: toActor(repo.instance, raw.committer),
1300
+ name: raw.commit.committer?.name,
1301
+ email: raw.commit.committer?.email,
1302
+ date: toDate(raw.commit.committer?.date)
1303
+ },
1304
+ parents: raw.parents?.map((parent) => parent.sha) ?? [],
1305
+ url: raw.html_url,
1306
+ ...raw.stats ? { stats: {
1307
+ additions: raw.stats.additions ?? 0,
1308
+ deletions: raw.stats.deletions ?? 0,
1309
+ total: raw.stats.total
1310
+ } } : {},
1311
+ ...raw.files ? { files: raw.files.map(toChangedFile) } : {},
1312
+ raw
1313
+ };
1314
+ }
1315
+ /** A commit from the Git database API, which matches no accounts. */
1316
+ function toGitCommit(repo, raw) {
1317
+ return {
1318
+ ref: {
1319
+ forge: FORGE,
1320
+ instance: repo.instance,
1321
+ repo,
1322
+ sha: raw.sha
1323
+ },
1324
+ sha: raw.sha,
1325
+ message: raw.message,
1326
+ author: {
1327
+ name: raw.author?.name,
1328
+ email: raw.author?.email,
1329
+ date: toDate(raw.author?.date)
1330
+ },
1331
+ committer: {
1332
+ name: raw.committer?.name,
1333
+ email: raw.committer?.email,
1334
+ date: toDate(raw.committer?.date)
1335
+ },
1336
+ parents: raw.parents?.map((parent) => parent.sha) ?? [],
1337
+ url: raw.html_url,
1338
+ raw
1339
+ };
1340
+ }
1341
+ function toBranch(raw, defaultBranch) {
1342
+ return {
1343
+ name: raw.name,
1344
+ sha: raw.commit.sha,
1345
+ isDefault: defaultBranch === void 0 ? void 0 : raw.name === defaultBranch,
1346
+ isProtected: raw.protected,
1347
+ raw
1348
+ };
1349
+ }
1350
+ /** Merges rulesets with classic protection; `protection` is undefined when it's off or only an admin could read it. */
1351
+ function toBranchRules(branch, rules, protection, warnings) {
1352
+ const checks = /* @__PURE__ */ new Map();
1353
+ const add = (name, appId) => {
1354
+ const check = appId == null ? { name } : {
1355
+ name,
1356
+ appId: String(appId)
1357
+ };
1358
+ checks.set(`${check.appId ?? ""}\0${name}`, check);
1359
+ };
1360
+ const approvals = [];
1361
+ for (const rule of rules) {
1362
+ if (rule.type === "required_status_checks") for (const check of rule.parameters?.required_status_checks ?? []) add(check.context, check.integration_id);
1363
+ if (rule.type === "pull_request") approvals.push(rule.parameters?.required_approving_review_count ?? 0);
1364
+ }
1365
+ const classic = branch.protection?.enabled ? branch.protection.required_status_checks : void 0;
1366
+ if (classic && classic.enforcement_level !== "off") for (const check of classic.checks?.length ? classic.checks : classic.contexts?.map((context) => ({
1367
+ context,
1368
+ app_id: void 0
1369
+ })) ?? []) add(check.context, check.app_id);
1370
+ if (protection) approvals.push(protection.required_pull_request_reviews?.required_approving_review_count ?? 0);
1371
+ const known = protection || !branch.protection?.enabled;
1372
+ const pinned = new Set([...checks.values()].filter((check) => check.appId).map((check) => check.name));
1373
+ return {
1374
+ branch: branch.name,
1375
+ requiredChecks: [...checks.values()].filter((check) => check.appId || !pinned.has(check.name)),
1376
+ requiredApprovals: known ? Math.max(0, ...approvals) : approvals.length ? Math.max(...approvals) : void 0,
1377
+ ...warnings.length ? { warnings } : {},
1378
+ raw: {
1379
+ branch,
1380
+ rules,
1381
+ protection
1382
+ }
1383
+ };
1384
+ }
1385
+ function toTag(raw) {
1386
+ return {
1387
+ name: raw.name,
1388
+ sha: raw.commit.sha,
1389
+ raw
1390
+ };
1391
+ }
1392
+ const TREE_TYPES = {
1393
+ blob: "file",
1394
+ tree: "directory",
1395
+ commit: "submodule"
1396
+ };
1397
+ function toTreeEntry(raw) {
1398
+ return {
1399
+ path: raw.path,
1400
+ type: raw.mode === "120000" ? "symlink" : TREE_TYPES[raw.type ?? ""] ?? "file",
1401
+ sha: raw.sha,
1402
+ size: raw.size,
1403
+ mode: raw.mode
1404
+ };
1405
+ }
1406
+ function toWebhook(target, raw) {
1407
+ const nativeEvents = raw.events ?? [];
1408
+ return {
1409
+ ref: {
1410
+ forge: FORGE,
1411
+ instance: target.instance,
1412
+ target,
1413
+ id: String(raw.id)
1414
+ },
1415
+ url: raw.config?.url ?? "",
1416
+ events: eventKindsOf(GITHUB_NATIVE_EVENTS, nativeEvents),
1417
+ nativeEvents,
1418
+ active: raw.active ?? true,
1419
+ contentType: raw.config?.content_type === "form" ? "form" : "json",
1420
+ createdAt: toDate(raw.created_at),
1421
+ updatedAt: toDate(raw.updated_at),
1422
+ raw
1423
+ };
1424
+ }
1425
+ function toWebhookDelivery(hook, raw) {
1426
+ const status = raw.status_code ?? 0;
1427
+ return {
1428
+ ref: {
1429
+ forge: FORGE,
1430
+ instance: hook.instance,
1431
+ hook,
1432
+ id: String(raw.id),
1433
+ guid: raw.guid
1434
+ },
1435
+ event: raw.action ? `${raw.event}.${raw.action}` : raw.event ?? "",
1436
+ status,
1437
+ ok: status >= 200 && status < 300,
1438
+ deliveredAt: toDate(raw.delivered_at),
1439
+ duration: raw.duration,
1440
+ raw
1441
+ };
1442
+ }
1443
+ function graphqlUrl(baseUrl) {
1444
+ const url = new URL(baseUrl);
1445
+ if (url.host === "api.github.com") return "https://api.github.com/graphql";
1446
+ return `${url.origin}${url.pathname.replace(/\/v3\/?$/, "")}/graphql`;
1447
+ }
1448
+ /**
1449
+ * A failed GraphQL response as an error: `InsufficientScopeError` when the token lacks a scope a field needs, and
1450
+ * `RateLimitedError` for a rate limit, which GitHub reports with a `200`.
1451
+ */
1452
+ function graphqlError(operationName, errors, url, context, response) {
1453
+ const message = `GraphQL ${operationName ?? "request"} failed: ${errors?.map((error) => error.message).join("; ") || "Empty GraphQL response"}`;
1454
+ const body = JSON.stringify(errors ?? null).slice(0, 512);
1455
+ const errorContext = {
1456
+ forge: FORGE,
1457
+ instance: context.instance,
1458
+ url,
1459
+ method: "POST"
1460
+ };
1461
+ const secondary = errors?.some((error) => isSecondaryRateLimit(error.message)) ?? false;
1462
+ if (secondary || errors?.some((error) => error.type === "RATE_LIMITED")) {
1463
+ const budget = response && rateLimitOf(response);
1464
+ const resetAt = response && (rateLimitReset(response, budget) ?? (secondary ? void 0 : budget?.resetAt));
1465
+ return new RateLimitedError(message, 200, body, {
1466
+ ...errorContext,
1467
+ resetAt,
1468
+ secondary
1469
+ });
1470
+ }
1471
+ const scopeError = errors?.find((error) => error.type === "INSUFFICIENT_SCOPES");
1472
+ if (!scopeError) return new ForgeApiError(message, 200, body, errorContext);
1473
+ return new InsufficientScopeError(message, 200, body, {
1474
+ ...errorContext,
1475
+ acceptedScopes: quotedScopes(scopeError.message.match(/requires one of the following scopes: \[([^\]]*)\]/)?.[1]),
1476
+ grantedScopes: quotedScopes(scopeError.message.match(/has only been granted the: \[([^\]]*)\]/)?.[1])
1477
+ });
1478
+ }
1479
+ function quotedScopes(list) {
1480
+ return list === void 0 ? void 0 : [...list.matchAll(/'([^']+)'/g)].map((match) => match[1]);
1481
+ }
1482
+ const OPERATION_TYPES = /* @__PURE__ */ new Set([
1483
+ "query",
1484
+ "mutation",
1485
+ "subscription"
1486
+ ]);
1487
+ /** The operations a GraphQL document declares, read from its top level so that fields, variables, strings and comments don't count. */
1488
+ function graphqlOperations(document) {
1489
+ const operations = [];
1490
+ let depth = 0;
1491
+ let definitionStart = true;
1492
+ let awaitingName;
1493
+ for (const [token] of document.matchAll(/"""(?:\\"""|[\s\S])*?"""|"(?:\\.|[^"\\\n\r])*"|#[^\n\r]*|[{}()]|[$@]?[_a-z]\w*/gi)) {
1494
+ if (token[0] === "\"" || token[0] === "#") continue;
1495
+ if (token === "{" || token === "(") {
1496
+ if (depth === 0 && definitionStart && token === "{") operations.push({ type: "query" });
1497
+ depth++;
1498
+ definitionStart = false;
1499
+ awaitingName = void 0;
1500
+ } else if (token === "}" || token === ")") {
1501
+ depth--;
1502
+ definitionStart = depth === 0 && token === "}";
1503
+ } else if (depth === 0) {
1504
+ if (awaitingName && /^[_a-z]/i.test(token)) awaitingName.name = token;
1505
+ awaitingName = definitionStart && OPERATION_TYPES.has(token) ? { type: token } : void 0;
1506
+ if (awaitingName) operations.push(awaitingName);
1507
+ definitionStart = false;
1508
+ }
1509
+ }
1510
+ return operations;
1511
+ }
1512
+ function createGraphQLClient(fetcher, url, context) {
1513
+ return async (document, variables, options) => {
1514
+ const query = typeof document === "string" ? (await import("./graphql-BDhuP5jN-BSpB8lWf.js"))[document] : document.query;
1515
+ const operationName = graphqlOperations(query)[0]?.name;
1516
+ const { data, response } = await fetcher.json(url, {
1517
+ method: "POST",
1518
+ json: {
1519
+ query,
1520
+ variables,
1521
+ operationName
1522
+ },
1523
+ signal: options?.signal
1524
+ });
1525
+ if (data.errors?.length || !data.data) throw graphqlError(operationName, data.errors, url, context, response);
1526
+ return data.data;
1527
+ };
1528
+ }
1529
+ const SIGNATURE_HEADER = "x-hub-signature-256";
1530
+ function verifyGitHubSignature(delivery, secret) {
1531
+ return verifyHmacSignature(delivery, secret, {
1532
+ header: SIGNATURE_HEADER,
1533
+ prefix: "sha256="
1534
+ });
1535
+ }
1536
+ const githubWebhooks = ({ options, instance }) => ({
1537
+ events: GITHUB_WEBHOOK_EVENTS,
1538
+ verify: (delivery) => verifyGitHubSignature(delivery, options.webhookSecret),
1539
+ translate: async (delivery) => (await import("./events-DjRw3KSr-C72gY7Vu.js")).translateGitHubWebhook(instance, delivery)
1540
+ });
1541
+ const DISCUSSION_CLOSE_REASONS = {
1542
+ completed: "resolved",
1543
+ duplicate: "duplicate"
1544
+ };
1545
+ const COLLABORATOR_PERMISSIONS = {
1546
+ read: "pull",
1547
+ write: "push"
1548
+ };
1549
+ /** GitHub Enterprise Server versions that support marking a notification done. */
1550
+ const GHES_MARK_DONE = "3.13";
1551
+ /** GitHub Enterprise Server versions with the Dependabot alerts REST API. */
1552
+ const GHES_DEPENDABOT_ALERTS = "3.8";
1553
+ const GRAPHQL_BATCH = 20;
1554
+ const LOCK_REASONS = {
1555
+ off_topic: "off-topic",
1556
+ too_heated: "too heated",
1557
+ resolved: "resolved",
1558
+ spam: "spam"
1559
+ };
1560
+ const REVIEW_CONTEXT_TTL = 3e5;
1561
+ const POLL_DELAYS = [
1562
+ 500,
1563
+ 1e3,
1564
+ 2e3
1565
+ ];
1566
+ const CONTRIBUTOR_STATS_DELAYS = [
1567
+ 500,
1568
+ 1e3,
1569
+ 2e3,
1570
+ 4e3,
1571
+ 8e3
1572
+ ];
1573
+ const ISSUE_LIKE = {
1574
+ issue: true,
1575
+ pull_request: true,
1576
+ discussion: true
1577
+ };
1578
+ function repoPath(repo) {
1579
+ return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
1580
+ }
1581
+ function branchPath(branch) {
1582
+ return branch.split("/").map(encodeURIComponent).join("/");
1583
+ }
1584
+ const ZERO_OID = "0".repeat(40);
1585
+ /**
1586
+ * GitHub's refusal to move a branch that is no longer at the commit a write built on, as a 409 `BranchMovedError`,
1587
+ * and to delete a file that does not exist, as a 404 `NotFoundError`, whatever the status of the response.
1588
+ */
1589
+ function commitError(error) {
1590
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError) return error;
1591
+ const text = `${error.message} ${error.body}`;
1592
+ const context = {
1593
+ forge: error.forge,
1594
+ instance: error.instance,
1595
+ url: error.url,
1596
+ method: error.method
1597
+ };
1598
+ if (/Expected branch to point to|not a fast[- ]forward/i.test(text)) return new BranchMovedError("The branch no longer points at the commit the change was made on", 409, error.body, context, { cause: error });
1599
+ if (/requested for deletion which does not exist/i.test(text)) return new NotFoundError("A file to delete does not exist", 404, error.body, context, { cause: error });
1600
+ return error;
1601
+ }
1602
+ /** GitHub's `422` for a head that moved since `expected_head_sha`, as `BranchMovedError`, and for a conflict, as `MergeConflictError`. */
1603
+ function updateBranchError(error) {
1604
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError || error.status !== 422) return error;
1605
+ const context = {
1606
+ forge: error.forge,
1607
+ instance: error.instance,
1608
+ url: error.url,
1609
+ method: error.method
1610
+ };
1611
+ if (/expected head sha/i.test(error.body)) return new BranchMovedError("The head branch no longer points at the expected sha", error.status, error.body, context, { cause: error });
1612
+ if (/conflict/i.test(error.body)) return new MergeConflictError("The head branch conflicts with its base", error.status, error.body, context, { cause: error });
1613
+ return error;
1614
+ }
1615
+ function threadPath(ref) {
1616
+ switch (ref.kind) {
1617
+ case "pull_request": return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1618
+ default: return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1619
+ }
1620
+ }
1621
+ function installationId(installation) {
1622
+ return typeof installation === "string" ? installation : installation.id;
1623
+ }
1624
+ /**
1625
+ * Free text as legacy search reads it: advanced search parses parentheses and
1626
+ * an unclosed quote as syntax, so those are dropped outside quoted phrases.
1627
+ */
1628
+ function advancedFreeText(text) {
1629
+ const parts = text.split("\"");
1630
+ if (parts.length % 2 === 0) {
1631
+ const unclosed = parts.pop();
1632
+ parts.push(`${parts.pop()} ${unclosed}`);
1633
+ }
1634
+ return parts.map((part, index) => index % 2 ? part : part.replace(/[()\s]+/g, " ")).join("\"").trim();
1635
+ }
1636
+ function setupGitHub({ options, baseUrl, instance, origin: context, fetcher, createFetcher, derive, state: credentials }) {
1637
+ const list = createListing(fetcher, "per_page");
1638
+ const auth = options.auth ?? { type: "anonymous" };
1639
+ /** GitHub GraphQL needs a credential, so anonymous providers stay on REST. */
1640
+ const anonymous = auth.type === "anonymous";
1641
+ /** An app without an installation reaches only the `/app` endpoints. */
1642
+ const appItself = auth.type === "app" && auth.installationId === void 0;
1643
+ const tokenKind = auth.type === "token" ? tokenKindOf(auth) : void 0;
1644
+ /** An installation, whether from app credentials or its token, acts as no account. */
1645
+ const installation = auth.type === "app" || tokenKind === "installation";
1646
+ /** GitHub serves notifications only to classic personal access tokens and OAuth app tokens. */
1647
+ const notificationsAuth = auth.type === "token" && (tokenKind === void 0 || tokenKind === "classic");
1648
+ const host = hostOf(baseUrl);
1649
+ /** GitHub Enterprise Server; `ghe.com` data residency hosts follow github.com. */
1650
+ const enterprise = host !== "api.github.com" && !isGheCom(host);
1651
+ const graphql = createGraphQLClient(fetcher, graphqlUrl(baseUrl), { instance });
1652
+ /**
1653
+ * Discussion notification subjects carry no URL. The repo's most recently
1654
+ * updated discussions are listed and matched on an exact, unique title.
1655
+ */
1656
+ async function resolveDiscussionNumbers(items) {
1657
+ const pending = items.filter((item) => item.subject.type === "thread" && item.subject.thread.kind === "discussion" && !item.subject.thread.number);
1658
+ if (!pending.length) return [];
1659
+ const repos = [...new Map(pending.map((item) => {
1660
+ const repo = item.subject.thread.repo;
1661
+ return [`${repo.owner}/${repo.name}`, repo];
1662
+ })).values()];
1663
+ let result;
1664
+ try {
1665
+ const { query, variables } = (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).recentDiscussionsQuery(repos);
1666
+ result = await graphql({ query }, variables);
1667
+ } catch (error) {
1668
+ if (error instanceof InsufficientScopeError || error instanceof ForgeApiError && error.status === 200) return [toWarning("discussion_unresolved", error)];
1669
+ throw error;
1670
+ }
1671
+ for (const item of pending) {
1672
+ const thread = item.subject.thread;
1673
+ const index = repos.findIndex((repo) => repo.owner === thread.repo.owner && repo.name === thread.repo.name);
1674
+ const matches = (result[`r${index}`]?.discussions.nodes ?? []).filter((node) => node.title === item.title);
1675
+ if (matches.length === 1) item.subject = {
1676
+ type: "thread",
1677
+ thread: {
1678
+ ...thread,
1679
+ number: String(matches[0].number),
1680
+ externalId: matches[0].id
1681
+ }
1682
+ };
1683
+ }
1684
+ return [];
1685
+ }
1686
+ /** When each polled path may be read again, from GitHub's `X-Poll-Interval`. */
1687
+ const nextPoll = /* @__PURE__ */ new Map();
1688
+ function throttledPage(path, listOptions, subject) {
1689
+ const at = nextPoll.get(path) ?? 0;
1690
+ const wait = at - Date.now();
1691
+ if (!isFirstPage(listOptions.cursor) || listOptions.force || wait <= 0) return;
1692
+ const warning = {
1693
+ code: "feed_throttled",
1694
+ message: `GitHub asked to wait ${Math.ceil(wait / 1e3)}s more before reading ${subject} again; no request was sent. Read it later, or pass force: true`
1695
+ };
1696
+ return {
1697
+ items: [],
1698
+ throttled: true,
1699
+ nextPollAt: new Date(at),
1700
+ warnings: [warning],
1701
+ ...listOptions.cursor?.etag ? { etag: listOptions.cursor.etag } : {}
1702
+ };
1703
+ }
1704
+ function recordPoll(path, cursor, response) {
1705
+ const interval = Number(response.headers.get("x-poll-interval"));
1706
+ if (!isFirstPage(cursor) || !(interval > 0)) return {};
1707
+ const at = Date.now() + interval * 1e3;
1708
+ nextPoll.set(path, at);
1709
+ return { nextPollAt: new Date(at) };
1710
+ }
1711
+ async function notificationPage(listOptions = {}) {
1712
+ const throttled = throttledPage("/notifications", listOptions, "notifications");
1713
+ if (throttled) return throttled;
1714
+ const result = await fetcher.json(listOptions.cursor?.nextUrl ?? "/notifications", {
1715
+ query: listOptions.cursor?.nextUrl ? void 0 : {
1716
+ all: listOptions.all ?? false,
1717
+ since: listOptions.since?.toISOString(),
1718
+ per_page: listOptions.perPage
1719
+ },
1720
+ etag: listOptions.cursor?.nextUrl ? void 0 : listOptions.cursor?.etag,
1721
+ signal: listOptions.signal
1722
+ });
1723
+ const items = (result.data ?? []).map((raw) => toNotification(instance, raw));
1724
+ const warnings = await resolveDiscussionNumbers(items);
1725
+ const etag = listOptions.cursor?.nextUrl ? void 0 : result.cursor?.etag ?? listOptions.cursor?.etag;
1726
+ return {
1727
+ items,
1728
+ cursor: result.cursor?.nextUrl ? result.cursor : void 0,
1729
+ ...etag ? { etag } : {},
1730
+ notModified: result.notModified,
1731
+ warnings: warnings.length ? warnings : void 0,
1732
+ ...recordPoll("/notifications", listOptions.cursor, result.response),
1733
+ ...rateLimitPart(result.response)
1734
+ };
1735
+ }
1736
+ async function discussionId(ref, options) {
1737
+ if (ref.externalId) return ref.externalId;
1738
+ return (await getDiscussion(ref, options)).ref.externalId;
1739
+ }
1740
+ async function getDiscussion(ref, options) {
1741
+ const discussion = (await graphql("DISCUSSION_THREAD", {
1742
+ owner: ref.repo.owner,
1743
+ name: ref.repo.name,
1744
+ number: Number(ref.number)
1745
+ }, options)).repository?.discussion;
1746
+ if (!discussion) throw new NotFoundError(`Discussion ${ref.number} not found`, 404, "", context);
1747
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionThread(ref, discussion);
1748
+ }
1749
+ async function discussionCommentPage(ref, listOptions) {
1750
+ const comments = (await graphql("DISCUSSION_COMMENTS", {
1751
+ owner: ref.repo.owner,
1752
+ name: ref.repo.name,
1753
+ number: Number(ref.number),
1754
+ after: listOptions.cursor?.token ?? null
1755
+ }, listOptions)).repository?.discussion?.comments;
1756
+ return {
1757
+ items: (comments?.nodes ?? []).flatMap((comment) => [{
1758
+ comment,
1759
+ isReply: false
1760
+ }, ...(comment.replies?.nodes ?? []).map((reply) => ({
1761
+ comment: reply,
1762
+ isReply: true
1763
+ }))]),
1764
+ cursor: comments?.pageInfo.hasNextPage && comments.pageInfo.endCursor ? { token: comments.pageInfo.endCursor } : void 0
1765
+ };
1766
+ }
1767
+ async function get(thread, options) {
1768
+ const ref = requireThread(thread, context);
1769
+ if (ref.kind === "discussion") return getDiscussion(ref, options);
1770
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1771
+ const result = toThread(ref, data);
1772
+ if (ref.kind === "pull_request" && data.head?.sha) try {
1773
+ const checks = await headChecks(ref.repo, data.head.sha, options?.signal);
1774
+ result.checks = summariseChecks(checks.items.map((check) => check.state), data.html_url ? `${data.html_url}/checks` : void 0);
1775
+ if (checks.warnings?.length) result.warnings = [...result.warnings ?? [], ...checks.warnings];
1776
+ } catch (error) {
1777
+ if (!degradesToWarning(error)) throw error;
1778
+ result.warnings = [...result.warnings ?? [], toWarning("checks_unreadable", error, ref.number)];
1779
+ }
1780
+ return result;
1781
+ }
1782
+ async function headChecks(repo, sha, signal) {
1783
+ let checkRunTotal;
1784
+ const [runs, status] = await Promise.allSettled([Array.fromAsync(fetcher.items(`${repoPath(repo)}/commits/${sha}/check-runs`, {
1785
+ query: { per_page: 100 },
1786
+ select: (body, next) => {
1787
+ const { check_runs, total_count } = body;
1788
+ checkRunTotal = total_count;
1789
+ return {
1790
+ items: check_runs,
1791
+ next
1792
+ };
1793
+ },
1794
+ signal
1795
+ }), (raw) => toCheckRun(repo, raw)), Array.fromAsync(fetcher.items(`${repoPath(repo)}/commits/${sha}/status`, {
1796
+ query: { per_page: 100 },
1797
+ select: (body, next) => ({
1798
+ items: body.statuses,
1799
+ next
1800
+ }),
1801
+ signal
1802
+ }), (raw) => toStatusCheck(repo, raw))]);
1803
+ if (signal?.aborted) throw signal.reason;
1804
+ if (runs.status === "rejected" && status.status === "rejected") throw runs.reason;
1805
+ for (const result of [runs, status]) if (result.status === "rejected" && !degradesToWarning(result.reason)) throw result.reason;
1806
+ const statuses = status.status === "fulfilled" ? status.value : [];
1807
+ const total = runs.status === "fulfilled" && status.status === "fulfilled" && checkRunTotal !== void 0 ? checkRunTotal + statuses.length : void 0;
1808
+ return {
1809
+ items: [...runs.status === "fulfilled" ? runs.value : [], ...statuses],
1810
+ ...total !== void 0 ? { total } : {},
1811
+ warnings: [...runs.status === "rejected" ? [toWarning("checks_unreadable", runs.reason, "check-runs")] : [], ...status.status === "rejected" ? [toWarning("checks_unreadable", status.reason, "statuses")] : []]
1812
+ };
1813
+ }
1814
+ async function getMany(refs, options) {
1815
+ if (anonymous) return getManyConcurrently(refs, (ref, getOptions) => ref.kind === "discussion" ? Promise.reject(new UnsupportedOperationError("github does not read discussions without credentials", context)) : get(ref, getOptions), options);
1816
+ const results = Array.from({ length: refs.length });
1817
+ const batchable = [];
1818
+ for (const [index, ref] of refs.entries()) if (!isResolvedThread(ref)) results[index] = {
1819
+ ok: false,
1820
+ ref,
1821
+ warning: toWarning("thread_unresolved", /* @__PURE__ */ new Error("Thread ref has no number"), ref.number)
1822
+ };
1823
+ else batchable.push({
1824
+ index,
1825
+ ref
1826
+ });
1827
+ if (!batchable.length) return results;
1828
+ const g = await import("./graphql-BDhuP5jN-BSpB8lWf.js");
1829
+ for (let start = 0; start < batchable.length; start += GRAPHQL_BATCH) {
1830
+ const chunk = batchable.slice(start, start + GRAPHQL_BATCH);
1831
+ const { query, variables } = g.threadsBatchQuery(chunk.map((item) => item.ref));
1832
+ const url = graphqlUrl(baseUrl);
1833
+ const { data, response } = await fetcher.json(url, {
1834
+ method: "POST",
1835
+ json: {
1836
+ query,
1837
+ variables,
1838
+ operationName: "ThreadsBatch"
1839
+ },
1840
+ signal: options?.signal
1841
+ });
1842
+ const failure = data.data ? void 0 : graphqlError("ThreadsBatch", data.errors, url, { instance }, response);
1843
+ if (failure instanceof RateLimitedError) throw failure;
1844
+ chunk.forEach(({ index, ref }, offset) => {
1845
+ const node = data.data?.[`t${offset}`];
1846
+ const discussion = ref.kind === "discussion" ? node?.discussion : void 0;
1847
+ const issueOrPullRequest = ref.kind === "discussion" ? void 0 : node?.issueOrPullRequest;
1848
+ if (failure) {
1849
+ results[index] = {
1850
+ ok: false,
1851
+ ref,
1852
+ warning: toWarning(failure instanceof InsufficientScopeError ? "insufficient_scope" : "thread_unreadable", failure, ref.number)
1853
+ };
1854
+ return;
1855
+ }
1856
+ if (!discussion && !issueOrPullRequest) {
1857
+ const error = data.errors?.find((error) => error.path?.[0] === `t${offset}`);
1858
+ if (error?.type === "INSUFFICIENT_SCOPES") {
1859
+ results[index] = {
1860
+ ok: false,
1861
+ ref,
1862
+ warning: toWarning("insufficient_scope", graphqlError("ThreadsBatch", [error], url, { instance }), ref.number)
1863
+ };
1864
+ return;
1865
+ }
1866
+ results[index] = {
1867
+ ok: false,
1868
+ ref,
1869
+ warning: {
1870
+ code: "thread_unreadable",
1871
+ message: error?.message ?? "Not found",
1872
+ subject: ref.number
1873
+ }
1874
+ };
1875
+ return;
1876
+ }
1877
+ results[index] = {
1878
+ ok: true,
1879
+ ref,
1880
+ thread: discussion ? g.toDiscussionThread(ref, discussion) : g.toGraphQLThread(ref, issueOrPullRequest)
1881
+ };
1882
+ });
1883
+ }
1884
+ return results;
1885
+ }
1886
+ async function listPage(repo, query = {}) {
1887
+ const state = query.state ?? "open";
1888
+ const direction = query.direction ?? "desc";
1889
+ const createdAfter = query.createdAfter?.getTime();
1890
+ if (query.kind === "discussion") {
1891
+ if (query.assignee) return {
1892
+ items: [],
1893
+ warnings: [{
1894
+ code: "filter_unsupported",
1895
+ message: "Discussions have no assignees"
1896
+ }]
1897
+ };
1898
+ if (query.milestone && query.milestone !== "none") return {
1899
+ items: [],
1900
+ warnings: [{
1901
+ code: "filter_unsupported",
1902
+ message: "Discussions have no milestones"
1903
+ }]
1904
+ };
1905
+ const warnings = isFirstPage(query.cursor) && query.sort === "comments" ? [{
1906
+ code: "sort_unsupported",
1907
+ message: "Discussions cannot be sorted by comments; sorted by update time"
1908
+ }] : [];
1909
+ for (const filter of ["involves", "mentions"]) if (isFirstPage(query.cursor) && query[filter]) warnings.push({
1910
+ code: "filter_unsupported",
1911
+ message: `GitHub lists discussions without a ${filter} filter; it was ignored`
1912
+ });
1913
+ const data = await graphql("DISCUSSIONS_LIST", {
1914
+ owner: repo.owner,
1915
+ name: repo.name,
1916
+ first: Math.min(query.perPage ?? 50, 100),
1917
+ after: query.cursor?.token ?? null,
1918
+ field: query.sort === "created" || !query.sort ? "CREATED_AT" : "UPDATED_AT",
1919
+ direction: direction.toUpperCase()
1920
+ }, query);
1921
+ const { toDiscussionThread } = await import("./graphql-BDhuP5jN-BSpB8lWf.js");
1922
+ const discussions = data.repository?.discussions;
1923
+ return {
1924
+ items: (discussions?.nodes ?? []).map((node) => toDiscussionThread({
1925
+ forge: FORGE,
1926
+ instance,
1927
+ repo,
1928
+ kind: "discussion",
1929
+ number: String(node.number)
1930
+ }, node)).filter((thread) => (state === "all" || thread.state === state) && (!query.author || thread.author?.login === query.author) && (!query.labels?.length || query.labels.every((label) => thread.labels.some((item) => item.name === label))) && (!query.since || (thread.updatedAt?.getTime() ?? 0) >= query.since.getTime()) && (createdAfter === void 0 || (thread.createdAt?.getTime() ?? 0) >= createdAfter)),
1931
+ cursor: discussions?.pageInfo.hasNextPage && discussions.pageInfo.endCursor ? { token: discussions.pageInfo.endCursor } : void 0,
1932
+ ...warnings.length ? { warnings } : {}
1933
+ };
1934
+ }
1935
+ if (state === "merged") {
1936
+ const page = await searchThreadsPage({
1937
+ repo,
1938
+ kind: "pull_request",
1939
+ labels: query.labels,
1940
+ author: query.author,
1941
+ assignee: query.assignee,
1942
+ involves: query.involves,
1943
+ since: query.since,
1944
+ queryRaw: [
1945
+ "is:merged",
1946
+ query.createdAfter && `created:>=${query.createdAfter.toISOString()}`,
1947
+ query.mentions && `mentions:${query.mentions}`,
1948
+ query.milestone && (query.milestone === "none" ? "no:milestone" : `milestone:"${query.milestone.replaceAll("\"", "")}"`)
1949
+ ].filter(Boolean).join(" "),
1950
+ sort: query.sort ?? "created",
1951
+ direction,
1952
+ perPage: query.perPage,
1953
+ cursor: query.cursor,
1954
+ signal: query.signal
1955
+ });
1956
+ await withPullChecks(page, query);
1957
+ return page;
1958
+ }
1959
+ const milestone = query.milestone === void 0 || query.milestone === "none" || !isFirstPage(query.cursor) ? query.milestone : await milestoneNumber(repo, query.milestone, query);
1960
+ if (milestone === null) return { items: [] };
1961
+ const warnings = isFirstPage(query.cursor) && query.involves ? [{
1962
+ code: "filter_unsupported",
1963
+ message: "GitHub lists issues and pull requests without an involves filter; it was ignored. search.threads() has one"
1964
+ }] : [];
1965
+ const pullsOnly = query.kind === "pull_request" && !query.labels?.length && !query.author && !query.assignee && !query.mentions && !query.milestone && !query.since && query.sort !== "comments";
1966
+ const result = await fetcher.page(`${repoPath(repo)}/${pullsOnly ? "pulls" : "issues"}`, {
1967
+ query: {
1968
+ state,
1969
+ labels: query.labels?.join(","),
1970
+ creator: query.author,
1971
+ assignee: query.assignee,
1972
+ mentioned: query.mentions,
1973
+ milestone,
1974
+ since: query.since?.toISOString(),
1975
+ sort: query.sort ?? "created",
1976
+ direction,
1977
+ per_page: query.perPage
1978
+ },
1979
+ cursor: query.cursor,
1980
+ signal: query.signal
1981
+ });
1982
+ const older = (raw) => createdAfter !== void 0 && (Date.parse(raw.created_at ?? "") || 0) < createdAfter;
1983
+ const page = toPage(result, (raw) => {
1984
+ const isPull = Boolean(raw.pull_request || raw.head);
1985
+ if (query.kind === "issue" && isPull || query.kind === "pull_request" && !isPull || older(raw)) return;
1986
+ return toThread({
1987
+ forge: FORGE,
1988
+ instance,
1989
+ repo,
1990
+ kind: isPull ? "pull_request" : "issue",
1991
+ number: String(raw.number)
1992
+ }, raw);
1993
+ });
1994
+ const ordered = (query.sort ?? "created") === "created" && direction === "desc";
1995
+ await withPullChecks(page, query);
1996
+ const listed = warnings.length ? {
1997
+ ...page,
1998
+ warnings: [...warnings, ...page.warnings ?? []]
1999
+ } : page;
2000
+ return ordered && (result.data ?? []).some(older) ? {
2001
+ ...listed,
2002
+ cursor: void 0
2003
+ } : listed;
2004
+ }
2005
+ /** The number of the milestone titled `title`, or `null` when the repository has none by that title. */
2006
+ async function milestoneNumber(repo, title, options) {
2007
+ for await (const milestone of iteratePages((page) => milestonesPage(repo, page), {
2008
+ state: "all",
2009
+ signal: options.signal
2010
+ })) if (milestone.title === title) return milestone.id;
2011
+ return null;
2012
+ }
2013
+ /** Fills `checks`, and a missing `commentCount`, on every pull in the page with one batched read. */
2014
+ async function withPullChecks(page, options) {
2015
+ const pulls = page.items.filter((thread) => thread.kind === "pull_request");
2016
+ if (!pulls.length || anonymous) return;
2017
+ try {
2018
+ const results = await getMany(pulls.map((thread) => thread.ref), options);
2019
+ for (const [index, result] of results.entries()) if (result.ok) {
2020
+ pulls[index].checks = result.thread.checks ?? pulls[index].checks;
2021
+ pulls[index].commentCount ??= result.thread.commentCount;
2022
+ pulls[index].mergedBy ??= result.thread.mergedBy;
2023
+ }
2024
+ } catch (error) {
2025
+ if (!degradesToWarning(error)) throw error;
2026
+ page.warnings = [...page.warnings ?? [], toWarning("checks_unreadable", error)];
2027
+ }
2028
+ }
2029
+ async function commentsPage(thread, listOptions = {}) {
2030
+ const ref = requireThread(thread, context);
2031
+ if (ref.kind === "discussion") {
2032
+ const [page, { toDiscussionComment }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
2033
+ return {
2034
+ ...page,
2035
+ items: page.items.map(({ comment }) => toDiscussionComment(ref, comment))
2036
+ };
2037
+ }
2038
+ return list(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/comments`, listOptions, (raw) => toComment(ref, raw), { query: { since: listOptions.since?.toISOString() } });
2039
+ }
2040
+ /** Discussion comment ids are node ids already; other comments are read for theirs. */
2041
+ async function commentNodeId(ref, options) {
2042
+ if ("thread" in ref && ref.thread.kind === "discussion") return ref.id;
2043
+ const { data } = await fetcher.json("commit" in ref ? commitCommentPath(ref) : commentPath(ref), { signal: options?.signal });
2044
+ if (!data.node_id) throw new NotFoundError(`Comment ${ref.id} has no node id`, 404, "", context);
2045
+ return data.node_id;
2046
+ }
2047
+ function commentPath(ref) {
2048
+ return `${repoPath(ref.thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`;
2049
+ }
2050
+ function commitCommentPath(ref) {
2051
+ return `${repoPath(ref.commit.repo)}/comments/${encodeURIComponent(ref.id)}`;
2052
+ }
2053
+ async function setState(thread, state, options_ = {}) {
2054
+ const ref = requireThread(thread, context);
2055
+ if (ref.kind === "discussion") {
2056
+ const reason = options_.reasonRaw ?? (options_.reason && DISCUSSION_CLOSE_REASONS[options_.reason]);
2057
+ if (state === "closed" && options_.reason && !reason) throw new UnsupportedOperationError(`GitHub discussions have no ${options_.reason} close reason; pass reasonRaw: 'outdated'`, context);
2058
+ const id = await discussionId(ref, options_);
2059
+ const data = state === "closed" ? (await graphql("CLOSE_DISCUSSION", {
2060
+ id,
2061
+ reason: reason?.toUpperCase() ?? null
2062
+ }, options_)).closeDiscussion : (await graphql("REOPEN_DISCUSSION", { id }, options_)).reopenDiscussion;
2063
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionThread(ref, data.discussion);
2064
+ }
2065
+ const reason = options_.reasonRaw ?? options_.reason;
2066
+ const { data } = await fetcher.json(threadPath(ref), {
2067
+ method: "PATCH",
2068
+ json: ref.kind === "issue" && state === "closed" && reason ? {
2069
+ state,
2070
+ state_reason: reason
2071
+ } : { state },
2072
+ signal: options_.signal
2073
+ });
2074
+ return toThread(ref, data);
2075
+ }
2076
+ async function merge(thread, options_ = {}) {
2077
+ const ref = requireThread(thread, context);
2078
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests can be merged", context);
2079
+ if (options_.whenChecksPass) throw new UnsupportedOperationError("GitHub auto-merge is not available through the REST API", context);
2080
+ if (options_.method === "rebase_merge" || options_.method === "fast_forward_only") throw new UnsupportedOperationError(`GitHub does not support the ${options_.method} merge method`, context);
2081
+ let method = options_.method;
2082
+ if (!method) {
2083
+ const { data: repo } = await fetcher.json(repoPath(ref.repo), { signal: options_.signal });
2084
+ method = soleMergeMethod({
2085
+ merge: repo.allow_merge_commit,
2086
+ squash: repo.allow_squash_merge,
2087
+ rebase: repo.allow_rebase_merge
2088
+ }, context);
2089
+ }
2090
+ return directMerge(ref, method, options_);
2091
+ }
2092
+ async function directMerge(ref, method, mergeOptions) {
2093
+ const path = `${threadPath(ref)}/merge`;
2094
+ const { sha, title, message } = mergeOptions;
2095
+ const body = {
2096
+ merge_method: method,
2097
+ sha,
2098
+ commit_title: title,
2099
+ commit_message: message
2100
+ };
2101
+ const timeout = options.timeout ?? 3e4;
2102
+ const budget = new AbortController();
2103
+ const signal = mergeOptions.signal ? anySignal([budget.signal, mergeOptions.signal]) : budget.signal;
2104
+ const timer = setTimeout(() => budget.abort(new DOMException("Merge timed out", "TimeoutError")), timeout);
2105
+ const timedOut = (url, requestMethod, cause, uuid) => new ForgeTimeoutError(uuid ? `Merge request ${uuid} for pull request ${ref.number} was still pending after ${timeout}ms; GitHub may still complete it` : `Merge of pull request ${ref.number} got no response within ${timeout}ms; GitHub may still complete it`, timeout, {
2106
+ ...context,
2107
+ url,
2108
+ method: requestMethod
2109
+ }, { cause });
2110
+ let url = fetcher.resolve(`${path}-async`);
2111
+ let requestMethod = "PUT";
2112
+ let uuid;
2113
+ try {
2114
+ let state;
2115
+ let status;
2116
+ try {
2117
+ const { data, response } = await fetcher.json(`${path}-async`, {
2118
+ method: "PUT",
2119
+ json: {
2120
+ ...body,
2121
+ merge_action: "direct_merge"
2122
+ },
2123
+ signal
2124
+ });
2125
+ state = data;
2126
+ status = response.status;
2127
+ } catch (error) {
2128
+ if (budget.signal.aborted) throw error;
2129
+ if (enterprise && error instanceof NotFoundError) {
2130
+ url = fetcher.resolve(path);
2131
+ const { data } = await fetcher.json(path, {
2132
+ method: "PUT",
2133
+ json: body,
2134
+ mapError: toMergeError,
2135
+ signal
2136
+ });
2137
+ return {
2138
+ status: "merged",
2139
+ sha: data?.sha,
2140
+ raw: data
2141
+ };
2142
+ }
2143
+ state = pendingMergeFrom(error, method, sha, title, message);
2144
+ status = 409;
2145
+ }
2146
+ for (let attempt = 0; state.status === "pending"; attempt++) {
2147
+ uuid = state.details?.uuid;
2148
+ if (!uuid) throw new ForgeApiError("GitHub reported a pending merge without a request id", status, JSON.stringify(state).slice(0, 512), {
2149
+ ...context,
2150
+ url,
2151
+ method: requestMethod
2152
+ });
2153
+ const poll = `${path}-async/${encodeURIComponent(uuid)}`;
2154
+ url = fetcher.resolve(poll);
2155
+ requestMethod = "GET";
2156
+ await sleep(POLL_DELAYS[Math.min(attempt, POLL_DELAYS.length - 1)], signal);
2157
+ const { data, response } = await fetcher.json(poll, { signal });
2158
+ state = data;
2159
+ status = response.status;
2160
+ }
2161
+ const errorContext = {
2162
+ ...context,
2163
+ url,
2164
+ method: requestMethod
2165
+ };
2166
+ const excerpt = JSON.stringify(state).slice(0, 512);
2167
+ switch (state.status) {
2168
+ case "merged": return {
2169
+ status: "merged",
2170
+ sha: state.details?.sha,
2171
+ raw: state
2172
+ };
2173
+ case "enqueued": throw new MergeBlockedError("Pull request was added to a merge queue and has not merged", status, excerpt, errorContext);
2174
+ case "failed": throw new MergeBlockedError(state.details?.message || "GitHub could not merge the pull request", status, excerpt, errorContext);
2175
+ default: throw new ForgeApiError(`GitHub reported an unknown merge status ${JSON.stringify(state.status)}`, status, excerpt, errorContext);
2176
+ }
2177
+ } catch (error) {
2178
+ throw budget.signal.aborted ? timedOut(url, requestMethod, error, uuid) : error;
2179
+ } finally {
2180
+ clearTimeout(timer);
2181
+ }
2182
+ }
2183
+ function pendingMergeFrom(error, method, sha, title, message) {
2184
+ if (!(error instanceof ForgeApiError)) throw error;
2185
+ if (isPlainApiError(error, 400)) throw new MergeBlockedError("Pull request cannot be merged in its current state", 400, error.body, {
2186
+ ...context,
2187
+ url: error.url,
2188
+ method: error.method
2189
+ }, { cause: error });
2190
+ if (!isPlainApiError(error, 409)) throw toMergeError(error);
2191
+ let pending;
2192
+ try {
2193
+ pending = JSON.parse(error.body);
2194
+ } catch {}
2195
+ const details = pending?.details;
2196
+ if (!details?.uuid) throw toMergeError(error);
2197
+ if (title !== void 0 || message !== void 0 || details.merge_action !== "direct_merge" || details.merge_method !== method || details.bypass_rules || sha !== void 0 && details.expected_head_sha !== sha) throw new MergeBlockedError("Another merge request is pending whose options do not match or cannot be verified", 409, error.body, {
2198
+ ...context,
2199
+ url: error.url,
2200
+ method: error.method
2201
+ }, { cause: error });
2202
+ return {
2203
+ status: "pending",
2204
+ details
2205
+ };
2206
+ }
2207
+ function isPlainApiError(error, status) {
2208
+ return error instanceof ForgeApiError && error.constructor === ForgeApiError && error.status === status;
2209
+ }
2210
+ /** A merge goes through REST, which takes no method; a rebase goes through GraphQL, after a read for the pull request's node id. */
2211
+ async function updateBranch(thread, updateOptions = {}) {
2212
+ const ref = requirePull(thread, "updated");
2213
+ const { sha, signal } = updateOptions;
2214
+ if (updateOptions.method === "rebase") {
2215
+ const { data: pull } = await fetcher.json(threadPath(ref), { signal });
2216
+ if (sha !== void 0 && pull.head?.sha !== sha) throw new BranchMovedError(`Head branch of pull request ${ref.number} is at ${pull.head?.sha}, not ${sha}`, 409, "", context);
2217
+ return {
2218
+ status: "queued",
2219
+ raw: (await graphql("UPDATE_PULL_REQUEST_BRANCH", {
2220
+ id: pull.node_id,
2221
+ sha: sha ?? null,
2222
+ method: "REBASE"
2223
+ }, updateOptions)).updatePullRequestBranch
2224
+ };
2225
+ }
2226
+ const { data } = await fetcher.json(`${threadPath(ref)}/update-branch`, {
2227
+ method: "PUT",
2228
+ json: sha === void 0 ? {} : { expected_head_sha: sha },
2229
+ mapError: updateBranchError,
2230
+ signal
2231
+ });
2232
+ return {
2233
+ status: "queued",
2234
+ raw: data
2235
+ };
2236
+ }
2237
+ const REVIEW_EVENTS = {
2238
+ approve: "APPROVE",
2239
+ request_changes: "REQUEST_CHANGES",
2240
+ comment: "COMMENT"
2241
+ };
2242
+ function requirePull(thread, action) {
2243
+ const ref = requireThread(thread, context);
2244
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only pull requests can be ${action}`, context);
2245
+ return ref;
2246
+ }
2247
+ function reviewCommentInput(comments) {
2248
+ return comments?.map((comment) => ({
2249
+ path: comment.path,
2250
+ body: comment.body,
2251
+ line: comment.line,
2252
+ start_line: comment.startLine,
2253
+ side: comment.side?.toUpperCase()
2254
+ }));
2255
+ }
2256
+ /** Resolvable conversations, by the id of each comment in them; empty when GraphQL is unreachable. */
2257
+ async function reviewThreadsByComment(ref, options) {
2258
+ const byComment = /* @__PURE__ */ new Map();
2259
+ if (anonymous) return byComment;
2260
+ let after = null;
2261
+ do {
2262
+ let data;
2263
+ try {
2264
+ data = await graphql("REVIEW_THREADS", {
2265
+ owner: ref.repo.owner,
2266
+ name: ref.repo.name,
2267
+ number: Number(ref.number),
2268
+ ...after ? { after } : {}
2269
+ }, options);
2270
+ } catch (error) {
2271
+ if (error instanceof ForgeError) return byComment;
2272
+ throw error;
2273
+ }
2274
+ const threads = data.repository?.pullRequest?.reviewThreads;
2275
+ for (const node of threads?.nodes ?? []) for (const comment of node.comments.nodes) if (comment.databaseId !== null) byComment.set(String(comment.databaseId), {
2276
+ id: node.id,
2277
+ resolved: node.isResolved
2278
+ });
2279
+ const next = threads?.pageInfo?.hasNextPage ? threads.pageInfo.endCursor : null;
2280
+ after = next !== after ? next : null;
2281
+ } while (after);
2282
+ return byComment;
2283
+ }
2284
+ /** Review comments and conversations read for a pull's first page of reviews, reused by its later pages. */
2285
+ const reviewContext = /* @__PURE__ */ new Map();
2286
+ async function reviewsPage(thread, listOptions = {}) {
2287
+ const ref = requirePull(thread, "reviewed");
2288
+ const result = await fetcher.page(`${threadPath(ref)}/reviews`, {
2289
+ query: { per_page: listOptions.perPage },
2290
+ cursor: listOptions.cursor,
2291
+ signal: listOptions.signal,
2292
+ conditional: false
2293
+ });
2294
+ const now = Date.now();
2295
+ for (const [path, entry] of reviewContext) if (now - entry.at >= REVIEW_CONTEXT_TTL) reviewContext.delete(path);
2296
+ const key = threadPath(ref);
2297
+ const kept = !isFirstPage(listOptions.cursor) && reviewContext.get(key) || {
2298
+ at: now,
2299
+ read: Promise.all([Array.fromAsync(fetcher.items(`${key}/comments`, {
2300
+ query: { per_page: 100 },
2301
+ signal: listOptions.signal
2302
+ })), reviewThreadsByComment(ref, listOptions)])
2303
+ };
2304
+ reviewContext.delete(key);
2305
+ const [comments, byComment] = await kept.read;
2306
+ if (result.cursor) reviewContext.set(key, kept);
2307
+ return toPage(result, (raw) => toReview(ref, raw, comments.filter((comment) => String(comment.pull_request_review_id ?? "") === String(raw.id)).map((comment) => toReviewComment(ref, comment, byComment.get(String(comment.id))))));
2308
+ }
2309
+ async function reviewThreadsPage(thread, listOptions = {}) {
2310
+ const ref = requirePull(thread, "read for review threads");
2311
+ const [data, { toReviewThread }] = await Promise.all([graphql("REVIEW_THREAD_PAGE", {
2312
+ owner: ref.repo.owner,
2313
+ name: ref.repo.name,
2314
+ number: Number(ref.number),
2315
+ first: Math.min(listOptions.perPage ?? 50, 100),
2316
+ after: listOptions.cursor?.token ?? null
2317
+ }, listOptions), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
2318
+ const pull = data.repository?.pullRequest;
2319
+ if (!pull) throw new NotFoundError(`Pull request ${ref.number} not found`, 404, "", context);
2320
+ const { nodes, pageInfo } = pull.reviewThreads;
2321
+ return {
2322
+ items: nodes.map((node) => toReviewThread(ref, node)),
2323
+ cursor: pageInfo.hasNextPage && pageInfo.endCursor ? { token: pageInfo.endCursor } : void 0
2324
+ };
2325
+ }
2326
+ async function createReview(thread, input, options) {
2327
+ const ref = requirePull(thread, "reviewed");
2328
+ const { data } = await fetcher.json(`${threadPath(ref)}/reviews`, {
2329
+ method: "POST",
2330
+ json: {
2331
+ event: input.event ? REVIEW_EVENTS[input.event] : void 0,
2332
+ body: input.body,
2333
+ comments: reviewCommentInput(input.comments)
2334
+ },
2335
+ signal: options?.signal
2336
+ });
2337
+ return toReview(ref, data, []);
2338
+ }
2339
+ async function getComment(ref, options) {
2340
+ const thread = requireThread(ref.thread, context);
2341
+ if (thread.kind === "discussion") {
2342
+ const data = await graphql("GET_DISCUSSION_COMMENT", { id: ref.id }, options);
2343
+ if (!data.node?.id) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2344
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionComment(thread, data.node);
2345
+ }
2346
+ const { data } = await fetcher.json(commentPath(ref), { signal: options?.signal });
2347
+ return toComment(thread, data);
2348
+ }
2349
+ async function getReview(ref, options) {
2350
+ const pull = requirePull(ref.thread, "reviewed");
2351
+ const path = `${threadPath(pull)}/reviews/${encodeURIComponent(ref.id)}`;
2352
+ const [{ data }, comments, byComment] = await Promise.all([
2353
+ fetcher.json(path, { signal: options?.signal }),
2354
+ Array.fromAsync(fetcher.items(`${path}/comments`, {
2355
+ query: { per_page: 100 },
2356
+ signal: options?.signal
2357
+ })),
2358
+ reviewThreadsByComment(pull, options)
2359
+ ]);
2360
+ return toReview(pull, data, comments.map((comment) => toReviewComment(pull, comment, byComment.get(String(comment.id)))));
2361
+ }
2362
+ async function getCheck(ref, options) {
2363
+ if (ref.type !== "check_run") throw new UnsupportedOperationError(`GitHub cannot read a ${ref.type} by id; only check runs can be read on their own`, context);
2364
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/check-runs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2365
+ return toCheckRun(ref.repo, data);
2366
+ }
2367
+ async function getJob(ref, options) {
2368
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2369
+ const run = ref.run ?? (data.run_id === void 0 ? void 0 : {
2370
+ forge: "github",
2371
+ instance,
2372
+ repo: ref.repo,
2373
+ id: String(data.run_id)
2374
+ });
2375
+ if (!run) throw new UnsupportedOperationError(`GitHub returned job ${ref.id} without its run, and the ref names no run`, context);
2376
+ return toWorkflowJob(run, data);
2377
+ }
2378
+ async function subscriptionNode(thread, options) {
2379
+ const ref = requireThread(thread, context);
2380
+ if (ref.kind !== "issue" && ref.kind !== "pull_request" && ref.kind !== "discussion") throw new UnsupportedOperationError(`GitHub has no subscription for a ${ref.kind}`, context);
2381
+ const data = await graphql("SUBSCRIPTION_STATE", {
2382
+ owner: ref.repo.owner,
2383
+ name: ref.repo.name,
2384
+ number: Number(ref.number),
2385
+ discussion: ref.kind === "discussion"
2386
+ }, options);
2387
+ const node = ref.kind === "discussion" ? data.repository?.discussion : data.repository?.issueOrPullRequest;
2388
+ if (!node) throw new NotFoundError(`Thread ${ref.number} not found`, 404, "", context);
2389
+ return {
2390
+ id: node.id,
2391
+ state: node.viewerSubscription
2392
+ };
2393
+ }
2394
+ async function closingPage(ref, document, listOptions) {
2395
+ const [data, { toGraphQLThread }] = await Promise.all([graphql(document, {
2396
+ owner: ref.repo.owner,
2397
+ name: ref.repo.name,
2398
+ number: Number(ref.number),
2399
+ first: Math.min(listOptions.perPage ?? 50, 100),
2400
+ after: listOptions.cursor?.token ?? null
2401
+ }, listOptions), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
2402
+ const references = data.repository?.thread?.references;
2403
+ if (!references) throw new NotFoundError(`Thread ${ref.number} not found`, 404, "", context);
2404
+ return {
2405
+ items: references.nodes.map((node) => {
2406
+ const repo = {
2407
+ forge: FORGE,
2408
+ instance,
2409
+ owner: node.repository.owner.login,
2410
+ name: node.repository.name,
2411
+ externalId: node.repository.databaseId === void 0 ? void 0 : String(node.repository.databaseId)
2412
+ };
2413
+ return toGraphQLThread({
2414
+ forge: FORGE,
2415
+ instance,
2416
+ repo,
2417
+ kind: node.__typename === "PullRequest" ? "pull_request" : "issue",
2418
+ number: String(node.number)
2419
+ }, node);
2420
+ }),
2421
+ cursor: references.pageInfo.hasNextPage && references.pageInfo.endCursor ? { token: references.pageInfo.endCursor } : void 0
2422
+ };
2423
+ }
2424
+ async function setSubscription(thread, state, options) {
2425
+ const { id } = await subscriptionNode(thread, options);
2426
+ await graphql("UPDATE_SUBSCRIPTION", {
2427
+ id,
2428
+ state
2429
+ }, options);
2430
+ }
2431
+ async function reposPage(repoFetcher, path, wrapped, listOptions = {}) {
2432
+ return toPage(await repoFetcher.page(path, {
2433
+ query: { per_page: listOptions.perPage },
2434
+ cursor: listOptions.cursor,
2435
+ signal: listOptions.signal,
2436
+ select: wrapped ? (body, next) => ({
2437
+ items: body.repositories,
2438
+ next
2439
+ }) : void 0
2440
+ }), (raw) => toRepo(instance, raw));
2441
+ }
2442
+ /** The authenticated login, read once and reused; reactions are deleted by id, so removing one needs it. */
2443
+ const viewerLogin = memo(async () => (await fetcher.json("/user")).data.login);
2444
+ /** `/users/{owner}/repos` serves organisations too, but lists only public repositories. */
2445
+ async function ownerReposPage(owner, query = {}) {
2446
+ const visibility = query.visibility === "all" ? void 0 : query.visibility;
2447
+ const read = (path, params) => list(path, query, (raw) => toRepo(instance, raw), { query: {
2448
+ ...params,
2449
+ sort: query.sort === "name" ? "full_name" : query.sort,
2450
+ direction: query.direction
2451
+ } });
2452
+ const userRepos = () => read(`/users/${encodeURIComponent(owner.owner)}/repos`, { type: "owner" });
2453
+ if (visibility === "public") return userRepos();
2454
+ try {
2455
+ return await read(`/orgs/${encodeURIComponent(owner.owner)}/repos`, { type: visibility === "internal" ? void 0 : visibility });
2456
+ } catch (error) {
2457
+ if (!(error instanceof NotFoundError) || !isFirstPage(query.cursor)) throw error;
2458
+ }
2459
+ if (auth.type === "token" && !installation && (await viewerLogin()).toLowerCase() === owner.owner.toLowerCase()) return read("/user/repos", {
2460
+ affiliation: "owner",
2461
+ visibility: visibility === "internal" ? void 0 : visibility
2462
+ });
2463
+ if (visibility) return {
2464
+ items: [],
2465
+ warnings: [{
2466
+ code: "filter_unsupported",
2467
+ message: "GitHub lists only the public repositories of another user"
2468
+ }]
2469
+ };
2470
+ return userRepos();
2471
+ }
2472
+ /** Repository hooks, or organisation hooks for a namespace ref. */
2473
+ function hooksPath(target) {
2474
+ return isNamespaceRef(target) ? `/orgs/${encodeURIComponent(target.owner)}/hooks` : `${repoPath(target)}/hooks`;
2475
+ }
2476
+ function hookConfig(input) {
2477
+ return {
2478
+ ...input.url ? { url: input.url } : {},
2479
+ content_type: input.contentType ?? "json",
2480
+ ...input.secret ? { secret: input.secret } : {}
2481
+ };
2482
+ }
2483
+ /**
2484
+ * The hook endpoints respond with `404` when the credential lacks
2485
+ * `admin:repo_hook` or `admin:org_hook`, so the status alone is misleading.
2486
+ */
2487
+ function scopeIs404(error) {
2488
+ if (error instanceof NotFoundError) return new ForbiddenError("GitHub responded with 404 for a webhook endpoint, which it also does when the credential lacks admin:repo_hook or admin:org_hook", 404, error.body, "resource_protected", {
2489
+ forge: error.forge,
2490
+ instance: error.instance,
2491
+ url: error.url,
2492
+ method: error.method,
2493
+ reasonRaw: "hook_scope_404"
2494
+ }, { cause: error });
2495
+ return error;
2496
+ }
2497
+ /** GitHub responds with `403` to a re-request of another app's check run, and names a missing permission as `Resource not accessible by ...`. */
2498
+ function notOwnerOfCheckRun(error) {
2499
+ if (error.acceptedScopes?.length && !error.acceptedScopes.some((scope) => error.grantedScopes?.includes(scope)) || /not accessible by/i.test(error.body)) return error;
2500
+ return new ForbiddenError("GitHub refused to re-request a check run that another app created", error.status, error.body, "not_owner", {
2501
+ forge: error.forge,
2502
+ instance: error.instance,
2503
+ url: error.url,
2504
+ method: error.method
2505
+ }, { cause: error });
2506
+ }
2507
+ /** GitHub responds with `422` to a change of the tag, target or draft state of an immutable release. */
2508
+ function immutableReleaseIs422(error) {
2509
+ if (!(error instanceof ForgeApiError) || error.constructor !== ForgeApiError || error.status !== 422) return error;
2510
+ const reasonRaw = error.body.match(/\w+ cannot be changed when release is immutable/)?.[0];
2511
+ if (!reasonRaw) return error;
2512
+ return new ForbiddenError("GitHub refused the change because the release is immutable", error.status, error.body, "immutable_release", {
2513
+ forge: error.forge,
2514
+ instance: error.instance,
2515
+ url: error.url,
2516
+ method: error.method,
2517
+ reasonRaw
2518
+ }, { cause: error });
2519
+ }
2520
+ /** GitHub search qualifiers, in the order the docs list them. */
2521
+ function searchQualifiers(query) {
2522
+ const qualifiers = [];
2523
+ const advanced = !query.kind;
2524
+ /** In advanced search a bare `OR` binds looser than the other qualifiers, so caller syntax is grouped. */
2525
+ const group = (value) => advanced ? `(${value})` : value;
2526
+ const text = advanced && query.text ? advancedFreeText(query.text) : query.text;
2527
+ if (text) qualifiers.push(group(text));
2528
+ if (query.repo) qualifiers.push(`repo:${query.repo.owner}/${query.repo.name}`);
2529
+ else if (query.owner) qualifiers.push(`user:${query.owner}`);
2530
+ qualifiers.push(query.kind ? query.kind === "pull_request" ? "is:pr" : "is:issue" : "(is:issue OR is:pr)");
2531
+ if (query.state && query.state !== "all") qualifiers.push(`state:${query.state}`);
2532
+ for (const [name, value] of [
2533
+ ["author", query.author],
2534
+ ["involves", query.involves],
2535
+ ["assignee", query.assignee]
2536
+ ]) if (value) qualifiers.push(`${name}:${value}`);
2537
+ for (const label of query.labels ?? []) qualifiers.push(`label:"${label}"`);
2538
+ if (query.since) qualifiers.push(`updated:>=${query.since.toISOString()}`);
2539
+ if (query.queryRaw) qualifiers.push(group(query.queryRaw));
2540
+ return qualifiers;
2541
+ }
2542
+ /**
2543
+ * GitHub requires a kind in issue search; naming both needs advanced search.
2544
+ * GitHub Enterprise Server may predate it, and GitHub App user access tokens
2545
+ * can't search both kinds at once, so those read issues, then pull requests.
2546
+ */
2547
+ async function searchThreadsPage(query) {
2548
+ if (!query.kind && (enterprise || auth.type === "token" && tokenKindOf(auth, await resolveToken(auth)) === "app-user")) return phased(["issue", "pull_request"].map((kind) => (cursor) => searchIssuesPage({
2549
+ ...query,
2550
+ kind,
2551
+ cursor
2552
+ })), query.cursor);
2553
+ return searchIssuesPage(query);
2554
+ }
2555
+ async function searchIssuesPage(query) {
2556
+ const result = await fetcher.page("/search/issues", {
2557
+ query: {
2558
+ q: searchQualifiers(query).join(" "),
2559
+ advanced_search: query.kind ? void 0 : "true",
2560
+ sort: query.sort && query.sort !== "relevance" ? query.sort : void 0,
2561
+ order: query.direction,
2562
+ per_page: query.perPage
2563
+ },
2564
+ cursor: query.cursor,
2565
+ signal: query.signal,
2566
+ select: (body, next) => {
2567
+ const { items, total_count } = body;
2568
+ return {
2569
+ items,
2570
+ next,
2571
+ total: total_count
2572
+ };
2573
+ }
2574
+ });
2575
+ return toPage(result, (raw) => {
2576
+ const repo = query.repo ?? repoRefFromApiUrl(instance, raw.repository_url);
2577
+ if (!repo) return;
2578
+ const isPull = Boolean(raw.pull_request);
2579
+ return toThread({
2580
+ forge: FORGE,
2581
+ instance,
2582
+ repo,
2583
+ kind: isPull ? "pull_request" : "issue",
2584
+ number: String(raw.number)
2585
+ }, raw);
2586
+ });
2587
+ }
2588
+ function milestonesPage(repo, listOptions = {}) {
2589
+ return list(`${repoPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: { state: listOptions.state ?? "open" } });
2590
+ }
2591
+ async function contributorStats(repo, statsOptions = {}) {
2592
+ const path = `${repoPath(repo)}/stats/contributors`;
2593
+ for (let attempt = 0;; attempt++) {
2594
+ const { data, response } = await fetcher.json(path, { signal: statsOptions.signal });
2595
+ if (response.status !== 202) return (data ?? []).map((raw) => toContributorStats(instance, raw));
2596
+ if (attempt >= CONTRIBUTOR_STATS_DELAYS.length) throw new ForgeApiError(`GitHub is still computing the contributor statistics of ${repo.owner}/${repo.name}`, 202, "", {
2597
+ ...context,
2598
+ url: fetcher.resolve(path),
2599
+ method: "GET"
2600
+ });
2601
+ await sleep(CONTRIBUTOR_STATS_DELAYS[attempt], statsOptions.signal);
2602
+ }
2603
+ }
2604
+ const REPO_SEARCH_SORTS = {
2605
+ updated: "updated",
2606
+ stars: "stars"
2607
+ };
2608
+ async function searchReposPage(query) {
2609
+ const qualifiers = [
2610
+ query.text,
2611
+ query.owner && `user:${query.owner}`,
2612
+ query.language && `language:${query.language}`,
2613
+ query.queryRaw
2614
+ ].filter(Boolean);
2615
+ const warnings = query.sort === "created" ? [{
2616
+ code: "sort_unsupported",
2617
+ message: "GitHub repository search cannot sort by creation time; sorted by relevance"
2618
+ }] : [];
2619
+ const result = await fetcher.page("/search/repositories", {
2620
+ query: {
2621
+ q: qualifiers.join(" "),
2622
+ sort: query.sort ? REPO_SEARCH_SORTS[query.sort] : void 0,
2623
+ order: query.direction,
2624
+ per_page: query.perPage
2625
+ },
2626
+ cursor: query.cursor,
2627
+ signal: query.signal,
2628
+ select: (body, next) => {
2629
+ const { items, total_count } = body;
2630
+ return {
2631
+ items,
2632
+ next,
2633
+ total: total_count
2634
+ };
2635
+ }
2636
+ });
2637
+ return toPage(result, (raw) => toRepo(instance, raw), warnings);
2638
+ }
2639
+ const COMMIT_SEARCH_SORTS = {
2640
+ author_date: "author-date",
2641
+ committer_date: "committer-date"
2642
+ };
2643
+ async function searchCommitsPage(query) {
2644
+ const qualifiers = [
2645
+ query.text,
2646
+ query.repo && `repo:${query.repo.owner}/${query.repo.name}`,
2647
+ query.author && `author:${query.author}`,
2648
+ query.committer && `committer:${query.committer}`,
2649
+ query.since && `author-date:>=${query.since.toISOString()}`,
2650
+ query.until && `author-date:<=${query.until.toISOString()}`,
2651
+ query.queryRaw
2652
+ ].filter(Boolean);
2653
+ const result = await fetcher.page("/search/commits", {
2654
+ query: {
2655
+ q: qualifiers.join(" "),
2656
+ sort: query.sort && COMMIT_SEARCH_SORTS[query.sort],
2657
+ order: query.direction,
2658
+ per_page: query.perPage
2659
+ },
2660
+ cursor: query.cursor,
2661
+ signal: query.signal,
2662
+ select: (body, next) => {
2663
+ const { items, total_count } = body;
2664
+ return {
2665
+ items,
2666
+ next,
2667
+ total: total_count
2668
+ };
2669
+ }
2670
+ });
2671
+ return toPage(result, (raw) => {
2672
+ const repo = query.repo ?? (raw.repository && toRepoRef(instance, raw.repository));
2673
+ return repo && toCommit(repo, raw);
2674
+ });
2675
+ }
2676
+ /** The excerpts only come with the text match media type. */
2677
+ async function searchCodePage(query) {
2678
+ const qualifiers = [
2679
+ query.text,
2680
+ query.repo ? `repo:${query.repo.owner}/${query.repo.name}` : query.owner && `user:${query.owner}`,
2681
+ query.queryRaw
2682
+ ].filter(Boolean);
2683
+ let incomplete = false;
2684
+ const result = await fetcher.page("/search/code", {
2685
+ query: {
2686
+ q: qualifiers.join(" "),
2687
+ per_page: query.perPage
2688
+ },
2689
+ headers: { accept: "application/vnd.github.text-match+json" },
2690
+ cursor: query.cursor,
2691
+ signal: query.signal,
2692
+ select: (body, next) => {
2693
+ const { items, incomplete_results, total_count } = body;
2694
+ incomplete = incomplete_results === true;
2695
+ return {
2696
+ items,
2697
+ next,
2698
+ total: total_count
2699
+ };
2700
+ }
2701
+ });
2702
+ return toPage(result, (raw) => ({
2703
+ repo: query.repo ?? toRepoRef(instance, raw.repository),
2704
+ path: raw.path,
2705
+ ref: new URL(raw.url).searchParams.get("ref") ?? void 0,
2706
+ fragments: (raw.text_matches ?? []).filter((match) => match.property === "content").map((match) => ({ text: match.fragment })),
2707
+ url: raw.html_url,
2708
+ raw
2709
+ }), incomplete ? [{
2710
+ code: "search_incomplete",
2711
+ message: "GitHub stopped the search before it finished; the page may be missing matches"
2712
+ }] : []);
2713
+ }
2714
+ async function feedPage(path, listOptions = {}) {
2715
+ const throttled = throttledPage(path, listOptions, "this feed");
2716
+ if (throttled) return throttled;
2717
+ const result = await fetcher.page(path, {
2718
+ query: { per_page: listOptions.perPage },
2719
+ cursor: listOptions.cursor,
2720
+ signal: listOptions.signal
2721
+ });
2722
+ const poll = recordPoll(path, listOptions.cursor, result.response);
2723
+ const { toFeedEvents } = await import("./events-DjRw3KSr-C72gY7Vu.js");
2724
+ const page = toPage(result, (raw) => toFeedEvents(instance, raw));
2725
+ return {
2726
+ ...page,
2727
+ items: page.items.flat(),
2728
+ ...poll
2729
+ };
2730
+ }
2731
+ function createInstallationsApi(app) {
2732
+ const appFetcher = createFetcher({
2733
+ baseUrl,
2734
+ authHeaders: async () => ({ authorization: `Bearer ${await app.appJwt()}` })
2735
+ });
2736
+ const auth = options.auth;
2737
+ function toInstallation(raw) {
2738
+ return {
2739
+ forge: FORGE,
2740
+ instance,
2741
+ id: String(raw.id),
2742
+ account: toActor(instance, raw.account),
2743
+ targetTypeRaw: raw.target_type,
2744
+ repositorySelectionRaw: raw.repository_selection,
2745
+ raw
2746
+ };
2747
+ }
2748
+ function provider(installation) {
2749
+ return derive({
2750
+ ...options,
2751
+ auth: {
2752
+ ...auth,
2753
+ installationId: installationId(installation)
2754
+ }
2755
+ }, app);
2756
+ }
2757
+ async function listPage(listOptions = {}) {
2758
+ return toPage(await appFetcher.page("/app/installations", {
2759
+ query: { per_page: listOptions.perPage },
2760
+ cursor: listOptions.cursor,
2761
+ signal: listOptions.signal
2762
+ }), toInstallation);
2763
+ }
2764
+ return {
2765
+ listPage,
2766
+ async get(installation, options) {
2767
+ return toInstallation((await appFetcher.json(`/app/installations/${installationId(installation)}`, { signal: options?.signal })).data);
2768
+ },
2769
+ token: (installation, options) => app.installationTokenDetails(installationId(installation), options),
2770
+ reposPage(installation, listOptions) {
2771
+ const id = installationId(installation);
2772
+ return reposPage(createFetcher({
2773
+ baseUrl,
2774
+ authHeaders: async () => ({ authorization: `Bearer ${await app.installationToken(id)}` })
2775
+ }), "/installation/repositories", true, listOptions);
2776
+ },
2777
+ provider,
2778
+ providers() {
2779
+ return forgeIterable(async function* () {
2780
+ for await (const installation of iteratePages(listPage)) yield {
2781
+ installation,
2782
+ provider: provider(installation)
2783
+ };
2784
+ });
2785
+ }
2786
+ };
2787
+ }
2788
+ /** github.com serves file bytes from a CDN outside the REST API rate limit. */
2789
+ const rawFetcher = host === "api.github.com" ? createFetcher({
2790
+ baseUrl: "https://raw.githubusercontent.com",
2791
+ authHeaders: createAuthHeaders(options.auth, credentials)
2792
+ }) : void 0;
2793
+ async function readFile(repo, path, fileOptions = {}) {
2794
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
2795
+ if (fileOptions.metadata === false && rawFetcher) {
2796
+ const response = await rawFetcher.raw(`/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}/${encodeURIComponent(fileOptions.ref ?? "HEAD")}/${encoded}`, { signal: fileOptions.signal });
2797
+ const bytes = new Uint8Array(await response.arrayBuffer());
2798
+ return toFileContent(bytes, {
2799
+ path,
2800
+ size: bytes.byteLength
2801
+ }, fileOptions, context);
2802
+ }
2803
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents/${encoded}`, {
2804
+ query: { ref: fileOptions.ref },
2805
+ signal: fileOptions.signal
2806
+ });
2807
+ const file = {
2808
+ path: data.path,
2809
+ sha: data.sha,
2810
+ size: data.size,
2811
+ url: data.html_url ?? void 0
2812
+ };
2813
+ const content = data.encoding === "base64" && data.content !== void 0 ? data.content : (await fetcher.json(`${repoPath(repo)}/git/blobs/${data.sha}`, { signal: fileOptions.signal })).data.content;
2814
+ return toFileContent(fromBase64(content), file, fileOptions, context);
2815
+ }
2816
+ async function templates(repo, options = {}) {
2817
+ const signal = options.signal;
2818
+ return (await import("./templates-BGDqQMu4-PSB43E1j.js")).readTemplates(repo, options.kind ? [options.kind] : ["issue", "pull_request"], {
2819
+ list: async (ref, path) => {
2820
+ const { data } = await fetcher.json(`${repoPath(ref)}/contents${path ? `/${path.split("/").map(encodeURIComponent).join("/")}` : ""}`, { signal });
2821
+ return Array.isArray(data) ? data : [];
2822
+ },
2823
+ read: async (ref, path) => (await readFile(ref, path, {
2824
+ as: "text",
2825
+ signal
2826
+ })).content,
2827
+ repository: async (ref) => (await fetcher.json(repoPath(ref), { signal })).data
2828
+ });
2829
+ }
2830
+ async function treePage(repo, treeOptions = {}) {
2831
+ const ref = treeOptions.ref ?? "HEAD";
2832
+ const target = treeOptions.path ? `${ref}:${treeOptions.path.replace(/^\/|\/$/g, "")}` : ref;
2833
+ const { data, response } = await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(target)}`, {
2834
+ query: treeOptions.recursive ? { recursive: "1" } : {},
2835
+ signal: treeOptions.signal
2836
+ });
2837
+ const warnings = data.truncated ? [{
2838
+ code: "tree_truncated",
2839
+ message: "GitHub truncated the tree; read it directory by directory instead",
2840
+ subject: target
2841
+ }] : [];
2842
+ return toPage({
2843
+ data: data.tree,
2844
+ response,
2845
+ notModified: false
2846
+ }, toTreeEntry, warnings);
2847
+ }
2848
+ async function compare(repo, base, head, options = {}) {
2849
+ const path = `${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`;
2850
+ const limit = options.commitLimit;
2851
+ const perPage = limit === void 0 ? void 0 : Math.min(100, Math.max(1, limit));
2852
+ const { data } = await fetcher.json(path, {
2853
+ query: { per_page: perPage },
2854
+ signal: options.signal
2855
+ });
2856
+ let commits = data.commits ?? [];
2857
+ const total = data.total_commits ?? data.ahead_by;
2858
+ if (limit !== void 0 && perPage !== void 0 && total !== void 0 && total > commits.length) {
2859
+ const first = Math.floor(Math.max(0, total - limit) / perPage) + 1;
2860
+ const pages = Array.from({ length: Math.ceil(total / perPage) - first + 1 }, (_, index) => first + index);
2861
+ commits = (await Promise.all(pages.map(async (page) => page === 1 ? commits : (await fetcher.json(path, {
2862
+ query: {
2863
+ per_page: perPage,
2864
+ page
2865
+ },
2866
+ signal: options.signal
2867
+ })).data.commits ?? []))).flat();
2868
+ }
2869
+ return {
2870
+ base,
2871
+ head,
2872
+ aheadBy: data.ahead_by,
2873
+ behindBy: data.behind_by,
2874
+ mergeBaseSha: data.merge_base_commit?.sha,
2875
+ commits: commits.map((raw) => toCommit(repo, raw)).toReversed(),
2876
+ files: (data.files ?? []).map(toChangedFile),
2877
+ raw: data
2878
+ };
2879
+ }
2880
+ async function commitsPage(repo, query = {}) {
2881
+ return list(`${repoPath(repo)}/commits`, query, (raw) => toCommit(repo, raw), { query: {
2882
+ sha: query.ref,
2883
+ path: query.path,
2884
+ author: query.author,
2885
+ since: query.since?.toISOString(),
2886
+ until: query.until?.toISOString()
2887
+ } });
2888
+ }
2889
+ async function releasesPage(repo, listOptions = {}) {
2890
+ return list(`${repoPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
2891
+ }
2892
+ /** The commit that `input` builds on: `createFrom` resolved, `expectedHead`, or the head of the branch. */
2893
+ async function commitParent(repo, input, options) {
2894
+ if (input.createFrom !== void 0) return isSha(input.createFrom) ? input.createFrom : (await fetcher.json(`${repoPath(repo)}/commits/${encodeURIComponent(input.createFrom)}`, { signal: options?.signal })).data.sha;
2895
+ return input.expectedHead ?? (await fetcher.json(`${repoPath(repo)}/git/ref/heads/${branchPath(input.branch)}`, { signal: options?.signal })).data.object.sha;
2896
+ }
2897
+ /** Moves `branch` from `before` to `after` only if it is still at `before`. The zero oid stands for a branch that does not exist. */
2898
+ async function swapBranch(repo, branch, before, after, options) {
2899
+ const { repository } = await graphql("REPOSITORY_ID", {
2900
+ owner: repo.owner,
2901
+ name: repo.name
2902
+ }, options);
2903
+ if (!repository) throw new NotFoundError(`${repo.owner}/${repo.name} does not exist`, 404, "", context);
2904
+ await graphql("UPDATE_REFS", { input: {
2905
+ repositoryId: repository.id,
2906
+ refUpdates: [{
2907
+ name: `refs/heads/${branch}`,
2908
+ beforeOid: before,
2909
+ afterOid: after
2910
+ }]
2911
+ } }, options);
2912
+ }
2913
+ /** One `createCommitOnBranch` mutation, which GitHub signs and attributes to the credential's account. */
2914
+ async function commitOnBranch(repo, input, options) {
2915
+ const head = await commitParent(repo, input, options);
2916
+ if (input.createFrom !== void 0) await fetcher.json(`${repoPath(repo)}/git/refs`, {
2917
+ method: "POST",
2918
+ json: {
2919
+ ref: `refs/heads/${input.branch}`,
2920
+ sha: head
2921
+ },
2922
+ signal: options?.signal
2923
+ });
2924
+ const fileChanges = {
2925
+ additions: input.changes.flatMap((change) => change.content === null ? [] : [{
2926
+ path: change.path,
2927
+ contents: changeBase64(change.content)
2928
+ }]),
2929
+ deletions: input.changes.flatMap((change) => change.content === null ? [{ path: change.path }] : [])
2930
+ };
2931
+ try {
2932
+ const [data, { toGraphQLCommit }] = await Promise.all([graphql("CREATE_COMMIT_ON_BRANCH", { input: {
2933
+ branch: {
2934
+ repositoryNameWithOwner: `${repo.owner}/${repo.name}`,
2935
+ branchName: input.branch
2936
+ },
2937
+ expectedHeadOid: head,
2938
+ message: splitMessage(input.message),
2939
+ fileChanges
2940
+ } }, options), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
2941
+ return toGraphQLCommit(repo, data.createCommitOnBranch.commit);
2942
+ } catch (error) {
2943
+ if (input.createFrom !== void 0) await swapBranch(repo, input.branch, head, ZERO_OID).catch(() => {});
2944
+ throw commitError(error);
2945
+ }
2946
+ }
2947
+ /** Blobs, a tree, a commit and a ref update through the Git database API, which can name an author. */
2948
+ async function commitTree(repo, input, options) {
2949
+ const signal = options?.signal;
2950
+ const parent = await commitParent(repo, input, options);
2951
+ const tree = async (directory) => (await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(directory ? `${parent}:${directory}` : parent)}`, { signal })).data;
2952
+ const root = memo(() => tree(""));
2953
+ const existing = await existingFiles(input.changes, inDirectories(async (directory) => {
2954
+ try {
2955
+ const data = directory ? await tree(directory) : await root();
2956
+ return new Map(data.tree.filter((entry) => entry.type === "blob").map((entry) => [directory ? `${directory}/${entry.path}` : entry.path, entry]));
2957
+ } catch (error) {
2958
+ if (error instanceof NotFoundError) return;
2959
+ throw error;
2960
+ }
2961
+ }), context);
2962
+ const entries = await Promise.all(input.changes.map(async ({ path, content }) => {
2963
+ const mode = existing.get(path)?.mode ?? "100644";
2964
+ if (content === null || typeof content === "string") return {
2965
+ path,
2966
+ mode,
2967
+ type: "blob",
2968
+ ...content === null ? { sha: null } : { content }
2969
+ };
2970
+ const { data } = await fetcher.json(`${repoPath(repo)}/git/blobs`, {
2971
+ method: "POST",
2972
+ json: {
2973
+ content: changeBase64(content),
2974
+ encoding: "base64"
2975
+ },
2976
+ signal
2977
+ });
2978
+ return {
2979
+ path,
2980
+ mode,
2981
+ type: "blob",
2982
+ sha: data.sha
2983
+ };
2984
+ }));
2985
+ const { data: created } = await fetcher.json(`${repoPath(repo)}/git/trees`, {
2986
+ method: "POST",
2987
+ json: {
2988
+ base_tree: (await root()).sha,
2989
+ tree: entries
2990
+ },
2991
+ signal
2992
+ });
2993
+ const { data: commit } = await fetcher.json(`${repoPath(repo)}/git/commits`, {
2994
+ method: "POST",
2995
+ json: {
2996
+ message: input.message,
2997
+ tree: created.sha,
2998
+ parents: [parent],
2999
+ author: input.author
3000
+ },
3001
+ signal
3002
+ });
3003
+ try {
3004
+ await swapBranch(repo, input.branch, input.createFrom === void 0 ? parent : ZERO_OID, commit.sha, options);
3005
+ } catch (error) {
3006
+ if (input.createFrom !== void 0) throw error;
3007
+ const { data } = await fetcher.json(`${repoPath(repo)}/git/ref/heads/${branchPath(input.branch)}`, { signal });
3008
+ if (data.object.sha !== parent && error instanceof ForgeApiError) throw new BranchMovedError(`${input.branch} is at ${data.object.sha}, not ${parent}`, 409, error.body, context, { cause: error });
3009
+ throw error;
3010
+ }
3011
+ return toGitCommit(repo, commit);
3012
+ }
3013
+ async function writeRelease(repo, path, method, input, options) {
3014
+ const { data } = await fetcher.json(path, {
3015
+ method,
3016
+ json: {
3017
+ tag_name: input.tag,
3018
+ target_commitish: input.target,
3019
+ name: input.name,
3020
+ body: input.body,
3021
+ draft: input.draft,
3022
+ prerelease: input.prerelease
3023
+ },
3024
+ mapError: immutableReleaseIs422,
3025
+ signal: options?.signal
3026
+ });
3027
+ return toRelease(repo, data);
3028
+ }
3029
+ const ALERT_SOURCES = {
3030
+ dependency: {
3031
+ path: "dependabot/alerts",
3032
+ states: {
3033
+ open: "open",
3034
+ closed: "fixed,dismissed,auto_dismissed"
3035
+ },
3036
+ map: toDependabotAlert
3037
+ },
3038
+ code_scanning: {
3039
+ path: "code-scanning/alerts",
3040
+ states: {
3041
+ open: "open",
3042
+ closed: "closed"
3043
+ },
3044
+ map: toCodeScanningAlert
3045
+ },
3046
+ secret: {
3047
+ path: "secret-scanning/alerts",
3048
+ states: {
3049
+ open: "open",
3050
+ closed: "resolved"
3051
+ },
3052
+ map: toSecretScanningAlert
3053
+ },
3054
+ advisory: {
3055
+ path: "security-advisories",
3056
+ states: {
3057
+ open: void 0,
3058
+ closed: void 0
3059
+ },
3060
+ map: toRepositoryAdvisory
3061
+ }
3062
+ };
3063
+ async function alertsPage(repo, listOptions = {}) {
3064
+ const kinds = listOptions.kind ? [listOptions.kind] : Object.keys(ALERT_SOURCES);
3065
+ return phased(kinds.map((kind) => async (cursor) => {
3066
+ const source = ALERT_SOURCES[kind];
3067
+ const state = listOptions.state ?? "open";
3068
+ const filter = state === "all" ? void 0 : source.states[state];
3069
+ try {
3070
+ const result = await fetcher.page(`${repoPath(repo)}/${source.path}`, {
3071
+ query: {
3072
+ state: filter,
3073
+ per_page: listOptions.perPage
3074
+ },
3075
+ cursor,
3076
+ signal: listOptions.signal
3077
+ });
3078
+ return toPage(result, (raw) => {
3079
+ const alert = source.map(repo, raw);
3080
+ return filter || state === "all" || alert.state === "open" === (state === "open") ? alert : void 0;
3081
+ });
3082
+ } catch (error) {
3083
+ if (!listOptions.kind && (error instanceof InsufficientScopeError || error instanceof NotFoundError)) return {
3084
+ items: [],
3085
+ warnings: [toWarning(error instanceof InsufficientScopeError ? "insufficient_scope" : "alerts_unavailable", error, kind)]
3086
+ };
3087
+ throw error;
3088
+ }
3089
+ }), listOptions.cursor);
3090
+ }
3091
+ /** The GraphQL node id of an issue, pull request or discussion. */
3092
+ async function nodeId(thread, options) {
3093
+ const ref = requireThread(thread, context);
3094
+ return ref.externalId ?? (await subscriptionNode(ref, options)).id;
3095
+ }
3096
+ function reactionPath(target) {
3097
+ if ("thread" in target) return `${repoPath(target.thread.repo)}/issues/comments/${encodeURIComponent(target.id)}/reactions`;
3098
+ const ref = requireIssueOrPull(target, context, "react to");
3099
+ return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/reactions`;
3100
+ }
3101
+ async function reactionsPage(target, listOptions = {}) {
3102
+ const thread = "thread" in target ? target.thread : target;
3103
+ if (thread.kind === "discussion") {
3104
+ const id = "thread" in target ? target.id : await nodeId(thread, listOptions);
3105
+ const [data, { toGraphQLActor, GRAPHQL_REACTIONS }] = await Promise.all([graphql("NODE_REACTIONS", {
3106
+ id,
3107
+ after: listOptions.cursor?.token ?? null
3108
+ }, listOptions), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
3109
+ const reactions = data.node?.reactions;
3110
+ return {
3111
+ items: (reactions?.nodes ?? []).flatMap((raw) => {
3112
+ const actor = toGraphQLActor(instance, raw.user);
3113
+ return actor ? [{
3114
+ content: reactionContent(GRAPHQL_REACTIONS[raw.content] ?? raw.content),
3115
+ contentRaw: raw.content,
3116
+ actor,
3117
+ createdAt: toDate(raw.createdAt),
3118
+ raw
3119
+ }] : [];
3120
+ }),
3121
+ cursor: reactions?.pageInfo.hasNextPage && reactions.pageInfo.endCursor ? { token: reactions.pageInfo.endCursor } : void 0,
3122
+ ...reactions?.totalCount !== void 0 ? { total: reactions.totalCount } : {}
3123
+ };
3124
+ }
3125
+ const result = await fetcher.page(reactionPath(target), {
3126
+ query: { per_page: listOptions.perPage },
3127
+ cursor: listOptions.cursor,
3128
+ signal: listOptions.signal
3129
+ });
3130
+ return toPage(result, (raw) => {
3131
+ const actor = toActor(instance, raw.user);
3132
+ return actor && {
3133
+ content: reactionContent(raw.content),
3134
+ contentRaw: raw.content,
3135
+ actor,
3136
+ createdAt: toDate(raw.created_at),
3137
+ raw
3138
+ };
3139
+ });
3140
+ }
3141
+ async function react(target, reaction, options) {
3142
+ const thread = "thread" in target ? target.thread : target;
3143
+ if (thread.kind === "discussion") {
3144
+ await graphql("ADD_REACTION", {
3145
+ id: "thread" in target ? target.id : await nodeId(thread, options),
3146
+ content: (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).REACTION_CONTENT[reaction]
3147
+ }, options);
3148
+ return;
3149
+ }
3150
+ await fetcher.raw(reactionPath(target), {
3151
+ method: "POST",
3152
+ json: { content: reaction },
3153
+ signal: options?.signal
3154
+ });
3155
+ }
3156
+ async function unreact(target, reaction, options) {
3157
+ const thread = "thread" in target ? target.thread : target;
3158
+ if (thread.kind === "discussion") {
3159
+ await graphql("REMOVE_REACTION", {
3160
+ id: "thread" in target ? target.id : await nodeId(thread, options),
3161
+ content: (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).REACTION_CONTENT[reaction]
3162
+ }, options);
3163
+ return;
3164
+ }
3165
+ const path = reactionPath(target);
3166
+ const { data } = await fetcher.json(path, {
3167
+ query: {
3168
+ content: reaction,
3169
+ per_page: 100
3170
+ },
3171
+ signal: options?.signal
3172
+ });
3173
+ const login = await viewerLogin();
3174
+ const mine = data.find((item) => item.content === reaction && item.user?.login === login);
3175
+ if (mine) await fetcher.raw(`${path}/${encodeURIComponent(mine.id)}`, {
3176
+ method: "DELETE",
3177
+ signal: options?.signal
3178
+ });
3179
+ }
3180
+ async function issuePatch(thread, json, action, signal) {
3181
+ const ref = requireIssueOrPull(thread, context, action);
3182
+ return (await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`, {
3183
+ method: "PATCH",
3184
+ json,
3185
+ signal
3186
+ })).data;
3187
+ }
3188
+ /** Check runs need an installation credential; a token writes a commit status instead. */
3189
+ const canWriteCheckRuns = auth.type === "app" && auth.installationId !== void 0;
3190
+ const STATUS_STATES = {
3191
+ pending: "pending",
3192
+ success: "success",
3193
+ failure: "failure",
3194
+ neutral: "success",
3195
+ unknown: "pending"
3196
+ };
3197
+ const CHECK_RUN_CONCLUSIONS = {
3198
+ success: "success",
3199
+ failure: "failure",
3200
+ neutral: "neutral"
3201
+ };
3202
+ async function report(repo, sha, input, options) {
3203
+ if (canWriteCheckRuns) {
3204
+ const conclusion = CHECK_RUN_CONCLUSIONS[input.state];
3205
+ const { data } = await fetcher.json(`${repoPath(repo)}/check-runs`, {
3206
+ method: "POST",
3207
+ json: {
3208
+ name: input.name,
3209
+ head_sha: sha,
3210
+ status: conclusion ? "completed" : "in_progress",
3211
+ conclusion,
3212
+ details_url: input.url,
3213
+ external_id: input.externalId,
3214
+ output: input.description ? {
3215
+ title: input.name,
3216
+ summary: input.description
3217
+ } : void 0
3218
+ },
3219
+ signal: options?.signal
3220
+ });
3221
+ return toCheckRun(repo, data);
3222
+ }
3223
+ const { data } = await fetcher.json(`${repoPath(repo)}/statuses/${sha}`, {
3224
+ method: "POST",
3225
+ json: {
3226
+ state: STATUS_STATES[input.state],
3227
+ context: input.name,
3228
+ description: input.description,
3229
+ target_url: input.url
3230
+ },
3231
+ signal: options?.signal
3232
+ });
3233
+ return toStatusCheck(repo, data);
3234
+ }
3235
+ async function runsPage(repo, query = {}) {
3236
+ const result = await fetcher.page(`${repoPath(repo)}/actions/runs`, {
3237
+ query: {
3238
+ branch: query.branch,
3239
+ status: query.state === "pending" ? "in_progress" : query.state === "success" ? "success" : query.state === "failure" ? "failure" : void 0,
3240
+ per_page: query.perPage
3241
+ },
3242
+ cursor: query.cursor,
3243
+ signal: query.signal,
3244
+ select: (body, next) => {
3245
+ const { workflow_runs, total_count } = body;
3246
+ return {
3247
+ items: workflow_runs,
3248
+ next,
3249
+ total: total_count
3250
+ };
3251
+ }
3252
+ });
3253
+ return toPage(result, (raw) => toWorkflowRun(repo, raw));
3254
+ }
3255
+ const spec = {
3256
+ extensions: { graphql: ((document, variables = {}, graphqlOptions) => {
3257
+ const query = String(document);
3258
+ return options.readOnly && graphqlOperations(query).some(({ type }) => type === "mutation") ? Promise.reject(new ReadOnlyError("GraphQL mutations are writes and this github provider is read-only", context)) : graphql({ query }, variables, graphqlOptions);
3259
+ }) },
3260
+ checks: {
3261
+ list: verb(true, (repo, sha, options) => headChecks(repo, sha, options?.signal)),
3262
+ get: verb(true, getCheck),
3263
+ report: verb(true, report),
3264
+ rerun: verb(true, async (ref, options) => {
3265
+ if (ref.type !== "check_run") throw new UnsupportedOperationError(`GitHub cannot re-run a ${ref.type}; only check runs can be re-requested`, context);
3266
+ const rerunJob = () => fetcher.raw(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/rerun`, {
3267
+ method: "POST",
3268
+ signal: options?.signal
3269
+ });
3270
+ if (ref.app === "github-actions") {
3271
+ await rerunJob();
3272
+ return;
3273
+ }
3274
+ try {
3275
+ await fetcher.raw(`${repoPath(ref.repo)}/check-runs/${encodeURIComponent(ref.id)}/rerequest`, {
3276
+ method: "POST",
3277
+ signal: options?.signal
3278
+ });
3279
+ } catch (error) {
3280
+ if (!(error instanceof InsufficientScopeError) && !(error instanceof ForgeApiError && error.status === 422)) throw error;
3281
+ try {
3282
+ await rerunJob();
3283
+ } catch (rerunError) {
3284
+ if (!(rerunError instanceof NotFoundError)) throw rerunError;
3285
+ throw error instanceof InsufficientScopeError ? notOwnerOfCheckRun(error) : error;
3286
+ }
3287
+ }
3288
+ })
3289
+ },
3290
+ ci: {
3291
+ runsPage: verb(true, runsPage),
3292
+ getRun: verb(true, async (ref, options) => toWorkflowRun(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
3293
+ jobsPage: verb(true, (ref, listOptions = {}) => list(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/jobs`, listOptions, (raw) => toWorkflowJob(ref, raw), { select: (body, next) => {
3294
+ const { jobs, total_count } = body;
3295
+ return {
3296
+ items: jobs,
3297
+ next,
3298
+ total: total_count
3299
+ };
3300
+ } })),
3301
+ getJob: verb(true, getJob),
3302
+ log: verb(!anonymous, async (ref, options) => (await fetcher.stream(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/logs`, { signal: options?.signal })).body),
3303
+ rerunFailed: verb(true, async (ref, options) => {
3304
+ await fetcher.raw(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/rerun-failed-jobs`, {
3305
+ method: "POST",
3306
+ signal: options?.signal
3307
+ });
3308
+ })
3309
+ },
3310
+ contents: {
3311
+ getFile: verb(true, readFile),
3312
+ treePage: verb(true, treePage),
3313
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/branches`, listOptions, (raw) => toBranch(raw))),
3314
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/tags`, listOptions, toTag)),
3315
+ resolveRef: verb(true, async (repo, ref, options) => (await fetcher.json(`${repoPath(repo)}/commits/${encodeURIComponent(ref)}`, { signal: options?.signal })).data.sha),
3316
+ commitFiles: verb(true, (repo, input, options) => input.author ? commitTree(repo, input, options) : commitOnBranch(repo, input, options)),
3317
+ compare: verb(true, compare)
3318
+ },
3319
+ commits: {
3320
+ listPage: verb(true, commitsPage),
3321
+ get: verb(true, async ({ repo, sha }, options) => toCommit(repo, (await fetcher.json(`${repoPath(repo)}/commits/${sha}`, { signal: options?.signal })).data)),
3322
+ commentsPage: verb(true, (commit, listOptions = {}) => list(`${repoPath(commit.repo)}/commits/${encodeURIComponent(commit.sha)}/comments`, listOptions, (raw) => toCommitComment(commit, raw))),
3323
+ getComment: verb(anonymous ? "unverified" : true, async (ref, options) => {
3324
+ const { data } = await fetcher.json(commitCommentPath(ref), { signal: options?.signal });
3325
+ return toCommitComment(ref.commit, data);
3326
+ }),
3327
+ createComment: verb(true, async (commit, body, options) => {
3328
+ const { data } = await fetcher.json(`${repoPath(commit.repo)}/commits/${encodeURIComponent(commit.sha)}/comments`, {
3329
+ method: "POST",
3330
+ json: { body },
3331
+ signal: options?.signal
3332
+ });
3333
+ return toCommitComment(commit, data);
3334
+ }),
3335
+ updateComment: verb(true, async (ref, body, options) => {
3336
+ const { data } = await fetcher.json(commitCommentPath(ref), {
3337
+ method: "PATCH",
3338
+ json: { body },
3339
+ signal: options?.signal
3340
+ });
3341
+ return toCommitComment(ref.commit, data);
3342
+ }),
3343
+ deleteComment: verb(true, async (ref, options) => {
3344
+ await fetcher.raw(commitCommentPath(ref), {
3345
+ method: "DELETE",
3346
+ signal: options?.signal
3347
+ });
3348
+ }),
3349
+ commentHiding: verb(true, {
3350
+ hideComment: async (ref, reason, options) => {
3351
+ await graphql("MINIMIZE_COMMENT", {
3352
+ id: await commentNodeId(ref, options),
3353
+ classifier: reason.toUpperCase()
3354
+ }, options);
3355
+ },
3356
+ unhideComment: async (ref, options) => {
3357
+ await graphql("UNMINIMIZE_COMMENT", { id: await commentNodeId(ref, options) }, options);
3358
+ }
3359
+ })
3360
+ },
3361
+ search: {
3362
+ threadsPage: verb(true, searchThreadsPage),
3363
+ reposPage: verb(true, searchReposPage),
3364
+ commitsPage: verb(true, searchCommitsPage),
3365
+ codePage: verb(!anonymous, searchCodePage),
3366
+ queryRaw: true
3367
+ },
3368
+ releases: {
3369
+ listPage: verb(true, releasesPage),
3370
+ get: verb(true, async (ref, options) => toRelease(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
3371
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
3372
+ downloadAsset: verb(true, async (ref, downloadOptions = {}) => (await fetcher.stream(`${repoPath(ref.repo)}/releases/assets/${encodeURIComponent(ref.id)}`, {
3373
+ headers: { accept: "application/octet-stream" },
3374
+ signal: downloadOptions.signal
3375
+ })).body),
3376
+ latest: verb(true, async (repo, options) => {
3377
+ try {
3378
+ return toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/latest`, { signal: options?.signal })).data);
3379
+ } catch (error) {
3380
+ if (error instanceof NotFoundError) return;
3381
+ throw error;
3382
+ }
3383
+ }),
3384
+ create: verb(true, (repo, input, options) => writeRelease(repo, `${repoPath(repo)}/releases`, "POST", input, options)),
3385
+ update: verb(true, (ref, update, options) => writeRelease(ref.repo, `${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, "PATCH", update, options))
3386
+ },
3387
+ securityAlerts: {
3388
+ kinds: {
3389
+ dependency: !anonymous && (enterprise ? ({ version }) => versionAtLeast(version, GHES_DEPENDABOT_ALERTS) && "unverified" : true),
3390
+ code_scanning: !anonymous,
3391
+ secret: !anonymous,
3392
+ advisory: !anonymous && !enterprise
3393
+ },
3394
+ listPage: alertsPage
3395
+ },
3396
+ traits: {
3397
+ eventKinds: "native",
3398
+ authKinds: [
3399
+ "token",
3400
+ "app",
3401
+ "anonymous"
3402
+ ],
3403
+ limits: {
3404
+ bodyLength: 65536,
3405
+ commentLength: 65536,
3406
+ labelLength: 50
3407
+ }
3408
+ },
3409
+ probeVersion: enterprise ? async () => (await fetcher.json("/meta")).data.installed_version : void 0,
3410
+ installations: credentials ? verb(true, createInstallationsApi(credentials)) : void 0,
3411
+ web: GITHUB_WEB.links({
3412
+ baseUrl,
3413
+ instance
3414
+ }),
3415
+ webhooks: {
3416
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw), { mapError: scopeIs404 })),
3417
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
3418
+ method: "POST",
3419
+ json: {
3420
+ name: "web",
3421
+ active: input.active ?? true,
3422
+ events: nativeEventsFor(GITHUB_NATIVE_EVENTS, input.events, input.nativeEvents),
3423
+ config: hookConfig(input)
3424
+ },
3425
+ mapError: scopeIs404,
3426
+ signal: options?.signal
3427
+ })).data)),
3428
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3429
+ method: "PATCH",
3430
+ json: {
3431
+ ...update.active === void 0 ? {} : { active: update.active },
3432
+ ...update.events || update.nativeEvents ? { events: nativeEventsFor(GITHUB_NATIVE_EVENTS, update.events, update.nativeEvents) } : {},
3433
+ ...update.url || update.secret || update.contentType ? { config: hookConfig(update) } : {}
3434
+ },
3435
+ mapError: scopeIs404,
3436
+ signal: options?.signal
3437
+ })).data)),
3438
+ delete: verb(true, async (ref, options) => {
3439
+ await fetcher.raw(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3440
+ method: "DELETE",
3441
+ mapError: scopeIs404,
3442
+ signal: options?.signal
3443
+ });
3444
+ }),
3445
+ rotateSecret: verb(true, async (ref, secret, options) => {
3446
+ const current = toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3447
+ mapError: scopeIs404,
3448
+ signal: options?.signal
3449
+ })).data);
3450
+ const { data } = await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
3451
+ method: "PATCH",
3452
+ json: { config: hookConfig({
3453
+ url: current.url,
3454
+ contentType: current.contentType,
3455
+ secret
3456
+ }) },
3457
+ mapError: scopeIs404,
3458
+ signal: options?.signal
3459
+ });
3460
+ return toWebhook(ref.target, data);
3461
+ }),
3462
+ deliveriesPage: verb(true, (ref, listOptions = {}) => list(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}/deliveries`, listOptions, (raw) => toWebhookDelivery(ref, raw), { mapError: scopeIs404 })),
3463
+ redeliver: verb(true, async (ref, options) => {
3464
+ await fetcher.raw(`${hooksPath(ref.hook.target)}/${encodeURIComponent(ref.hook.id)}/deliveries/${encodeURIComponent(ref.id)}/attempts`, {
3465
+ method: "POST",
3466
+ mapError: scopeIs404,
3467
+ signal: options?.signal
3468
+ });
3469
+ })
3470
+ },
3471
+ scopes: githubScopesFor,
3472
+ users: {
3473
+ get: verb(true, async (login, options) => toUser(instance, (await fetcher.json(`/users/${encodeURIComponent(login)}`, { signal: options?.signal })).data)),
3474
+ me: verb(auth.type === "token" && !installation, async (options) => toUser(instance, (await fetcher.json("/user", { signal: options?.signal })).data)),
3475
+ sponsorable: verb(!enterprise && !anonymous, async (login, options) => {
3476
+ const data = await graphql("SPONSORABLE", { login }, options);
3477
+ if (!data.repositoryOwner) throw new NotFoundError(`Account ${login} not found`, 404, "", context);
3478
+ return data.repositoryOwner.hasSponsorsListing;
3479
+ }),
3480
+ eventsPage: verb(true, (login, listOptions) => feedPage(`/users/${encodeURIComponent(login)}/events`, listOptions)),
3481
+ blocking: verb(auth.type === "token" && !installation && (enterprise ? "unverified" : true), {
3482
+ block: async (login, options) => {
3483
+ await fetcher.raw(`/user/blocks/${encodeURIComponent(login)}`, {
3484
+ method: "PUT",
3485
+ signal: options?.signal
3486
+ });
3487
+ },
3488
+ unblock: async (login, options) => {
3489
+ await fetcher.raw(`/user/blocks/${encodeURIComponent(login)}`, {
3490
+ method: "DELETE",
3491
+ signal: options?.signal
3492
+ });
3493
+ }
3494
+ })
3495
+ },
3496
+ repos: {
3497
+ get: verb(true, async (ref, options) => {
3498
+ return toRepo(instance, (await fetcher.json(repoPath(ref), { signal: options?.signal })).data);
3499
+ }),
3500
+ listPage: verb(!anonymous, (listOptions = {}) => installation ? reposPage(fetcher, "/installation/repositories", true, listOptions) : reposPage(fetcher, "/user/repos", false, listOptions)),
3501
+ byOwnerPage: verb(true, ownerReposPage),
3502
+ labelsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/labels`, listOptions, toLabel)),
3503
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${repoPath(repo)}/labels`, {
3504
+ method: "POST",
3505
+ json: {
3506
+ name: label.name,
3507
+ color: label.colour,
3508
+ description: label.description
3509
+ },
3510
+ signal: options?.signal
3511
+ })).data)),
3512
+ milestonesPage: verb(true, milestonesPage),
3513
+ issueTypes: verb(!anonymous && !enterprise, async (repo, options) => {
3514
+ const { data } = await fetcher.json(`${repoPath(repo)}/issue-types`, { signal: options?.signal });
3515
+ return data.map((raw) => toIssueType(raw));
3516
+ }),
3517
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/collaborators`, listOptions, (raw) => toCollaborator(instance, raw))),
3518
+ contributorsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/contributors`, listOptions, (raw) => toContributor(instance, raw), { query: listOptions.includeUnlinked ? { anon: 1 } : {} })),
3519
+ contributorStats: verb(true, contributorStats),
3520
+ templates: verb(true, templates),
3521
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
3522
+ const { data } = await fetcher.json(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}/permission`, { signal: options?.signal });
3523
+ return toRole({
3524
+ role_name: data.role_name ?? (data.permission === "none" ? void 0 : data.permission),
3525
+ permissions: data.user?.permissions
3526
+ });
3527
+ }),
3528
+ branchRules: verb(enterprise ? "unverified" : true, async (repo, name, options) => {
3529
+ const branchPath = `branches/${name.split("/").map(encodeURIComponent).join("/")}`;
3530
+ const path = `${repoPath(repo)}/${branchPath}`;
3531
+ const [{ data: branch }, rules] = await Promise.all([fetcher.json(path, { signal: options?.signal }), Array.fromAsync(fetcher.items(`${repoPath(repo)}/rules/${branchPath}`, {
3532
+ query: { per_page: 100 },
3533
+ signal: options?.signal
3534
+ }))]);
3535
+ const warnings = [];
3536
+ let protection;
3537
+ if (branch.protection?.enabled) try {
3538
+ if (anonymous) throw new AuthenticationRequiredError("Credentials are required for this request", 401, "", context);
3539
+ protection = (await fetcher.json(`${path}/protection`, { signal: options?.signal })).data;
3540
+ } catch (error) {
3541
+ if (!(error instanceof NotFoundError || error instanceof ForbiddenError || error instanceof InsufficientScopeError || error instanceof AuthenticationRequiredError)) throw error;
3542
+ warnings.push(toWarning("insufficient_scope", error, "protection"));
3543
+ }
3544
+ return toBranchRules(branch, rules, protection, warnings);
3545
+ }),
3546
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
3547
+ return { status: (await fetcher.raw(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}`, {
3548
+ method: "PUT",
3549
+ json: { permission: COLLABORATOR_PERMISSIONS[role] ?? role },
3550
+ signal: options?.signal
3551
+ })).status === 201 ? "invited" : "added" };
3552
+ }),
3553
+ assignableUsersPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/assignees`, listOptions, (raw) => toActor(instance, raw))),
3554
+ reviewerCandidatesPage: verb(!anonymous && "emulated", async (thread, listOptions = {}) => {
3555
+ const ref = requireThread(thread, context);
3556
+ const page = await fetcher.page(`${repoPath(ref.repo)}/collaborators`, {
3557
+ query: { per_page: listOptions.perPage },
3558
+ cursor: listOptions.cursor,
3559
+ signal: listOptions.signal
3560
+ });
3561
+ const author = page.notModified ? void 0 : (await get(ref, listOptions)).author?.login;
3562
+ return toPage(page, (raw) => raw.login === author ? void 0 : toActor(instance, raw));
3563
+ }),
3564
+ eventsPage: verb(true, (repo, listOptions) => feedPage(`${repoPath(repo)}/events`, listOptions))
3565
+ },
3566
+ orgs: {
3567
+ teamsPage: verb(!anonymous, (org, listOptions = {}) => list(`/orgs/${encodeURIComponent(org.owner)}/teams`, listOptions, (raw) => toTeam(instance, teamOrg(org), raw))),
3568
+ teamMembersPage: verb(!anonymous, (team, listOptions = {}) => list(`/orgs/${encodeURIComponent(team.org.owner)}/teams/${encodeURIComponent(team.slug)}/members`, listOptions, (raw) => toActor(instance, raw))),
3569
+ blocking: verb(enterprise ? "unverified" : true, {
3570
+ block: async (org, login, options) => {
3571
+ await fetcher.raw(`/orgs/${encodeURIComponent(org.owner)}/blocks/${encodeURIComponent(login)}`, {
3572
+ method: "PUT",
3573
+ signal: options?.signal
3574
+ });
3575
+ },
3576
+ unblock: async (org, login, options) => {
3577
+ await fetcher.raw(`/orgs/${encodeURIComponent(org.owner)}/blocks/${encodeURIComponent(login)}`, {
3578
+ method: "DELETE",
3579
+ signal: options?.signal
3580
+ });
3581
+ }
3582
+ })
3583
+ },
3584
+ notifications: {
3585
+ listPage: verb(notificationsAuth, notificationPage),
3586
+ markRead: verb(notificationsAuth, async (ref, options) => {
3587
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
3588
+ method: "PATCH",
3589
+ signal: options?.signal
3590
+ });
3591
+ }),
3592
+ markDone: verb(notificationsAuth && (enterprise ? ({ version }) => versionAtLeast(version, GHES_MARK_DONE) : true), async (ref, options) => {
3593
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
3594
+ method: "DELETE",
3595
+ signal: options?.signal
3596
+ });
3597
+ }),
3598
+ unsubscribe: verb(notificationsAuth, async (ref, options) => {
3599
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}/subscription`, {
3600
+ method: "DELETE",
3601
+ signal: options?.signal
3602
+ });
3603
+ }),
3604
+ markAllRead: verb(notificationsAuth, async (bulk = {}) => {
3605
+ await fetcher.raw(bulk.repo ? `${repoPath(bulk.repo)}/notifications` : "/notifications", {
3606
+ method: "PUT",
3607
+ ...bulk.before ? { json: { last_read_at: bulk.before.toISOString() } } : {},
3608
+ signal: bulk.signal
3609
+ });
3610
+ })
3611
+ },
3612
+ threads: {
3613
+ get: perKind({
3614
+ issue: true,
3615
+ pull_request: true,
3616
+ discussion: !anonymous
3617
+ }, get),
3618
+ getMany: verb(true, getMany),
3619
+ listPage: perKind({
3620
+ ...ISSUE_LIKE,
3621
+ discussion: !anonymous
3622
+ }, listPage),
3623
+ listFilters: [
3624
+ "involves",
3625
+ "mentions",
3626
+ "milestone"
3627
+ ],
3628
+ eventsPage: verb(true, async (thread, listOptions = {}) => {
3629
+ const ref = requireThread(thread, context);
3630
+ if (ref.kind === "discussion") {
3631
+ const [page, { toDiscussionCommentEvent }] = await Promise.all([discussionCommentPage(ref, listOptions), import("./graphql-BDhuP5jN-BSpB8lWf.js")]);
3632
+ return {
3633
+ ...page,
3634
+ items: page.items.map(({ comment, isReply }) => toDiscussionCommentEvent(ref, comment, isReply))
3635
+ };
3636
+ }
3637
+ return list(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/timeline`, listOptions, (entry) => toEvent(instance, ref, entry));
3638
+ }),
3639
+ commentsPage: perKind({
3640
+ issue: true,
3641
+ pull_request: true,
3642
+ discussion: !anonymous
3643
+ }, commentsPage),
3644
+ getComment: perKind({
3645
+ issue: anonymous ? "unverified" : true,
3646
+ pull_request: true,
3647
+ discussion: !anonymous
3648
+ }, getComment),
3649
+ reviewsPage: verb(true, reviewsPage),
3650
+ getReview: verb(anonymous ? "unverified" : true, getReview),
3651
+ filesPage: verb(true, (ref, listOptions = {}) => list(`${threadPath(requirePull(ref, "read for changed files"))}/files`, listOptions, toChangedFile)),
3652
+ commitsPage: verb(true, (ref, listOptions = {}) => list(`${threadPath(requirePull(ref, "read for commits"))}/commits`, listOptions, (raw) => toCommit(ref.repo, raw))),
3653
+ createReview: verb(true, createReview),
3654
+ submitReview: verb(true, async (ref, event, body, options) => {
3655
+ const pull = requirePull(ref.thread, "reviewed");
3656
+ const { data } = await fetcher.json(`${threadPath(pull)}/reviews/${encodeURIComponent(ref.id)}/events`, {
3657
+ method: "POST",
3658
+ json: {
3659
+ event: REVIEW_EVENTS[event],
3660
+ body
3661
+ },
3662
+ signal: options?.signal
3663
+ });
3664
+ return toReview(pull, data, []);
3665
+ }),
3666
+ replyToReviewComment: verb(true, async (thread, comment, body, options) => {
3667
+ const pull = requirePull(thread, "reviewed");
3668
+ const id = comment.inReplyTo ?? comment.ref?.id;
3669
+ if (id === void 0) throw new UnsupportedOperationError("GitHub replies to a review comment by its id; pass the comment with its `ref`", context);
3670
+ const { data } = await fetcher.json(`${threadPath(pull)}/comments/${encodeURIComponent(id)}/replies`, {
3671
+ method: "POST",
3672
+ json: { body },
3673
+ signal: options?.signal
3674
+ });
3675
+ return toReviewComment(pull, data, comment.thread);
3676
+ }),
3677
+ reviewThreadsPage: verb(!anonymous, reviewThreadsPage),
3678
+ reviewThreads: verb(true, {
3679
+ resolveReviewThread: async (_ref, id, options) => {
3680
+ await graphql("RESOLVE_REVIEW_THREAD", { id }, options);
3681
+ },
3682
+ unresolveReviewThread: async (_ref, id, options) => {
3683
+ await graphql("UNRESOLVE_REVIEW_THREAD", { id }, options);
3684
+ }
3685
+ }),
3686
+ checks: perKind({ pull_request: true }, async (thread, options) => {
3687
+ const ref = requireThread(thread, context);
3688
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
3689
+ return data.head?.sha ? headChecks(ref.repo, data.head.sha, options?.signal) : { items: [] };
3690
+ }),
3691
+ createComment: perKind({
3692
+ issue: true,
3693
+ pull_request: true,
3694
+ discussion: true
3695
+ }, async (thread, body, options) => {
3696
+ const ref = requireThread(thread, context);
3697
+ if (ref.kind === "discussion") {
3698
+ const data = await graphql("ADD_DISCUSSION_COMMENT", {
3699
+ id: await discussionId(ref, options),
3700
+ body
3701
+ }, options);
3702
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionComment(ref, data.addDiscussionComment.comment);
3703
+ }
3704
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/comments`, {
3705
+ method: "POST",
3706
+ json: { body },
3707
+ signal: options?.signal
3708
+ });
3709
+ return toComment(ref, data);
3710
+ }),
3711
+ updateComment: perKind({
3712
+ issue: true,
3713
+ pull_request: true,
3714
+ discussion: true
3715
+ }, async (ref, body, options) => {
3716
+ const thread = requireThread(ref.thread, context);
3717
+ if (thread.kind === "discussion") {
3718
+ const data = await graphql("UPDATE_DISCUSSION_COMMENT", {
3719
+ id: ref.id,
3720
+ body
3721
+ }, options);
3722
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionComment(thread, data.updateDiscussionComment.comment);
3723
+ }
3724
+ const { data } = await fetcher.json(commentPath(ref), {
3725
+ method: "PATCH",
3726
+ json: { body },
3727
+ signal: options?.signal
3728
+ });
3729
+ return toComment(thread, data);
3730
+ }),
3731
+ deleteComment: perKind({
3732
+ issue: true,
3733
+ pull_request: true,
3734
+ discussion: true
3735
+ }, async (ref, options) => {
3736
+ if (ref.thread.kind === "discussion") {
3737
+ await graphql("DELETE_DISCUSSION_COMMENT", { id: ref.id }, options);
3738
+ return;
3739
+ }
3740
+ await fetcher.raw(commentPath(ref), {
3741
+ method: "DELETE",
3742
+ signal: options?.signal
3743
+ });
3744
+ }),
3745
+ create: perKind({
3746
+ issue: true,
3747
+ pull_request: true
3748
+ }, async (repo, input, options) => {
3749
+ const assignees = input.assignees?.map(actorLogin);
3750
+ if (input.kind === "issue") {
3751
+ const { data } = await fetcher.json(`${repoPath(repo)}/issues`, {
3752
+ method: "POST",
3753
+ json: {
3754
+ title: input.title,
3755
+ body: input.body,
3756
+ labels: input.labels,
3757
+ assignees
3758
+ },
3759
+ signal: options?.signal
3760
+ });
3761
+ return toThread({
3762
+ forge: FORGE,
3763
+ instance,
3764
+ repo,
3765
+ kind: "issue",
3766
+ number: String(data.number)
3767
+ }, data);
3768
+ }
3769
+ if (input.kind !== "pull_request") throw new UnsupportedOperationError("GitHub discussions cannot be created through this API yet", context);
3770
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a pull request needs head and base branches", context);
3771
+ const { data: pull } = await fetcher.json(`${repoPath(repo)}/pulls`, {
3772
+ method: "POST",
3773
+ json: {
3774
+ title: input.title,
3775
+ body: input.body,
3776
+ head: input.head,
3777
+ base: input.base,
3778
+ draft: input.draft
3779
+ },
3780
+ signal: options?.signal
3781
+ });
3782
+ const ref = {
3783
+ forge: FORGE,
3784
+ instance,
3785
+ repo,
3786
+ kind: "pull_request",
3787
+ number: String(pull.number)
3788
+ };
3789
+ if (!input.labels?.length && !assignees?.length) return toThread(ref, pull);
3790
+ const { data: issue } = await fetcher.json(`${repoPath(repo)}/issues/${encodeURIComponent(pull.number)}`, {
3791
+ method: "PATCH",
3792
+ json: {
3793
+ labels: input.labels,
3794
+ assignees
3795
+ },
3796
+ signal: options?.signal
3797
+ });
3798
+ return toThread(ref, {
3799
+ ...pull,
3800
+ labels: issue.labels,
3801
+ assignees: issue.assignees
3802
+ });
3803
+ }),
3804
+ /** The pulls endpoint takes no labels or assignees, so a pull request with them is edited as an issue. */
3805
+ update: perKind({
3806
+ issue: true,
3807
+ pull_request: true,
3808
+ discussion: true
3809
+ }, async (thread, input, options) => {
3810
+ const ref = requireThread(thread, context);
3811
+ if (ref.kind === "discussion") {
3812
+ if (input.labels || input.assignees) throw new UnsupportedOperationError("Setting labels or assignees on a GitHub discussion is not supported", context);
3813
+ const id = await discussionId(ref, options);
3814
+ const changed = input.state && await setState({
3815
+ ...ref,
3816
+ externalId: id
3817
+ }, input.state, options);
3818
+ if (input.title === void 0 && input.body === void 0) return changed || getDiscussion(ref, options);
3819
+ const data = await graphql("UPDATE_DISCUSSION", {
3820
+ id,
3821
+ title: input.title,
3822
+ body: input.body
3823
+ }, options);
3824
+ return (await import("./graphql-BDhuP5jN-BSpB8lWf.js")).toDiscussionThread(ref, data.updateDiscussion.discussion);
3825
+ }
3826
+ const target = requireIssueOrPull(ref, context, "update");
3827
+ const json = {
3828
+ title: input.title,
3829
+ body: input.body,
3830
+ state: input.state,
3831
+ labels: input.labels,
3832
+ assignees: input.assignees?.map(actorLogin)
3833
+ };
3834
+ if (target.kind === "pull_request" && (input.labels || input.assignees)) {
3835
+ await issuePatch(target, json, "update", options?.signal);
3836
+ return toThread(target, (await fetcher.json(threadPath(target), { signal: options?.signal })).data);
3837
+ }
3838
+ const { data } = await fetcher.json(threadPath(target), {
3839
+ method: "PATCH",
3840
+ json,
3841
+ signal: options?.signal
3842
+ });
3843
+ return toThread(target, data);
3844
+ }),
3845
+ addLabels: perKind({
3846
+ issue: true,
3847
+ pull_request: true
3848
+ }, async (thread, labels, options) => {
3849
+ const ref = requireIssueOrPull(thread, context, "label");
3850
+ return toLabels((await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`, {
3851
+ method: "POST",
3852
+ json: { labels },
3853
+ signal: options?.signal
3854
+ })).data);
3855
+ }),
3856
+ removeLabels: perKind({
3857
+ issue: true,
3858
+ pull_request: true
3859
+ }, async (thread, labels, options) => {
3860
+ const ref = requireIssueOrPull(thread, context, "label");
3861
+ const path = `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`;
3862
+ let remaining;
3863
+ for (const label of labels) try {
3864
+ remaining = (await fetcher.json(`${path}/${encodeURIComponent(label)}`, {
3865
+ method: "DELETE",
3866
+ signal: options?.signal
3867
+ })).data;
3868
+ } catch (error) {
3869
+ if (!(error instanceof NotFoundError && error.body.includes("Label does not exist"))) throw error;
3870
+ }
3871
+ return toLabels(remaining ?? (await fetcher.json(path, {
3872
+ query: { per_page: 100 },
3873
+ signal: options?.signal
3874
+ })).data);
3875
+ }),
3876
+ setMilestone: perKind({
3877
+ issue: true,
3878
+ pull_request: true
3879
+ }, async (thread, milestone, options) => toMilestone((await issuePatch(thread, { milestone: milestone === void 0 ? null : await milestoneId(milestone, (page) => milestonesPage(requireThread(thread, context).repo, page), context, options) }, "set the milestone of", options?.signal)).milestone)),
3880
+ setIssueType: perKind({ issue: enterprise ? "unverified" : true }, async (thread, issueType, options) => toIssueType((await issuePatch(thread, { type: typeof issueType === "object" ? issueType.name : issueType ?? null }, "set the type of", options?.signal)).type)),
3881
+ reactions: perKind({
3882
+ issue: true,
3883
+ pull_request: true,
3884
+ discussion: true
3885
+ }, {
3886
+ react,
3887
+ unreact
3888
+ }),
3889
+ locking: perKind({
3890
+ issue: true,
3891
+ pull_request: true,
3892
+ discussion: true
3893
+ }, {
3894
+ lock: async (thread, options = {}) => {
3895
+ const ref = requireThread(thread, context);
3896
+ if (ref.kind === "discussion") {
3897
+ await graphql("LOCK_LOCKABLE", { id: await nodeId(ref, options) }, options);
3898
+ return;
3899
+ }
3900
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
3901
+ method: "PUT",
3902
+ json: options.reason ? { lock_reason: LOCK_REASONS[options.reason] } : {},
3903
+ signal: options.signal
3904
+ });
3905
+ },
3906
+ unlock: async (thread, options) => {
3907
+ const ref = requireThread(thread, context);
3908
+ if (ref.kind === "discussion") {
3909
+ await graphql("UNLOCK_LOCKABLE", { id: await nodeId(ref, options) }, options);
3910
+ return;
3911
+ }
3912
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
3913
+ method: "DELETE",
3914
+ signal: options?.signal
3915
+ });
3916
+ }
3917
+ }),
3918
+ hiding: perKind({
3919
+ issue: true,
3920
+ pull_request: true,
3921
+ discussion: true
3922
+ }, {
3923
+ hideComment: async (ref, reason, options) => {
3924
+ await graphql("MINIMIZE_COMMENT", {
3925
+ id: await commentNodeId(ref, options),
3926
+ classifier: reason.toUpperCase()
3927
+ }, options);
3928
+ },
3929
+ unhideComment: async (ref, options) => {
3930
+ await graphql("UNMINIMIZE_COMMENT", { id: await commentNodeId(ref, options) }, options);
3931
+ }
3932
+ }),
3933
+ reactionsPage: perKind({
3934
+ issue: true,
3935
+ pull_request: true,
3936
+ discussion: !anonymous
3937
+ }, reactionsPage),
3938
+ transfer: verb(true, async (thread, repo, options) => {
3939
+ const ref = requireThread(thread, context);
3940
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("GitHub transfers issues only", context);
3941
+ const target = await graphql("REPOSITORY_ID", {
3942
+ owner: repo.owner,
3943
+ name: repo.name
3944
+ }, options);
3945
+ if (!target.repository) throw new NotFoundError(`Repository ${repo.owner}/${repo.name} not found`, 404, "", context);
3946
+ const data = await graphql("TRANSFER_ISSUE", {
3947
+ issue: await nodeId(ref, options),
3948
+ repo: target.repository.id
3949
+ }, options);
3950
+ return {
3951
+ forge: FORGE,
3952
+ instance,
3953
+ repo,
3954
+ kind: "issue",
3955
+ number: String(data.transferIssue.issue.number),
3956
+ externalId: data.transferIssue.issue.id
3957
+ };
3958
+ }),
3959
+ markDuplicate: verb(true, async (thread, canonical, options) => {
3960
+ await graphql("MARK_DUPLICATE", {
3961
+ canonical: await nodeId(canonical, options),
3962
+ duplicate: await nodeId(thread, options)
3963
+ }, options);
3964
+ }),
3965
+ setLabels: perKind({
3966
+ issue: true,
3967
+ pull_request: true
3968
+ }, async (thread, labels, options) => {
3969
+ const ref = requireIssueOrPull(thread, context, "label");
3970
+ return toLabels((await fetcher.json(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/labels`, {
3971
+ method: "PUT",
3972
+ json: { labels },
3973
+ signal: options?.signal
3974
+ })).data);
3975
+ }),
3976
+ setAssignees: perKind({
3977
+ issue: true,
3978
+ pull_request: true
3979
+ }, async (thread, assignees, options) => {
3980
+ return ((await issuePatch(thread, { assignees: assignees.map(actorLogin) }, "assign", options?.signal)).assignees ?? []).flatMap((user) => toActor(instance, user) ?? []);
3981
+ }),
3982
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
3983
+ const ref = requireThread(thread, context);
3984
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests have reviewers", context);
3985
+ const teams = reviewers.filter((reviewer) => typeof reviewer !== "string" && reviewer.typeRaw === "Team").map(actorLogin);
3986
+ const users = reviewers.filter((reviewer) => typeof reviewer === "string" || reviewer.typeRaw !== "Team").map(actorLogin);
3987
+ await fetcher.raw(`${threadPath(ref)}/requested_reviewers`, {
3988
+ method: "POST",
3989
+ json: {
3990
+ reviewers: users,
3991
+ ...teams.length ? { team_reviewers: teams } : {}
3992
+ },
3993
+ signal: options?.signal
3994
+ });
3995
+ }),
3996
+ close: perKind(ISSUE_LIKE, (ref, options_) => setState(ref, "closed", options_)),
3997
+ reopen: perKind({
3998
+ issue: true,
3999
+ pull_request: true,
4000
+ discussion: true
4001
+ }, (ref, options) => setState(ref, "open", options)),
4002
+ merge: verb(true, merge),
4003
+ updateBranch: verb(true, updateBranch),
4004
+ closingIssuesPage: verb(!anonymous, async (thread, listOptions = {}) => closingPage(requirePull(thread, "read for the issues they close"), "CLOSING_ISSUES", listOptions)),
4005
+ closingPullRequestsPage: verb(!anonymous, async (thread, listOptions = {}) => {
4006
+ const ref = requireThread(thread, context);
4007
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("Only issues are closed by pull requests", context);
4008
+ return closingPage(ref, "CLOSING_PULL_REQUESTS", listOptions);
4009
+ }),
4010
+ subscriptions: perKind(ISSUE_LIKE, {
4011
+ subscription: async (thread, options) => {
4012
+ const { state } = await subscriptionNode(thread, options);
4013
+ return state === "SUBSCRIBED" ? "subscribed" : state === "IGNORED" ? "ignored" : "none";
4014
+ },
4015
+ subscribe: (thread, options) => setSubscription(thread, "SUBSCRIBED", options),
4016
+ unsubscribe: (thread, options) => setSubscription(thread, "UNSUBSCRIBED", options)
4017
+ })
4018
+ }
4019
+ };
4020
+ return appItself ? supportOnly(spec, ["installations"]) : spec;
4021
+ }
4022
+ /** Creates a GitHub provider for github.com or a GitHub Enterprise Server instance. */
4023
+ const github = /* @__PURE__ */ defineForgeProvider({
4024
+ forge: FORGE,
4025
+ hasWeb: true,
4026
+ baseUrl: "https://api.github.com",
4027
+ anonymous: true,
4028
+ instance: webHost,
4029
+ headers: {
4030
+ "accept": "application/vnd.github+json",
4031
+ "x-github-api-version": "2022-11-28"
4032
+ },
4033
+ prepare: ({ options, baseUrl, headers, state }) => options.auth?.type === "app" ? state ?? createAppCredentials(options.auth, {
4034
+ baseUrl,
4035
+ fetch: options.fetch,
4036
+ timeout: options.timeout,
4037
+ onRetry: options.onRetry,
4038
+ onRateLimit: options.onRateLimit,
4039
+ headers
4040
+ }) : void 0,
4041
+ authHeaders: ({ options, state }) => createAuthHeaders(options.auth, state),
4042
+ webhooks: githubWebhooks,
4043
+ setup: setupGitHub
4044
+ });
4045
+ const PULL_CHECK_READS = /* @__PURE__ */ new Set([
4046
+ "threads.get",
4047
+ "threads.getMany",
4048
+ "threads.list",
4049
+ "threads.closingPullRequests"
4050
+ ]);
4051
+ /**
4052
+ * Token scopes and fine-grained permissions GitHub documents per endpoint
4053
+ * group. Classic scopes are the ones an OAuth consent screen asks for; the
4054
+ * permissions are the fine-grained token and app equivalents.
4055
+ */
4056
+ function githubScopesFor(verb) {
4057
+ const [group = "", name = ""] = verb.split(".");
4058
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : {
4059
+ token: ["admin:repo_hook", "admin:org_hook"],
4060
+ permissions: { webhooks: "admin" }
4061
+ };
4062
+ if (group === "notifications") return {
4063
+ token: ["notifications"],
4064
+ note: "Notifications need a classic personal access token or an OAuth app token; fine-grained tokens and GitHub Apps have no access to them"
4065
+ };
4066
+ if (group === "securityAlerts") return {
4067
+ token: ["security_events", "repo"],
4068
+ permissions: {
4069
+ vulnerability_alerts: "read",
4070
+ secret_scanning_alerts: "read",
4071
+ code_scanning_alerts: "read",
4072
+ repository_advisories: "read"
4073
+ },
4074
+ note: "Drafts and private vulnerability reports need a security manager, an administrator, or a collaborator on the advisory"
4075
+ };
4076
+ if (group === "installations") return { note: "App credentials: an app JWT signed with the app private key" };
4077
+ if (verb === "users.block" || verb === "users.unblock") return {
4078
+ token: ["user"],
4079
+ permissions: { blocking: "write" },
4080
+ note: "Needs a user token: a GitHub App installation cannot block for an account"
4081
+ };
4082
+ if (verb === "orgs.block" || verb === "orgs.unblock") return {
4083
+ token: ["admin:org"],
4084
+ permissions: { organization_user_blocking: "write" }
4085
+ };
4086
+ if (group === "users" || group === "search") return {
4087
+ token: ["read:user"],
4088
+ permissions: {}
4089
+ };
4090
+ if (group === "orgs") return {
4091
+ token: ["read:org"],
4092
+ permissions: { members: "read" }
4093
+ };
4094
+ if (verb === "threads.checks") return {
4095
+ token: ["repo"],
4096
+ permissions: {
4097
+ pull_requests: "read",
4098
+ checks: "read",
4099
+ statuses: "read"
4100
+ }
4101
+ };
4102
+ if (verb === "checks.list") return {
4103
+ token: ["repo"],
4104
+ permissions: {
4105
+ checks: "read",
4106
+ statuses: "read"
4107
+ }
4108
+ };
4109
+ if (verb === "checks.get") return {
4110
+ token: ["repo"],
4111
+ permissions: { checks: "read" }
4112
+ };
4113
+ if (verb === "checks.rerun") return {
4114
+ token: ["repo"],
4115
+ permissions: {
4116
+ checks: "write",
4117
+ actions: "write"
4118
+ },
4119
+ note: "A check run created by GitHub Actions is re-run as its job, which needs `actions: write`"
4120
+ };
4121
+ if (group === "ci") return {
4122
+ token: ["repo"],
4123
+ permissions: { actions: WRITE_VERBS.has(verb) ? "write" : "read" }
4124
+ };
4125
+ if (verb === "checks.report") return {
4126
+ token: ["repo:status"],
4127
+ permissions: {
4128
+ checks: "write",
4129
+ statuses: "write"
4130
+ }
4131
+ };
4132
+ if (verb === "threads.updateBranch") return {
4133
+ token: ["repo", "public_repo"],
4134
+ permissions: {
4135
+ pull_requests: "write",
4136
+ contents: "write"
4137
+ },
4138
+ note: "A GitHub App needs `contents: write` on the head repository"
4139
+ };
4140
+ if (verb === "repos.issueTypes") return {
4141
+ token: ["repo"],
4142
+ permissions: { metadata: "read" }
4143
+ };
4144
+ if (verb === "repos.branchRules") return {
4145
+ token: ["repo", "public_repo"],
4146
+ permissions: {
4147
+ contents: "read",
4148
+ metadata: "read",
4149
+ administration: "read"
4150
+ },
4151
+ note: "Classic branch protection shows its approvals only to an admin of the repository, or with `administration: read`"
4152
+ };
4153
+ if (verb === "threads.setIssueType") return {
4154
+ token: ["repo", "public_repo"],
4155
+ permissions: { issues: "write" },
4156
+ note: "Needs push access: without it, GitHub leaves the type unchanged"
4157
+ };
4158
+ const write = WRITE_VERBS.has(verb);
4159
+ if (PULL_CHECK_READS.has(verb)) return {
4160
+ token: ["repo", "public_repo"],
4161
+ permissions: {
4162
+ issues: "read",
4163
+ pull_requests: "read",
4164
+ checks: "read",
4165
+ statuses: "read"
4166
+ },
4167
+ note: "The `checks` of a pull request are read from its check runs and commit statuses"
4168
+ };
4169
+ if (group === "threads") return {
4170
+ token: ["repo", "public_repo"],
4171
+ permissions: {
4172
+ issues: write ? "write" : "read",
4173
+ pull_requests: write ? "write" : "read"
4174
+ }
4175
+ };
4176
+ if (group === "repos" || group === "contents" || group === "releases") return {
4177
+ token: ["repo", "public_repo"],
4178
+ permissions: {
4179
+ contents: write ? "write" : "read",
4180
+ metadata: "read"
4181
+ }
4182
+ };
4183
+ return {};
4184
+ }
4185
+ //#endregion
4186
+ export { toRepoRef as a, github, toLabels as i, toActor as n, toThreadState as o, toIssueType as r, FORGE as t };