@vite-hub/forge 0.0.0-stage → 0.1.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,2282 @@
1
+ import { $ as toDate, A as hexColour, B as milestoneId, C as createListing, F as latestCommentOf, G as requireIssueOrPull, I as mapConcurrent, K as requireThread, L as memo, M as isFirstPage, O as getManyConcurrently, Q as teamOrg, R as memoBy, U as rateLimitPart, X as summariseChecks, Y as soleMergeMethod, _t as reactionContent, at as versionAtLeast, d as NotFoundError, et as toFileStatus, g as UnsupportedOperationError, it as toWarning, j as hostOf, k as hasEveryLabel, lt as githubShapedWeb, n as BranchMovedError, nt as toPage, o as ForgeError, q as resolveToken, rt as toPullStats, tt as toMergeError, ut as isNamespaceRef, y as actorLogin } from "./utils-CA_4WJhJ-DNgT61X2.js";
2
+ import { C as verb, S as toFileContent, _ as reviewState, a as verifyHmacSignature, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, l as defineForgeProvider, m as inDirectories, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf } from "./webhooks-DgHwxxYz-D1V2LOr1.js";
3
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/web-Rx0yHk6x.mjs
4
+ const RESERVED_PATHS = [
5
+ "-",
6
+ ".well-known",
7
+ "admin",
8
+ "api",
9
+ "assets",
10
+ "attachments",
11
+ "avatars",
12
+ "captcha",
13
+ "explore",
14
+ "issues",
15
+ "login",
16
+ "milestones",
17
+ "notifications",
18
+ "org",
19
+ "pulls",
20
+ "repo",
21
+ "repo-avatars",
22
+ "search",
23
+ "user"
24
+ ];
25
+ function forgejoWeb(forge, baseUrl) {
26
+ return {
27
+ forge,
28
+ baseUrl,
29
+ apiPath: "/api/v1",
30
+ links: ({ baseUrl }) => githubShapedWeb(baseUrl.replace(/\/api\/v1$/, ""), {
31
+ pull: "pulls",
32
+ sections: { stargazers: "stars" },
33
+ commentFragment: "issuecomment-",
34
+ file: (at) => /^[0-9a-f]{40}$/.test(at) ? `/src/commit/${at}` : `/src/${encodeURIComponent(at)}`,
35
+ parseFile: ([route, qualifier, ref, ...rest]) => {
36
+ if (route !== "src" || !qualifier || !ref) return;
37
+ if (qualifier === "branch" || qualifier === "tag" || qualifier === "commit") return rest.length ? {
38
+ at: ref,
39
+ path: rest.join("/")
40
+ } : void 0;
41
+ return {
42
+ at: qualifier,
43
+ path: [ref, ...rest].join("/")
44
+ };
45
+ },
46
+ lineFragment: (line) => `L${line}`,
47
+ reserved: RESERVED_PATHS
48
+ })
49
+ };
50
+ }
51
+ const FORGEJO_WEB = /* @__PURE__ */ forgejoWeb("forgejo", "https://codeberg.org");
52
+ //#endregion
53
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/definition-Cs2-m5Do.mjs
54
+ const FORGEJO_HEADERS = {
55
+ signature: ["x-forgejo-signature", "x-gitea-signature"],
56
+ event: [
57
+ "x-forgejo-event",
58
+ "x-gitea-event",
59
+ "x-github-event"
60
+ ],
61
+ delivery: ["x-forgejo-delivery", "x-gitea-delivery"]
62
+ };
63
+ /** Native Forgejo and Gitea event names per normalised kind, for hook subscriptions. */
64
+ const FORGEJO_NATIVE_EVENTS = {
65
+ comment: ["issue_comment", "pull_request_comment"],
66
+ review: [
67
+ "pull_request_review_approved",
68
+ "pull_request_review_rejected",
69
+ "pull_request_review_comment"
70
+ ],
71
+ review_comment: ["pull_request_review_comment"],
72
+ state_change: [
73
+ "issues",
74
+ "pull_request",
75
+ "pull_request_sync"
76
+ ],
77
+ label: ["issue_label", "pull_request_label"],
78
+ assignment: ["issue_assign", "pull_request_assign"],
79
+ push: ["push"],
80
+ ref: ["create", "delete"],
81
+ release: ["release"],
82
+ fork: ["fork"],
83
+ wiki: ["wiki"]
84
+ };
85
+ /** Normalised kinds and actions Forgejo and Gitea deliveries translate into. */
86
+ const FORGEJO_WEBHOOK_EVENTS = [
87
+ {
88
+ kind: "comment",
89
+ action: "created"
90
+ },
91
+ {
92
+ kind: "comment",
93
+ action: "edited"
94
+ },
95
+ {
96
+ kind: "comment",
97
+ action: "deleted"
98
+ },
99
+ {
100
+ kind: "review",
101
+ action: "submitted"
102
+ },
103
+ {
104
+ kind: "review_comment",
105
+ action: "created"
106
+ },
107
+ {
108
+ kind: "state_change",
109
+ action: "opened"
110
+ },
111
+ {
112
+ kind: "state_change",
113
+ action: "closed"
114
+ },
115
+ {
116
+ kind: "state_change",
117
+ action: "reopened"
118
+ },
119
+ {
120
+ kind: "state_change",
121
+ action: "merged"
122
+ },
123
+ {
124
+ kind: "label",
125
+ action: "edited"
126
+ },
127
+ {
128
+ kind: "label",
129
+ action: "unlabelled"
130
+ },
131
+ {
132
+ kind: "assignment",
133
+ action: "assigned"
134
+ },
135
+ {
136
+ kind: "assignment",
137
+ action: "unassigned"
138
+ },
139
+ { kind: "push" },
140
+ {
141
+ kind: "ref",
142
+ action: "created"
143
+ },
144
+ {
145
+ kind: "ref",
146
+ action: "deleted"
147
+ },
148
+ {
149
+ kind: "release",
150
+ action: "published"
151
+ },
152
+ {
153
+ kind: "release",
154
+ action: "edited"
155
+ },
156
+ {
157
+ kind: "release",
158
+ action: "deleted"
159
+ },
160
+ {
161
+ kind: "fork",
162
+ action: "created"
163
+ },
164
+ {
165
+ kind: "wiki",
166
+ action: "created"
167
+ },
168
+ {
169
+ kind: "wiki",
170
+ action: "edited"
171
+ },
172
+ {
173
+ kind: "wiki",
174
+ action: "deleted"
175
+ },
176
+ {
177
+ kind: "wiki",
178
+ action: "renamed"
179
+ }
180
+ ];
181
+ /** The id of the built-in user that Forgejo and Gitea Actions act as. */
182
+ const ACTIONS_USER_ID = -2;
183
+ /** Normalisers take the origin because they serve both Forgejo and Gitea. */
184
+ function toActor(origin, user) {
185
+ if (!user) return;
186
+ return {
187
+ ...origin,
188
+ login: user.login,
189
+ id: String(user.id ?? user.login),
190
+ name: user.full_name || void 0,
191
+ avatarUrl: user.avatar_url,
192
+ url: user.html_url,
193
+ typeRaw: user.is_bot === void 0 ? void 0 : user.is_bot ? "bot" : "user",
194
+ isBotHint: user.is_bot === true || user.id === ACTIONS_USER_ID || user.login.endsWith("[bot]")
195
+ };
196
+ }
197
+ function toRepoRef(origin, repo) {
198
+ const [owner, name] = repo.full_name.split("/");
199
+ return {
200
+ ...origin,
201
+ owner: repo.owner?.login ?? owner ?? "",
202
+ name: repo.name ?? name ?? "",
203
+ externalId: repo.id === void 0 ? void 0 : String(repo.id)
204
+ };
205
+ }
206
+ /** Forgejo and Gitea teams have no slug, so the name stands in for one. */
207
+ function toTeam(origin, org, raw) {
208
+ return {
209
+ ref: {
210
+ ...origin,
211
+ org,
212
+ id: String(raw.id),
213
+ slug: raw.name
214
+ },
215
+ name: raw.name,
216
+ description: raw.description || void 0,
217
+ permission: raw.permission,
218
+ raw
219
+ };
220
+ }
221
+ const MERGE_STYLES = {
222
+ "merge": "merge",
223
+ "rebase": "rebase",
224
+ "rebase-merge": "rebase_merge",
225
+ "squash": "squash",
226
+ "fast-forward-only": "fast_forward_only"
227
+ };
228
+ function toRepo(origin, raw) {
229
+ return {
230
+ ref: toRepoRef(origin, raw),
231
+ description: raw.description || void 0,
232
+ defaultBranch: raw.default_branch,
233
+ visibility: raw.internal ? "internal" : raw.private ? "private" : "public",
234
+ visibilityRaw: raw.internal ? "internal" : raw.private ? "private" : "public",
235
+ isFork: raw.fork ?? false,
236
+ isArchived: raw.archived ?? false,
237
+ parent: raw.parent ? toRepoRef(origin, raw.parent) : void 0,
238
+ topics: raw.topics ?? [],
239
+ url: raw.html_url,
240
+ cloneUrls: raw.clone_url || raw.ssh_url ? {
241
+ https: raw.clone_url,
242
+ ssh: raw.ssh_url
243
+ } : void 0,
244
+ createdAt: toDate(raw.created_at),
245
+ updatedAt: toDate(raw.updated_at),
246
+ openIssueCount: raw.open_issues_count,
247
+ openPullCount: raw.open_pr_counter,
248
+ owner: toActor(origin, raw.owner),
249
+ language: raw.language || void 0,
250
+ homepage: raw.website || void 0,
251
+ licence: raw.licenses?.length === 1 ? raw.licenses[0] : void 0,
252
+ stars: raw.stars_count,
253
+ forks: raw.forks_count,
254
+ watchers: raw.watchers_count,
255
+ mergeMethods: raw.allow_merge_commits === void 0 ? void 0 : [
256
+ ...raw.allow_merge_commits ? ["merge"] : [],
257
+ ...raw.allow_squash_merge ? ["squash"] : [],
258
+ ...raw.allow_rebase ? ["rebase"] : [],
259
+ ...raw.allow_rebase_explicit ? ["rebase_merge"] : [],
260
+ ...raw.allow_fast_forward_only_merge ? ["fast_forward_only"] : []
261
+ ],
262
+ defaultMergeMethod: MERGE_STYLES[raw.default_merge_style ?? ""],
263
+ deleteBranchOnMerge: raw.default_delete_branch_after_merge,
264
+ features: raw.has_issues === void 0 ? void 0 : {
265
+ issues: raw.has_issues,
266
+ pullRequests: raw.has_pull_requests ?? true,
267
+ discussions: false,
268
+ wiki: raw.has_wiki ?? false,
269
+ projects: raw.has_projects ?? false,
270
+ releases: raw.has_releases ?? true
271
+ },
272
+ permissions: raw.permissions ? {
273
+ admin: raw.permissions.admin,
274
+ maintain: raw.permissions.admin,
275
+ push: raw.permissions.push,
276
+ triage: raw.permissions.push,
277
+ pull: raw.permissions.pull
278
+ } : void 0,
279
+ raw
280
+ };
281
+ }
282
+ /** Forgejo and Gitea report `owner`, `admin`, `write`, `read` or `none`; there is no triage or maintain role. */
283
+ function toRole(raw) {
284
+ switch (raw) {
285
+ case "owner":
286
+ case "admin": return "admin";
287
+ case "write": return "write";
288
+ case "read": return "read";
289
+ default: return "none";
290
+ }
291
+ }
292
+ function toLabel(raw) {
293
+ return {
294
+ name: raw.name,
295
+ colour: raw.color || void 0,
296
+ description: raw.description || void 0
297
+ };
298
+ }
299
+ function toMilestone(raw) {
300
+ return raw ? {
301
+ id: String(raw.id),
302
+ title: raw.title,
303
+ state: raw.state === "closed" ? "closed" : "open",
304
+ description: raw.description || void 0,
305
+ dueOn: toDate(raw.due_on),
306
+ raw
307
+ } : void 0;
308
+ }
309
+ function toThreadKind(subjectType) {
310
+ switch (subjectType) {
311
+ case "Pull":
312
+ case "PullRequest": return "pull_request";
313
+ case "Issue": return "issue";
314
+ default: return;
315
+ }
316
+ }
317
+ function toSubjectState(state) {
318
+ switch (state) {
319
+ case "open":
320
+ case "closed":
321
+ case "merged": return state;
322
+ default: return "unknown";
323
+ }
324
+ }
325
+ function numberFromUrl(url) {
326
+ return /\/(?:issues|pulls|commits|git\/commits)\/([^/?#]+)/.exec(url ?? "")?.[1];
327
+ }
328
+ function toSubject(origin, raw) {
329
+ const repo = toRepoRef(origin, raw.repository);
330
+ const kind = toThreadKind(raw.subject.type);
331
+ if (kind) return {
332
+ type: "thread",
333
+ thread: {
334
+ ...origin,
335
+ repo,
336
+ kind,
337
+ typeRaw: raw.subject.type,
338
+ number: numberFromUrl(raw.subject.url)
339
+ }
340
+ };
341
+ const sha = raw.subject.type === "Commit" ? numberFromUrl(raw.subject.url) : void 0;
342
+ if (sha) return {
343
+ type: "commit",
344
+ commit: {
345
+ ...origin,
346
+ repo,
347
+ sha
348
+ }
349
+ };
350
+ if (raw.subject.type === "Repository") return {
351
+ type: "repo",
352
+ repo
353
+ };
354
+ return {
355
+ type: "other",
356
+ typeRaw: raw.subject.type,
357
+ repo,
358
+ url: raw.subject.url ?? void 0
359
+ };
360
+ }
361
+ function toNotification(origin, raw) {
362
+ const subject = toSubject(origin, raw);
363
+ const latestComment = latestCommentOf(subject, raw.subject.latest_comment_url);
364
+ return {
365
+ ref: {
366
+ ...origin,
367
+ id: String(raw.id)
368
+ },
369
+ subject,
370
+ subjectTypeRaw: raw.subject.type,
371
+ reason: "unknown",
372
+ unread: raw.unread,
373
+ title: raw.subject.title,
374
+ subjectState: toSubjectState(raw.subject.state),
375
+ subjectStateRaw: raw.subject.state,
376
+ updatedAt: toDate(raw.updated_at) ?? /* @__PURE__ */ new Date(0),
377
+ url: raw.subject.url ?? raw.url,
378
+ ...latestComment ? { latestComment } : {},
379
+ raw
380
+ };
381
+ }
382
+ function toThread(ref, raw) {
383
+ const origin = {
384
+ forge: ref.forge,
385
+ instance: ref.instance
386
+ };
387
+ const kind = (Boolean(raw.pull_request) || Boolean(raw.head)) && ref.kind === "issue" ? "pull_request" : ref.kind;
388
+ const state = raw.merged || raw.pull_request?.merged ? "merged" : raw.state === "open" || raw.state === "closed" ? raw.state : "unknown";
389
+ return {
390
+ ref: {
391
+ ...ref,
392
+ kind,
393
+ externalId: raw.id === void 0 ? ref.externalId : String(raw.id)
394
+ },
395
+ kind,
396
+ title: raw.title,
397
+ body: raw.body ?? void 0,
398
+ state,
399
+ stateRaw: raw.state,
400
+ isDraft: raw.draft ?? raw.pull_request?.draft ?? false,
401
+ author: toActor(origin, raw.user),
402
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(origin, user) ?? []),
403
+ reviewers: (raw.requested_reviewers ?? []).flatMap((user) => {
404
+ const actor = toActor(origin, user);
405
+ return actor ? [{
406
+ actor,
407
+ state: "pending",
408
+ stateRaw: "requested"
409
+ }] : [];
410
+ }),
411
+ labels: (raw.labels ?? []).map((label) => ({
412
+ name: label.name,
413
+ colour: label.color,
414
+ description: label.description || void 0
415
+ })),
416
+ url: raw.html_url,
417
+ createdAt: toDate(raw.created_at),
418
+ updatedAt: toDate(raw.updated_at),
419
+ closedAt: toDate(raw.closed_at),
420
+ mergedAt: toDate(raw.merged_at ?? raw.pull_request?.merged_at),
421
+ mergedBy: toActor(origin, raw.merged_by),
422
+ lastActivityAt: toDate(raw.updated_at),
423
+ locked: raw.is_locked,
424
+ commentCount: raw.comments,
425
+ milestone: toMilestone(raw.milestone),
426
+ branches: raw.head && raw.base ? {
427
+ head: {
428
+ ref: raw.head.ref,
429
+ sha: raw.head.sha,
430
+ repo: raw.head.repo ? toRepoRef(origin, raw.head.repo) : void 0
431
+ },
432
+ base: {
433
+ ref: raw.base.ref,
434
+ sha: raw.base.sha
435
+ },
436
+ mergeCommitSha: raw.merge_commit_sha ?? void 0
437
+ } : void 0,
438
+ stats: toPullStats({
439
+ additions: raw.additions,
440
+ deletions: raw.deletions,
441
+ changedFileCount: raw.changed_files
442
+ }),
443
+ raw
444
+ };
445
+ }
446
+ function toComment(thread, raw) {
447
+ return {
448
+ ref: {
449
+ forge: thread.forge,
450
+ instance: thread.instance,
451
+ thread,
452
+ id: String(raw.id)
453
+ },
454
+ body: raw.body ?? "",
455
+ author: toActor({
456
+ forge: thread.forge,
457
+ instance: thread.instance
458
+ }, raw.user),
459
+ createdAt: toDate(raw.created_at),
460
+ updatedAt: toDate(raw.updated_at),
461
+ url: raw.html_url,
462
+ raw
463
+ };
464
+ }
465
+ const EVENT_KINDS = {
466
+ comment: "comment",
467
+ review: "review",
468
+ code_comment: "review_comment",
469
+ commit_ref: "commit",
470
+ issue_ref: "referenced",
471
+ pull_ref: "referenced",
472
+ change_issue_ref: "referenced",
473
+ pull_push: "commit",
474
+ label: "label",
475
+ close: "state_change",
476
+ reopen: "state_change",
477
+ merge_pull: "state_change",
478
+ pull_request_ready_for_review: "state_change",
479
+ assignees: "assignment"
480
+ };
481
+ function toEventKind(type) {
482
+ return EVENT_KINDS[type ?? ""] ?? "other";
483
+ }
484
+ function summarise(entry, kind, actor) {
485
+ const who = actor?.login ?? "someone";
486
+ switch (kind) {
487
+ case "comment": return `${who} commented`;
488
+ case "review": return `${who} reviewed`;
489
+ case "review_comment": return `${who} commented on a line`;
490
+ case "commit": return `${who} referenced ${entry.ref_commit_sha?.slice(0, 7) || "a commit"}`;
491
+ case "referenced": return `${who} referenced this${entry.ref_issue ? ` from #${entry.ref_issue.number}` : ""}`;
492
+ case "label": return `${who} changed label ${entry.label?.name ?? ""}`.trim();
493
+ case "state_change": return `${who} ${entry.type ?? "changed state"}`;
494
+ case "assignment": return `${who} assigned ${entry.assignee?.login ?? ""}`.trim();
495
+ default: return `${who} ${entry.type ?? "acted"}`;
496
+ }
497
+ }
498
+ /** `issue_ref`, `pull_ref` and `change_issue_ref` name the thread that mentioned this one. */
499
+ function crossReference(thread, entry) {
500
+ const source = entry.ref_issue;
501
+ if (!source) return { type: "referenced" };
502
+ const [owner = "", name = ""] = source.repository?.full_name.split("/") ?? [];
503
+ const repo = name ? {
504
+ forge: thread.forge,
505
+ instance: thread.instance,
506
+ owner,
507
+ name,
508
+ externalId: source.repository?.id === void 0 ? void 0 : String(source.repository.id)
509
+ } : thread.repo;
510
+ return {
511
+ type: "referenced",
512
+ from: {
513
+ forge: thread.forge,
514
+ instance: thread.instance,
515
+ repo,
516
+ kind: source.pull_request ? "pull_request" : "issue",
517
+ number: String(source.number)
518
+ },
519
+ fromRepo: repo
520
+ };
521
+ }
522
+ function timelineDetail(thread, entry, kind) {
523
+ const origin = {
524
+ forge: thread.forge,
525
+ instance: thread.instance
526
+ };
527
+ switch (kind) {
528
+ case "comment":
529
+ case "review_comment": return {
530
+ type: kind,
531
+ comment: entry.id === void 0 ? void 0 : {
532
+ ...origin,
533
+ thread,
534
+ id: String(entry.id)
535
+ },
536
+ body: entry.body ?? void 0
537
+ };
538
+ case "review": return {
539
+ type: "review",
540
+ state: "unknown",
541
+ body: entry.body || void 0,
542
+ review: entry.review_id ? {
543
+ ...origin,
544
+ thread,
545
+ id: String(entry.review_id)
546
+ } : void 0
547
+ };
548
+ case "referenced": return crossReference(thread, entry);
549
+ default: return;
550
+ }
551
+ }
552
+ function toEvent(thread, entry, source = "poll") {
553
+ const origin = {
554
+ forge: thread.forge,
555
+ instance: thread.instance
556
+ };
557
+ const kind = toEventKind(entry.type);
558
+ const actor = toActor(origin, entry.user);
559
+ return {
560
+ ...origin,
561
+ id: String(entry.id ?? `${thread.number ?? ""}-${entry.type}-${entry.created_at}`),
562
+ kind,
563
+ kindRaw: entry.type,
564
+ summary: summarise(entry, kind, actor),
565
+ ...eventTime(toDate(entry.created_at), /* @__PURE__ */ new Date(0)),
566
+ actor,
567
+ repo: thread.repo,
568
+ thread,
569
+ detail: timelineDetail(thread, entry, kind),
570
+ source,
571
+ payload: entry
572
+ };
573
+ }
574
+ /** Commit status values. `warning` is informational and neither passes nor fails. */
575
+ function statusState(status) {
576
+ switch (status) {
577
+ case "success": return "success";
578
+ case "failure":
579
+ case "error": return "failure";
580
+ case "pending": return "pending";
581
+ case "warning": return "neutral";
582
+ default: return "unknown";
583
+ }
584
+ }
585
+ function toStatusCheck(repo, raw) {
586
+ const state = statusState(raw.status);
587
+ return {
588
+ ref: {
589
+ forge: repo.forge,
590
+ instance: repo.instance,
591
+ repo,
592
+ id: String(raw.id),
593
+ type: "status"
594
+ },
595
+ name: raw.context,
596
+ state,
597
+ stateRaw: raw.status,
598
+ url: raw.target_url || void 0,
599
+ startedAt: toDate(raw.created_at),
600
+ completedAt: state === "pending" ? void 0 : toDate(raw.updated_at),
601
+ raw
602
+ };
603
+ }
604
+ function toStatusChecks(repo, raw) {
605
+ return (raw.statuses ?? []).map((status) => toStatusCheck(repo, status));
606
+ }
607
+ /** Every Actions run and job status behind each normalised state, as the repeated `status` filter takes them. */
608
+ const ACTION_STATES = {
609
+ pending: [
610
+ "waiting",
611
+ "running",
612
+ "blocked"
613
+ ],
614
+ success: ["success"],
615
+ failure: ["failure", "cancelled"],
616
+ neutral: ["skipped"]
617
+ };
618
+ /** Gitea's statuses and conclusions behind each normalised state, as its repeated `status` filter takes them. */
619
+ const GITEA_ACTION_STATES = {
620
+ pending: [
621
+ "queued",
622
+ "waiting",
623
+ "in_progress"
624
+ ],
625
+ success: ["success"],
626
+ failure: ["failure", "cancelled"],
627
+ neutral: ["skipped"]
628
+ };
629
+ function stateOf(states) {
630
+ return new Map(Object.entries(states).flatMap(([state, raws]) => raws.map((raw) => [raw, state])));
631
+ }
632
+ const ACTION_STATE_OF = /* @__PURE__ */ stateOf(ACTION_STATES);
633
+ const GITEA_ACTION_STATE_OF = /* @__PURE__ */ stateOf(GITEA_ACTION_STATES);
634
+ function actionState(status) {
635
+ return ACTION_STATE_OF.get(status) ?? "unknown";
636
+ }
637
+ function giteaActionState(raw) {
638
+ return GITEA_ACTION_STATE_OF.get(raw.status === "completed" ? raw.conclusion ?? "" : raw.status) ?? "unknown";
639
+ }
640
+ /** Forgejo and Gitea write the zero Unix time for a run or job that never started or stopped. */
641
+ function actionTime(value) {
642
+ const date = toDate(value);
643
+ return date && date.getTime() > 0 ? date : void 0;
644
+ }
645
+ /** `prettyref` is the short ref; pull request runs carry `#<number>` or a bare sha instead of a branch. */
646
+ function actionBranch(raw) {
647
+ const ref = raw.prettyref;
648
+ return ref && !ref.startsWith("#") && ref !== raw.commit_sha ? ref : void 0;
649
+ }
650
+ function toActionRun(repo, raw) {
651
+ const state = actionState(raw.status);
652
+ return {
653
+ ref: {
654
+ forge: repo.forge,
655
+ instance: repo.instance,
656
+ repo,
657
+ id: String(raw.id)
658
+ },
659
+ name: raw.workflow_id || raw.title || String(raw.id),
660
+ state,
661
+ stateRaw: raw.status,
662
+ number: raw.index_in_repo === void 0 ? void 0 : String(raw.index_in_repo),
663
+ eventRaw: raw.trigger_event || raw.event,
664
+ branch: actionBranch(raw),
665
+ sha: raw.commit_sha || void 0,
666
+ url: raw.html_url || void 0,
667
+ actor: toActor({
668
+ forge: repo.forge,
669
+ instance: repo.instance
670
+ }, raw.trigger_user),
671
+ createdAt: toDate(raw.created),
672
+ startedAt: actionTime(raw.started),
673
+ completedAt: state === "pending" ? void 0 : actionTime(raw.stopped),
674
+ raw
675
+ };
676
+ }
677
+ function toActionJob(run, raw) {
678
+ return {
679
+ ref: {
680
+ forge: run.forge,
681
+ instance: run.instance,
682
+ repo: run.repo,
683
+ id: String(raw.id),
684
+ run
685
+ },
686
+ name: raw.name,
687
+ state: actionState(raw.status),
688
+ stateRaw: raw.status,
689
+ url: raw.html_url || void 0,
690
+ raw
691
+ };
692
+ }
693
+ function toGiteaActionRun(repo, raw) {
694
+ const state = giteaActionState(raw);
695
+ return {
696
+ ref: {
697
+ forge: repo.forge,
698
+ instance: repo.instance,
699
+ repo,
700
+ id: String(raw.id)
701
+ },
702
+ name: raw.path?.split("@refs/")[0] || raw.display_title || String(raw.id),
703
+ state,
704
+ stateRaw: raw.status,
705
+ number: raw.run_number === void 0 ? void 0 : String(raw.run_number),
706
+ eventRaw: raw.event,
707
+ branch: raw.head_branch || void 0,
708
+ sha: raw.head_sha || void 0,
709
+ url: raw.html_url || void 0,
710
+ actor: toActor({
711
+ forge: repo.forge,
712
+ instance: repo.instance
713
+ }, raw.actor),
714
+ createdAt: toDate(raw.created_at),
715
+ startedAt: actionTime(raw.started_at),
716
+ completedAt: state === "pending" ? void 0 : actionTime(raw.completed_at),
717
+ raw
718
+ };
719
+ }
720
+ function toGiteaActionJob(run, raw) {
721
+ const state = giteaActionState(raw);
722
+ return {
723
+ ref: {
724
+ forge: run.forge,
725
+ instance: run.instance,
726
+ repo: run.repo,
727
+ id: String(raw.id),
728
+ run
729
+ },
730
+ name: raw.name,
731
+ state,
732
+ stateRaw: raw.status,
733
+ url: raw.html_url || void 0,
734
+ startedAt: actionTime(raw.started_at),
735
+ completedAt: state === "pending" ? void 0 : actionTime(raw.completed_at),
736
+ raw
737
+ };
738
+ }
739
+ function toRelease(repo, raw) {
740
+ const origin = {
741
+ forge: repo.forge,
742
+ instance: repo.instance
743
+ };
744
+ const ref = {
745
+ ...origin,
746
+ repo,
747
+ id: String(raw.id),
748
+ tag: raw.tag_name
749
+ };
750
+ return {
751
+ ref,
752
+ name: raw.name || void 0,
753
+ tag: raw.tag_name,
754
+ body: raw.body || void 0,
755
+ isDraft: raw.draft,
756
+ isPrerelease: raw.prerelease,
757
+ author: raw.author ? toActor(repo, raw.author) : void 0,
758
+ publishedAt: raw.draft ? void 0 : toDate(raw.published_at),
759
+ createdAt: toDate(raw.created_at),
760
+ url: raw.html_url,
761
+ assets: raw.assets?.map((asset) => ({
762
+ ...asset.id === void 0 ? {} : { ref: {
763
+ ...origin,
764
+ repo,
765
+ release: ref,
766
+ id: String(asset.id)
767
+ } },
768
+ name: asset.name,
769
+ url: asset.browser_download_url,
770
+ size: asset.size,
771
+ downloadCount: asset.download_count
772
+ })),
773
+ raw
774
+ };
775
+ }
776
+ function toReviewComment(thread, raw) {
777
+ return {
778
+ ref: {
779
+ forge: thread.forge,
780
+ instance: thread.instance,
781
+ thread,
782
+ id: String(raw.id)
783
+ },
784
+ body: raw.body ?? "",
785
+ author: toActor(thread, raw.user),
786
+ path: raw.path,
787
+ line: raw.position ?? raw.original_position,
788
+ side: raw.position ? "right" : raw.original_position ? "left" : void 0,
789
+ createdAt: toDate(raw.created_at),
790
+ url: raw.html_url,
791
+ raw
792
+ };
793
+ }
794
+ function toReview(thread, raw, comments) {
795
+ return {
796
+ ref: {
797
+ forge: thread.forge,
798
+ instance: thread.instance,
799
+ thread,
800
+ id: String(raw.id)
801
+ },
802
+ author: toActor(thread, raw.user),
803
+ state: reviewState(raw.state?.toLowerCase() === "request_changes" ? "changes_requested" : raw.state),
804
+ stateRaw: raw.state,
805
+ body: raw.body || void 0,
806
+ submittedAt: toDate(raw.submitted_at),
807
+ comments,
808
+ url: raw.html_url,
809
+ raw
810
+ };
811
+ }
812
+ function toChangedFile(raw) {
813
+ return {
814
+ path: raw.filename,
815
+ previousPath: raw.previous_filename,
816
+ status: toFileStatus(raw.status),
817
+ statusRaw: raw.status,
818
+ additions: raw.additions,
819
+ deletions: raw.deletions
820
+ };
821
+ }
822
+ function toFileCommit(repo, raw) {
823
+ return {
824
+ ref: {
825
+ forge: repo.forge,
826
+ instance: repo.instance,
827
+ repo,
828
+ sha: raw.sha
829
+ },
830
+ sha: raw.sha,
831
+ message: raw.message ?? "",
832
+ author: {
833
+ name: raw.author?.name,
834
+ email: raw.author?.email,
835
+ date: toDate(raw.author?.date)
836
+ },
837
+ committer: {
838
+ name: raw.committer?.name,
839
+ email: raw.committer?.email,
840
+ date: toDate(raw.committer?.date)
841
+ },
842
+ parents: raw.parents?.flatMap((parent) => parent.sha ? [parent.sha] : []) ?? [],
843
+ url: raw.html_url,
844
+ raw
845
+ };
846
+ }
847
+ function toCommit(repo, raw) {
848
+ const origin = {
849
+ forge: repo.forge,
850
+ instance: repo.instance
851
+ };
852
+ return {
853
+ ref: {
854
+ ...origin,
855
+ repo,
856
+ sha: raw.sha
857
+ },
858
+ sha: raw.sha,
859
+ message: raw.commit?.message ?? "",
860
+ author: {
861
+ actor: toActor(origin, raw.author),
862
+ name: raw.commit?.author?.name,
863
+ email: raw.commit?.author?.email,
864
+ date: toDate(raw.commit?.author?.date)
865
+ },
866
+ committer: {
867
+ actor: toActor(origin, raw.committer),
868
+ name: raw.commit?.committer?.name,
869
+ email: raw.commit?.committer?.email,
870
+ date: toDate(raw.commit?.committer?.date)
871
+ },
872
+ parents: raw.parents?.flatMap((parent) => parent.sha ? [parent.sha] : []) ?? [],
873
+ url: raw.html_url,
874
+ ...raw.stats ? { stats: {
875
+ additions: raw.stats.additions ?? 0,
876
+ deletions: raw.stats.deletions ?? 0,
877
+ total: raw.stats.total
878
+ } } : {},
879
+ ...raw.files ? { files: raw.files.map(toChangedFile) } : {},
880
+ raw
881
+ };
882
+ }
883
+ function toBranch(raw) {
884
+ return {
885
+ name: raw.name,
886
+ sha: raw.commit?.id ?? "",
887
+ isProtected: raw.protected,
888
+ raw
889
+ };
890
+ }
891
+ /** The branch reports the protection rule that matches it, so one read covers both checks and approvals. */
892
+ function toBranchRules(raw) {
893
+ return {
894
+ branch: raw.name,
895
+ requiredChecks: raw.enable_status_check ? (raw.status_check_contexts ?? []).map((name) => ({ name })) : [],
896
+ requiredApprovals: raw.required_approvals ?? 0,
897
+ raw
898
+ };
899
+ }
900
+ function toTag(raw) {
901
+ return {
902
+ name: raw.name,
903
+ sha: raw.commit?.sha ?? raw.id ?? "",
904
+ raw
905
+ };
906
+ }
907
+ const TREE_TYPES = {
908
+ blob: "file",
909
+ tree: "directory",
910
+ commit: "submodule"
911
+ };
912
+ function toTreeEntry(raw) {
913
+ return {
914
+ path: raw.path,
915
+ type: raw.mode === "120000" ? "symlink" : TREE_TYPES[raw.type ?? ""] ?? "file",
916
+ sha: raw.sha,
917
+ size: raw.size,
918
+ mode: raw.mode
919
+ };
920
+ }
921
+ function toWebhook(target, raw) {
922
+ const nativeEvents = raw.events ?? [];
923
+ return {
924
+ ref: {
925
+ forge: target.forge,
926
+ instance: target.instance,
927
+ target,
928
+ id: String(raw.id)
929
+ },
930
+ url: raw.config?.url ?? "",
931
+ events: eventKindsOf(FORGEJO_NATIVE_EVENTS, nativeEvents),
932
+ nativeEvents,
933
+ active: raw.active ?? true,
934
+ contentType: raw.config?.content_type === "form" ? "form" : "json",
935
+ createdAt: toDate(raw.created_at),
936
+ updatedAt: toDate(raw.updated_at),
937
+ raw
938
+ };
939
+ }
940
+ /** A full page is followed even when `x-total-count` disagrees, because timelines report the page's own length. */
941
+ function countedNextUrl(url, count, totalHeader) {
942
+ const next = new URL(url);
943
+ const page = Number(next.searchParams.get("page")) || 1;
944
+ const limit = Number(next.searchParams.get("limit")) || void 0;
945
+ if (count === 0 || limit !== void 0 && count > limit) return;
946
+ const size = limit ?? count;
947
+ const total = totalHeader === null ? NaN : Number(totalHeader);
948
+ if (!(Number.isFinite(total) && (page - 1) * size + count < total) && count !== limit) return;
949
+ next.searchParams.set("page", String(page + 1));
950
+ next.searchParams.set("limit", String(Math.min(count, size)));
951
+ return next.toString();
952
+ }
953
+ /** `fetcher` with `page` and `items` that also continue listings Forgejo and Gitea page without a `Link` header. */
954
+ function countedPages(fetcher) {
955
+ async function page(path, options = {}) {
956
+ const result = await fetcher.page(path, options);
957
+ if (result.cursor?.nextUrl || result.notModified) return result;
958
+ const nextUrl = countedNextUrl(options.cursor?.nextUrl ? fetcher.resolve(options.cursor.nextUrl) : fetcher.resolve(path, options.query), result.data.length, result.response.headers.get("x-total-count"));
959
+ return nextUrl ? {
960
+ ...result,
961
+ cursor: {
962
+ ...result.cursor,
963
+ nextUrl
964
+ }
965
+ } : result;
966
+ }
967
+ async function* items(path, options = {}) {
968
+ let cursor;
969
+ do {
970
+ const result = await page(path, {
971
+ ...options,
972
+ cursor
973
+ });
974
+ yield* result.data;
975
+ cursor = result.notModified ? void 0 : result.cursor;
976
+ } while (cursor?.nextUrl);
977
+ }
978
+ return {
979
+ ...fetcher,
980
+ page,
981
+ items
982
+ };
983
+ }
984
+ function verifyForgejoSignature(delivery, secret, names = FORGEJO_HEADERS) {
985
+ return verifyHmacSignature(delivery, secret, { header: names.signature });
986
+ }
987
+ /** Handlers for one deployment family; Gitea differs from Forgejo only in its header names. */
988
+ function forgejoWebhooks(profile) {
989
+ return ({ options, origin }) => ({
990
+ events: FORGEJO_WEBHOOK_EVENTS,
991
+ verify: (delivery) => verifyForgejoSignature(delivery, options.webhookSecret, profile.headers),
992
+ translate: async (delivery) => (await import("./events-CRaLy7U3-3PNNp5WZ.js")).translateForgejoWebhook(origin, delivery, profile.headers)
993
+ });
994
+ }
995
+ const YAML_FILE = /\.ya?ml$/i;
996
+ /** The folders each web UI checks for a pull request template, in its order. Gitea skips `.forgejo` and `docs`. */
997
+ const PULL_TEMPLATE_DIRECTORIES = {
998
+ forgejo: [
999
+ "",
1000
+ ".forgejo",
1001
+ ".gitea",
1002
+ ".github",
1003
+ "docs"
1004
+ ],
1005
+ gitea: [
1006
+ "",
1007
+ ".gitea",
1008
+ ".github"
1009
+ ]
1010
+ };
1011
+ const PULL_TEMPLATE_FILES = ["PULL_REQUEST_TEMPLATE", "pull_request_template"].flatMap((name) => [
1012
+ `${name}.md`,
1013
+ `${name}.yaml`,
1014
+ `${name}.yml`
1015
+ ]);
1016
+ const FORGEJO_PROFILE = {
1017
+ forge: "forgejo",
1018
+ web: FORGEJO_WEB,
1019
+ headers: FORGEJO_HEADERS
1020
+ };
1021
+ const ISSUE_AND_PULL = {
1022
+ issue: true,
1023
+ pull_request: true
1024
+ };
1025
+ /** Forgejo versions with the Actions runs API, and with run jobs and job logs. */
1026
+ const FORGEJO_ACTION_RUNS = "12.0";
1027
+ const FORGEJO_ACTION_JOBS = "16.0";
1028
+ /** Gitea versions with runs and their jobs, and with job logs. */
1029
+ const GITEA_ACTION_RUNS = "1.25";
1030
+ const GITEA_ACTION_LOGS = "1.24";
1031
+ /** Gitea version with re-running the failed jobs of a run. */
1032
+ const GITEA_RERUN_FAILED = "1.26";
1033
+ /** Gitea version with replies to review comments. */
1034
+ const GITEA_REVIEW_REPLIES = "1.27";
1035
+ /** The Forgejo and Gitea version with activity feeds. */
1036
+ const ACTIVITY_FEEDS = "1.20";
1037
+ /** Forgejo and Gitea versions with blocking an account. */
1038
+ const FORGEJO_BLOCKS = "1.20";
1039
+ const GITEA_BLOCKS = "1.22";
1040
+ /** Gitea version with locking an issue or pull request. */
1041
+ const GITEA_LOCKS = "1.24";
1042
+ const GITEA_LOCK_REASONS = {
1043
+ off_topic: "Off-topic",
1044
+ too_heated: "Too heated",
1045
+ resolved: "Resolved",
1046
+ spam: "Spam"
1047
+ };
1048
+ /** Timelines send no usable count, so only a full page of an explicit size shows that another follows. */
1049
+ const TIMELINE_PAGE_SIZE = 50;
1050
+ /** Whether `user` has `login`, in any case; `true` when no login is wanted. Forgejo's issue search ignores `created_by` and `assigned_by`. */
1051
+ function sameLogin(user, login) {
1052
+ return !login || user?.login.toLowerCase() === login.toLowerCase();
1053
+ }
1054
+ /** The Forgejo implementation for one deployment family. Shared by `forgejo()` and `gitea()`. */
1055
+ function forgejoDefinition(profile) {
1056
+ return {
1057
+ forge: profile.forge,
1058
+ hasWeb: true,
1059
+ baseUrl: profile.web.baseUrl,
1060
+ anonymous: true,
1061
+ apiPath: profile.web.apiPath,
1062
+ headers: { accept: "application/json" },
1063
+ authHeaders: ({ options: { auth } }) => auth?.type === "token" ? async () => ({ authorization: `token ${await resolveToken(auth)}` }) : void 0,
1064
+ webhooks: forgejoWebhooks(profile),
1065
+ setup: (ctx) => setupForgejo(ctx, profile)
1066
+ };
1067
+ }
1068
+ function setupForgejo({ options, origin, fetcher: baseFetcher, baseUrl }, profile) {
1069
+ const context = origin;
1070
+ /** Collaborators, assignees, reviewers and permissions are served only to signed-in users. */
1071
+ const anonymous = options.auth?.type === "anonymous";
1072
+ const fetcher = countedPages(baseFetcher);
1073
+ const list = createListing(fetcher, "limit");
1074
+ /** Organisations are accounts too, so `/users/{owner}/repos` serves both. */
1075
+ function ownerReposPage(owner, query = {}) {
1076
+ return list(`/users/${encodeURIComponent(owner.owner)}/repos`, query, (raw) => toRepo(origin, raw), { warnings: isFirstPage(query.cursor) && ((query.sort ?? "created") !== "created" || query.direction === "desc") ? [{
1077
+ code: "sort_unsupported",
1078
+ message: `${profile.forge} lists the repositories of an owner oldest first only`
1079
+ }] : void 0 });
1080
+ }
1081
+ async function readUser(path, signal) {
1082
+ const { data } = await fetcher.json(path, { signal });
1083
+ return {
1084
+ ...toActor(origin, data),
1085
+ bio: data.description || void 0,
1086
+ location: data.location || void 0,
1087
+ websiteUrl: data.website || void 0,
1088
+ createdAt: toDate(data.created),
1089
+ followers: data.followers_count,
1090
+ following: data.following_count,
1091
+ raw: data
1092
+ };
1093
+ }
1094
+ function repoPath(repo) {
1095
+ return `/repos/${encodeURIComponent(repo.owner)}/${encodeURIComponent(repo.name)}`;
1096
+ }
1097
+ function threadPath(ref) {
1098
+ switch (ref.kind) {
1099
+ case "pull_request": return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1100
+ case "discussion": throw new UnsupportedOperationError(`${profile.forge} has no discussions`, context);
1101
+ default: return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1102
+ }
1103
+ }
1104
+ const currentUser = memo(() => fetcher.json("/user").then((result) => result.data));
1105
+ /**
1106
+ * An update or a deletion names the blob it replaces, so each directory the change touches is listed first,
1107
+ * at the commit the change builds on. A branch from `createFrom` is created before the commit.
1108
+ */
1109
+ async function commitFiles(repo, input, options) {
1110
+ const signal = options?.signal;
1111
+ const branchPath = `${repoPath(repo)}/branches/${input.branch.split("/").map(encodeURIComponent).join("/")}`;
1112
+ let head = input.expectedHead;
1113
+ if (input.createFrom !== void 0) {
1114
+ const { data } = await fetcher.json(`${repoPath(repo)}/branches`, {
1115
+ method: "POST",
1116
+ json: {
1117
+ new_branch_name: input.branch,
1118
+ old_ref_name: input.createFrom
1119
+ },
1120
+ signal
1121
+ });
1122
+ head = data.commit?.id;
1123
+ } else if (head !== void 0) {
1124
+ const { data } = await fetcher.json(branchPath, { signal });
1125
+ if (data.commit?.id !== head.toLowerCase()) throw new BranchMovedError(`${input.branch} is at ${data.commit?.id}, not ${head}`, 409, "", context);
1126
+ }
1127
+ try {
1128
+ const ref = head ?? input.branch;
1129
+ const existing = await existingFiles(input.changes, inDirectories(async (directory) => {
1130
+ try {
1131
+ const entries = await listDirectory(repo, directory, {
1132
+ ref,
1133
+ signal
1134
+ });
1135
+ return entries && new Map(entries.filter((entry) => entry.type === "file" || entry.type === "symlink").map((entry) => [entry.path, entry.sha]));
1136
+ } catch (error) {
1137
+ if (error instanceof NotFoundError) return;
1138
+ throw error;
1139
+ }
1140
+ }), context);
1141
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents`, {
1142
+ method: "POST",
1143
+ json: {
1144
+ branch: input.branch,
1145
+ message: input.message,
1146
+ ...input.author && { author: input.author },
1147
+ files: input.changes.map(({ path, content }) => content === null ? {
1148
+ operation: "delete",
1149
+ path,
1150
+ sha: existing.get(path)
1151
+ } : {
1152
+ operation: existing.has(path) ? "update" : "create",
1153
+ path,
1154
+ content: changeBase64(content),
1155
+ ...existing.has(path) && { sha: existing.get(path) }
1156
+ })
1157
+ },
1158
+ signal
1159
+ });
1160
+ return toFileCommit(repo, data.commit);
1161
+ } catch (error) {
1162
+ if (input.createFrom !== void 0) {
1163
+ if ((await fetcher.json(branchPath).catch(() => void 0))?.data.commit?.id === head) await fetcher.raw(branchPath, { method: "DELETE" }).catch(() => {});
1164
+ }
1165
+ throw error;
1166
+ }
1167
+ }
1168
+ /** Labels are addressed by id in writes, so names are resolved once per repo. */
1169
+ /** Forgejo and Gitea address reactions on issues and on comments with the same body. */
1170
+ function reactionPath(target) {
1171
+ return "thread" in target ? `${repoPath(target.thread.repo)}/issues/comments/${encodeURIComponent(target.id)}/reactions` : `${issuePath(requireIssueOrPull(target, context, "react to"))}/reactions`;
1172
+ }
1173
+ async function setReaction(target, reaction, method, options) {
1174
+ await fetcher.raw(reactionPath(target), {
1175
+ method,
1176
+ json: { content: reaction },
1177
+ signal: options?.signal
1178
+ });
1179
+ }
1180
+ const labelIdsOf = memoBy(async (path) => {
1181
+ const map = /* @__PURE__ */ new Map();
1182
+ for await (const label of fetcher.items(path, { query: { limit: 50 } })) map.set(label.name, label.id);
1183
+ return map;
1184
+ });
1185
+ /** Labels an organisation shares with its repositories; none for a user, whose `/orgs` route is a 404. */
1186
+ const orgLabelIdsOf = memoBy(async (owner) => {
1187
+ try {
1188
+ return await labelIdsOf(`/orgs/${encodeURIComponent(owner)}/labels`);
1189
+ } catch (error) {
1190
+ if (error instanceof NotFoundError) return /* @__PURE__ */ new Map();
1191
+ throw error;
1192
+ }
1193
+ });
1194
+ async function resolveLabels(repo, names) {
1195
+ const map = await labelIdsOf(`${repoPath(repo)}/labels`);
1196
+ const shared = names.some((name) => !map.has(name)) ? await orgLabelIdsOf(repo.owner) : void 0;
1197
+ return names.map((name) => {
1198
+ const id = map.get(name) ?? shared?.get(name);
1199
+ if (id === void 0) throw new UnsupportedOperationError(`No label named ${name} in ${repo.owner}/${repo.name}`, context);
1200
+ return id;
1201
+ });
1202
+ }
1203
+ async function notificationPage(listOptions = {}) {
1204
+ const result = await fetcher.json(listOptions.cursor?.nextUrl ?? "/notifications", {
1205
+ query: listOptions.cursor?.nextUrl ? void 0 : {
1206
+ all: listOptions.all ?? false,
1207
+ since: listOptions.since?.toISOString(),
1208
+ limit: listOptions.perPage
1209
+ },
1210
+ signal: listOptions.signal
1211
+ });
1212
+ return {
1213
+ items: (result.data ?? []).map((raw) => toNotification(origin, raw)),
1214
+ cursor: result.cursor,
1215
+ notModified: result.notModified,
1216
+ ...rateLimitPart(result.response)
1217
+ };
1218
+ }
1219
+ async function setStatus(ref, status, options) {
1220
+ await fetcher.raw(`/notifications/threads/${encodeURIComponent(ref.id)}`, {
1221
+ method: "PATCH",
1222
+ query: { "to-status": status },
1223
+ signal: options?.signal
1224
+ });
1225
+ }
1226
+ async function issueTarget(ref, { thread, signal }) {
1227
+ if (thread) {
1228
+ const resolved = requireThread(thread, context);
1229
+ if (resolved.kind !== "issue" && resolved.kind !== "pull_request") throw new UnsupportedOperationError("Only issue and pull request threads can be unsubscribed from", context);
1230
+ return {
1231
+ owner: resolved.repo.owner,
1232
+ name: resolved.repo.name,
1233
+ number: resolved.number
1234
+ };
1235
+ }
1236
+ const { data } = await fetcher.json(`/notifications/threads/${encodeURIComponent(ref.id)}`, { signal });
1237
+ const number = numberFromUrl(data.subject.url);
1238
+ if (!number || !toThreadKind(data.subject.type)) throw new UnsupportedOperationError("Only issue and pull request threads can be unsubscribed from", context);
1239
+ const [owner = "", name = ""] = data.repository.full_name.split("/");
1240
+ return {
1241
+ owner,
1242
+ name,
1243
+ number
1244
+ };
1245
+ }
1246
+ async function subscriptionPath(target) {
1247
+ const user = await currentUser();
1248
+ return `${repoPath(target)}/issues/${encodeURIComponent(target.number)}/subscriptions/${encodeURIComponent(user.login)}`;
1249
+ }
1250
+ async function unsubscribe(ref, writeOptions = {}) {
1251
+ await fetcher.raw(await subscriptionPath(await issueTarget(ref, writeOptions)), {
1252
+ method: "DELETE",
1253
+ signal: writeOptions.signal
1254
+ });
1255
+ }
1256
+ function issuePath(ref) {
1257
+ return `${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}`;
1258
+ }
1259
+ /** A pull request is edited through the pulls endpoint, whose response carries its branches and reviewers. */
1260
+ async function setState(thread, state, options) {
1261
+ const ref = requireIssueOrPull(thread, context, state === "open" ? "reopen" : "close");
1262
+ const { data } = await fetcher.json(ref.kind === "pull_request" ? threadPath(ref) : issuePath(ref), {
1263
+ method: "PATCH",
1264
+ json: { state },
1265
+ signal: options?.signal
1266
+ });
1267
+ return toThread(ref, data);
1268
+ }
1269
+ /** The merge response has no body, and a merge scheduled until checks pass responds with `201`. */
1270
+ async function merge(thread, mergeOptions = {}) {
1271
+ const ref = requireThread(thread, context);
1272
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only pull requests can be merged", context);
1273
+ const pull = `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1274
+ let method = mergeOptions.method;
1275
+ if (!method) {
1276
+ const { data: repo } = await fetcher.json(repoPath(ref.repo), { signal: mergeOptions.signal });
1277
+ method = soleMergeMethod({
1278
+ merge: repo.allow_merge_commits,
1279
+ rebase: repo.allow_rebase,
1280
+ rebase_merge: repo.allow_rebase_explicit,
1281
+ squash: repo.allow_squash_merge,
1282
+ fast_forward_only: repo.allow_fast_forward_only_merge
1283
+ }, context);
1284
+ }
1285
+ const response = await fetcher.raw(`${pull}/merge`, {
1286
+ method: "POST",
1287
+ json: {
1288
+ Do: method.replaceAll("_", "-"),
1289
+ MergeTitleField: mergeOptions.title,
1290
+ MergeMessageField: mergeOptions.message,
1291
+ head_commit_id: mergeOptions.sha,
1292
+ merge_when_checks_succeed: mergeOptions.whenChecksPass
1293
+ },
1294
+ mapError: toMergeError,
1295
+ signal: mergeOptions.signal
1296
+ });
1297
+ return { status: mergeOptions.whenChecksPass && response.status === 201 ? "queued" : "merged" };
1298
+ }
1299
+ /** The update takes no expected head, so `sha` is compared against a read of the pull request first. */
1300
+ async function updateBranch(thread, updateOptions = {}) {
1301
+ const ref = requirePull(thread, "updated");
1302
+ const { sha, signal } = updateOptions;
1303
+ if (sha !== void 0) {
1304
+ const { data } = await fetcher.json(pullPath(ref), { signal });
1305
+ if (data.head?.sha !== sha) throw new BranchMovedError(`Head branch of pull request ${ref.number} is at ${data.head?.sha}, not ${sha}`, 409, "", context);
1306
+ }
1307
+ await fetcher.raw(`${pullPath(ref)}/update`, {
1308
+ method: "POST",
1309
+ query: { style: updateOptions.method ?? "merge" },
1310
+ mapError: toMergeError,
1311
+ signal
1312
+ });
1313
+ return { status: "updated" };
1314
+ }
1315
+ const REVIEW_EVENTS = {
1316
+ approve: "APPROVED",
1317
+ request_changes: "REQUEST_CHANGES",
1318
+ comment: "COMMENT"
1319
+ };
1320
+ function requirePull(thread, action) {
1321
+ const ref = requireThread(thread, context);
1322
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only pull requests can be ${action}`, context);
1323
+ return ref;
1324
+ }
1325
+ function pullPath(ref) {
1326
+ return `${repoPath(ref.repo)}/pulls/${encodeURIComponent(ref.number)}`;
1327
+ }
1328
+ function reviewCommentInput(comments) {
1329
+ return comments?.map((comment) => ({
1330
+ path: comment.path,
1331
+ body: comment.body,
1332
+ ...comment.side === "left" ? { old_position: comment.line } : { new_position: comment.line }
1333
+ }));
1334
+ }
1335
+ async function createReview(thread, input, options) {
1336
+ const ref = requirePull(thread, "reviewed");
1337
+ const { data } = await fetcher.json(`${pullPath(ref)}/reviews`, {
1338
+ method: "POST",
1339
+ json: {
1340
+ event: input.event ? REVIEW_EVENTS[input.event] : void 0,
1341
+ body: input.body ?? "",
1342
+ comments: reviewCommentInput(input.comments)
1343
+ },
1344
+ signal: options?.signal
1345
+ });
1346
+ return toReview(ref, data, []);
1347
+ }
1348
+ async function get(thread, options) {
1349
+ const ref = requireThread(thread, context);
1350
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1351
+ const result = toThread(ref, data);
1352
+ if (ref.kind === "pull_request" && data.head?.sha) try {
1353
+ const checks = await statusChecks(ref.repo, data.head.sha, options?.signal);
1354
+ result.checks = summariseChecks(checks.map((check) => check.state));
1355
+ } catch (error) {
1356
+ if (!(error instanceof ForgeError)) throw error;
1357
+ result.warnings = [...result.warnings ?? [], toWarning("checks_unreadable", error, ref.number)];
1358
+ }
1359
+ return result;
1360
+ }
1361
+ const STATUS_STATES = {
1362
+ pending: "pending",
1363
+ success: "success",
1364
+ failure: "failure",
1365
+ neutral: "success",
1366
+ unknown: "pending"
1367
+ };
1368
+ async function statusChecks(repo, sha, signal) {
1369
+ const { data } = await fetcher.json(`${repoPath(repo)}/commits/${sha}/status`, { signal });
1370
+ return toStatusChecks(repo, data);
1371
+ }
1372
+ function milestonesPage(repo, listOptions = {}) {
1373
+ return list(`${repoPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: { state: listOptions.state ?? "open" } });
1374
+ }
1375
+ async function releasesPage(repo, listOptions = {}) {
1376
+ return list(`${repoPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
1377
+ }
1378
+ async function writeRelease(repo, path, method, input, options) {
1379
+ const { data } = await fetcher.json(path, {
1380
+ method,
1381
+ json: {
1382
+ tag_name: input.tag,
1383
+ target_commitish: input.target,
1384
+ name: input.name,
1385
+ body: input.body,
1386
+ draft: input.draft,
1387
+ prerelease: input.prerelease
1388
+ },
1389
+ signal: options?.signal
1390
+ });
1391
+ return toRelease(repo, method === "POST" ? {
1392
+ ...data,
1393
+ assets: []
1394
+ } : data);
1395
+ }
1396
+ async function listPage(repo, query = {}) {
1397
+ const warnings = [];
1398
+ if (query.kind === "discussion") return {
1399
+ items: [],
1400
+ warnings: [{
1401
+ code: "kind_unsupported",
1402
+ message: `${profile.forge} has no discussions`
1403
+ }]
1404
+ };
1405
+ const sort = query.sort ?? "created";
1406
+ const direction = query.direction ?? "desc";
1407
+ if (isFirstPage(query.cursor) && (sort !== "created" || direction !== "desc")) warnings.push({
1408
+ code: "sort_unsupported",
1409
+ message: `${profile.forge} lists repository issues newest first only`
1410
+ });
1411
+ const createdAfter = query.createdAfter?.getTime();
1412
+ const result = await fetcher.page(`${repoPath(repo)}/issues`, {
1413
+ query: {
1414
+ state: query.state === "merged" ? "closed" : query.state ?? "open",
1415
+ type: query.kind === "pull_request" ? "pulls" : query.kind === "issue" ? "issues" : void 0,
1416
+ labels: query.labels?.join(","),
1417
+ created_by: query.author,
1418
+ assigned_by: query.assignee,
1419
+ since: query.since?.toISOString(),
1420
+ limit: query.perPage
1421
+ },
1422
+ cursor: query.cursor,
1423
+ signal: query.signal
1424
+ });
1425
+ const older = (raw) => createdAfter !== void 0 && (Date.parse(raw.created_at ?? "") || 0) < createdAfter;
1426
+ const unmerged = (raw) => query.state === "merged" && !raw.pull_request?.merged;
1427
+ const page = toPage(result, (raw) => older(raw) || unmerged(raw) || !hasEveryLabel(raw.labels, query.labels) ? void 0 : toThread({
1428
+ ...origin,
1429
+ repo,
1430
+ kind: raw.pull_request ? "pull_request" : "issue",
1431
+ number: String(raw.number)
1432
+ }, raw), warnings);
1433
+ return (result.data ?? []).some(older) ? {
1434
+ ...page,
1435
+ cursor: void 0
1436
+ } : page;
1437
+ }
1438
+ /** Repository hooks, or organisation hooks for a namespace ref. */
1439
+ function hooksPath(target) {
1440
+ return isNamespaceRef(target) ? `/orgs/${encodeURIComponent(target.owner)}/hooks` : `${repoPath(target)}/hooks`;
1441
+ }
1442
+ async function searchThreadsPage(query) {
1443
+ const warnings = [];
1444
+ if (isFirstPage(query.cursor) && query.involves) warnings.push({
1445
+ code: "filter_unsupported",
1446
+ message: `${profile.forge} has no involves filter; it was ignored`
1447
+ });
1448
+ if (isFirstPage(query.cursor) && query.sort && query.sort !== "relevance") warnings.push({
1449
+ code: "sort_unsupported",
1450
+ message: `${profile.forge} searches issues newest first only`
1451
+ });
1452
+ const result = await fetcher.page("/repos/issues/search", {
1453
+ query: {
1454
+ q: query.text,
1455
+ type: query.kind === "pull_request" ? "pulls" : query.kind === "issue" ? "issues" : void 0,
1456
+ state: query.state ?? "all",
1457
+ labels: query.labels?.join(","),
1458
+ created_by: query.author,
1459
+ assigned_by: query.assignee,
1460
+ since: query.since?.toISOString(),
1461
+ owner: query.repo?.owner ?? query.owner,
1462
+ limit: query.perPage
1463
+ },
1464
+ cursor: query.cursor,
1465
+ signal: query.signal
1466
+ });
1467
+ return toPage(result, (raw) => {
1468
+ const [owner = "", name = ""] = raw.repository?.full_name.split("/") ?? [];
1469
+ const repo = query.repo ?? (name ? {
1470
+ ...origin,
1471
+ owner,
1472
+ name,
1473
+ externalId: raw.repository?.id === void 0 ? void 0 : String(raw.repository.id)
1474
+ } : void 0);
1475
+ if (!repo || !hasEveryLabel(raw.labels, query.labels) || !sameLogin(raw.user, query.author) || query.assignee && !raw.assignees?.some((user) => sameLogin(user, query.assignee)) || query.repo && raw.repository && raw.repository.full_name !== `${query.repo.owner}/${query.repo.name}`) return;
1476
+ return toThread({
1477
+ ...origin,
1478
+ repo,
1479
+ kind: raw.pull_request ? "pull_request" : "issue",
1480
+ number: String(raw.number)
1481
+ }, raw);
1482
+ }, warnings);
1483
+ }
1484
+ const isGitea = profile.forge === "gitea";
1485
+ /** Codeberg and gitea.com run a current release, so only a self-hosted instance waits for its version. */
1486
+ function released(minimum) {
1487
+ return hostOf(baseUrl) === hostOf(profile.web.baseUrl) ? true : ({ version }) => versionAtLeast(version, minimum);
1488
+ }
1489
+ function actions(forgejoMinimum, giteaMinimum) {
1490
+ return released(isGitea ? giteaMinimum : forgejoMinimum);
1491
+ }
1492
+ async function feedPage(path, listOptions, query) {
1493
+ const { toFeedEvent } = await import("./feed-DsC7Vws1-M_de2nSK.js");
1494
+ return list(path, listOptions, (raw) => toFeedEvent(origin, raw), { query });
1495
+ }
1496
+ async function setBlocked(scope, login, blocked, options) {
1497
+ const path = isGitea ? `${scope}/blocks/${encodeURIComponent(login)}` : `${scope}/${blocked ? "block" : "unblock"}/${encodeURIComponent(login)}`;
1498
+ await fetcher.raw(path, {
1499
+ method: isGitea && !blocked ? "DELETE" : "PUT",
1500
+ signal: options?.signal
1501
+ });
1502
+ }
1503
+ async function setLocked(thread, locked, options = {}) {
1504
+ const ref = requireThread(thread, context);
1505
+ await fetcher.raw(`${repoPath(ref.repo)}/issues/${encodeURIComponent(ref.number)}/lock`, {
1506
+ method: locked ? "PUT" : "DELETE",
1507
+ ...locked ? { json: options.reason ? { lock_reason: GITEA_LOCK_REASONS[options.reason] } : {} } : {},
1508
+ signal: options.signal
1509
+ });
1510
+ }
1511
+ /** Gitea lists runs and serves job logs only with a token. */
1512
+ const giteaAnonymous = isGitea && anonymous;
1513
+ /** Team ids of an organisation by lowercased name, which Forgejo and Gitea keep unique. */
1514
+ const teamIdsOf = memoBy(async (org) => {
1515
+ const map = /* @__PURE__ */ new Map();
1516
+ for await (const team of fetcher.items(`/orgs/${encodeURIComponent(org)}/teams`)) map.set(team.name.toLowerCase(), team.id);
1517
+ return map;
1518
+ });
1519
+ /** One page of an Actions listing, read from `key` and continued from `total_count` when no `Link` header is sent. */
1520
+ async function actionsPage(path, key, query, pageOptions) {
1521
+ const url = pageOptions.cursor?.nextUrl ? fetcher.resolve(pageOptions.cursor.nextUrl) : fetcher.resolve(path, query);
1522
+ return fetcher.page(path, {
1523
+ query,
1524
+ cursor: pageOptions.cursor,
1525
+ signal: pageOptions.signal,
1526
+ select: (body, next) => {
1527
+ const listing = body;
1528
+ const items = listing[key] ?? [];
1529
+ return {
1530
+ items,
1531
+ next: next ?? countedNextUrl(url, items.length, listing.total_count === void 0 ? null : String(listing.total_count)),
1532
+ ...listing.total_count !== void 0 ? { total: listing.total_count } : {}
1533
+ };
1534
+ }
1535
+ });
1536
+ }
1537
+ async function runsPage(repo, query = {}) {
1538
+ const states = isGitea ? GITEA_ACTION_STATES : ACTION_STATES;
1539
+ const statuses = query.state ? `?${states[query.state].map((status) => `status=${status}`).join("&")}` : "";
1540
+ const path = `${repoPath(repo)}/actions/runs${statuses}`;
1541
+ if (isGitea) return toPage(await actionsPage(path, "workflow_runs", {
1542
+ branch: query.branch,
1543
+ page: 1,
1544
+ limit: query.perPage ?? 50
1545
+ }, query), (raw) => toGiteaActionRun(repo, raw));
1546
+ const result = await actionsPage(path, "workflow_runs", {
1547
+ ref: query.branch ? `refs/heads/${query.branch}` : void 0,
1548
+ page: 1,
1549
+ limit: query.perPage ?? 50
1550
+ }, query);
1551
+ return toPage(result, (raw) => query.branch && actionBranch(raw) !== query.branch ? void 0 : toActionRun(repo, raw));
1552
+ }
1553
+ async function jobsPage(ref, listOptions = {}) {
1554
+ const path = `${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/jobs`;
1555
+ if (isGitea) return toPage(await actionsPage(path, "jobs", {
1556
+ page: 1,
1557
+ limit: listOptions.perPage ?? 50
1558
+ }, listOptions), (raw) => toGiteaActionJob(ref, raw));
1559
+ const { data, response } = await fetcher.json(path, { signal: listOptions.signal });
1560
+ return {
1561
+ items: (data ?? []).map((raw) => toActionJob(ref, raw)),
1562
+ ...rateLimitPart(response)
1563
+ };
1564
+ }
1565
+ async function searchReposPage(query) {
1566
+ const result = await fetcher.page("/repos/search", {
1567
+ query: {
1568
+ q: query.text,
1569
+ owner: query.owner,
1570
+ sort: query.sort === "stars" ? "stars" : query.sort === "created" ? "created" : query.sort === "updated" ? "updated" : void 0,
1571
+ order: query.direction,
1572
+ limit: query.perPage
1573
+ },
1574
+ cursor: query.cursor,
1575
+ signal: query.signal,
1576
+ select: (body, next) => ({
1577
+ items: body.data,
1578
+ next
1579
+ })
1580
+ });
1581
+ return toPage(result, (raw) => toRepo(origin, raw));
1582
+ }
1583
+ async function templates(repo, options = {}) {
1584
+ const [issues, pulls] = await Promise.all([options.kind === "pull_request" ? [] : issueTemplates(repo, options.signal), options.kind === "issue" ? [] : pullTemplate(repo, options.signal)]);
1585
+ return [...issues, ...pulls];
1586
+ }
1587
+ /** The API parses each template but drops its front matter and a form's YAML, so the file gets read too. */
1588
+ async function issueTemplates(repo, signal) {
1589
+ const { data } = await fetcher.json(`${repoPath(repo)}/issue_templates`, { signal });
1590
+ return mapConcurrent(data ?? [], 4, async (raw) => ({
1591
+ kind: "issue",
1592
+ name: raw.name,
1593
+ path: raw.file_name,
1594
+ format: YAML_FILE.test(raw.file_name) ? "form" : "markdown",
1595
+ body: await readText(repo, raw.file_name, signal),
1596
+ title: raw.title || void 0,
1597
+ about: raw.about || void 0,
1598
+ labels: raw.labels?.length ? raw.labels : void 0,
1599
+ fields: raw.body?.map((field) => ({
1600
+ type: field.type,
1601
+ id: field.id || void 0,
1602
+ attributes: field.attributes ?? {},
1603
+ validations: field.validations ?? void 0
1604
+ })),
1605
+ raw
1606
+ }));
1607
+ }
1608
+ /** No API for pull request templates, so this finds the one file the web UI would pick. */
1609
+ async function pullTemplate(repo, signal) {
1610
+ const directories = PULL_TEMPLATE_DIRECTORIES[isGitea ? "gitea" : "forgejo"];
1611
+ const root = await listDirectory(repo, "", { signal }) ?? [];
1612
+ const pick = (entries) => PULL_TEMPLATE_FILES.map((name) => entries.find((entry) => entry.type === "file" && entry.name === name)).find(Boolean);
1613
+ const inRoot = pick(root);
1614
+ const nested = inRoot ? [] : await Promise.all(directories.filter((directory) => directory && root.some((entry) => entry.type === "dir" && entry.name === directory)).map(async (directory) => await listDirectory(repo, directory, { signal }) ?? []));
1615
+ const entry = inRoot ?? nested.map(pick).find(Boolean);
1616
+ if (!entry) return [];
1617
+ return [{
1618
+ kind: "pull_request",
1619
+ name: entry.name,
1620
+ path: entry.path,
1621
+ format: YAML_FILE.test(entry.name) ? "form" : "markdown",
1622
+ body: await readText(repo, entry.path, signal),
1623
+ raw: entry
1624
+ }];
1625
+ }
1626
+ async function readText(repo, path, signal) {
1627
+ return (await readFile(repo, path, {
1628
+ as: "text",
1629
+ signal
1630
+ })).content;
1631
+ }
1632
+ /** The entries of a directory, `''` for the root, or `undefined` when the path names a file. */
1633
+ async function listDirectory(repo, directory, options = {}) {
1634
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents${directory ? `/${directory.split("/").map(encodeURIComponent).join("/")}` : ""}`, {
1635
+ query: { ref: options.ref },
1636
+ signal: options.signal
1637
+ });
1638
+ return Array.isArray(data) ? data : void 0;
1639
+ }
1640
+ /** Large files come back with a null `content`, so they come from the raw endpoint, which has no size limit. */
1641
+ async function readFile(repo, path, fileOptions = {}) {
1642
+ const encoded = path.split("/").map(encodeURIComponent).join("/");
1643
+ if (fileOptions.metadata === false) {
1644
+ const response = await fetcher.raw(`${repoPath(repo)}/raw/${encoded}`, {
1645
+ query: { ref: fileOptions.ref },
1646
+ signal: fileOptions.signal
1647
+ });
1648
+ const bytes = new Uint8Array(await response.arrayBuffer());
1649
+ return toFileContent(bytes, {
1650
+ path,
1651
+ size: bytes.byteLength
1652
+ }, fileOptions, context);
1653
+ }
1654
+ const { data } = await fetcher.json(`${repoPath(repo)}/contents/${encoded}`, {
1655
+ query: { ref: fileOptions.ref },
1656
+ signal: fileOptions.signal
1657
+ });
1658
+ const file = {
1659
+ path: data.path,
1660
+ sha: data.sha,
1661
+ size: data.size,
1662
+ url: data.html_url ?? void 0
1663
+ };
1664
+ if (data.encoding === "base64" && data.content) return toFileContent(fromBase64(data.content), file, fileOptions, context);
1665
+ const response = await fetcher.raw(`${repoPath(repo)}/raw/${encoded}`, {
1666
+ query: { ref: fileOptions.ref },
1667
+ signal: fileOptions.signal
1668
+ });
1669
+ return toFileContent(new Uint8Array(await response.arrayBuffer()), file, fileOptions, context);
1670
+ }
1671
+ return {
1672
+ traits: {
1673
+ eventKinds: "native",
1674
+ authKinds: ["token", "anonymous"]
1675
+ },
1676
+ notApplicable: [
1677
+ ...isGitea ? [] : ["threads.lock"],
1678
+ "threads.hideComment",
1679
+ "threads.resolveReviewThread",
1680
+ "repos.issueTypes",
1681
+ "threads.setIssueType",
1682
+ "checks.rerun",
1683
+ "webhooks.deliveries",
1684
+ "webhooks.redeliver"
1685
+ ],
1686
+ search: {
1687
+ threadsPage: verb(true, searchThreadsPage),
1688
+ reposPage: verb(true, searchReposPage)
1689
+ },
1690
+ probeVersion: async () => (await fetcher.json("/version")).data.version,
1691
+ users: {
1692
+ get: verb(true, (login, options) => readUser(`/users/${encodeURIComponent(login)}`, options?.signal)),
1693
+ me: verb(true, (options) => readUser("/user", options?.signal)),
1694
+ eventsPage: verb(released(ACTIVITY_FEEDS), (login, listOptions = {}) => feedPage(`/users/${encodeURIComponent(login)}/activities/feeds`, listOptions, { "only-performed-by": true })),
1695
+ blocking: verb(released(isGitea ? GITEA_BLOCKS : FORGEJO_BLOCKS), {
1696
+ block: (login, options) => setBlocked("/user", login, true, options),
1697
+ unblock: (login, options) => setBlocked("/user", login, false, options)
1698
+ })
1699
+ },
1700
+ repos: {
1701
+ get: verb(true, async (ref, options) => toRepo(origin, (await fetcher.json(repoPath(ref), { signal: options?.signal })).data)),
1702
+ listPage: verb(true, (listOptions = {}) => list("/user/repos", listOptions, (raw) => toRepo(origin, raw))),
1703
+ byOwnerPage: verb(true, ownerReposPage),
1704
+ labelsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/labels`, listOptions, toLabel)),
1705
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${repoPath(repo)}/labels`, {
1706
+ method: "POST",
1707
+ json: {
1708
+ name: label.name,
1709
+ color: hexColour(label.colour, "#"),
1710
+ description: label.description
1711
+ },
1712
+ signal: options?.signal
1713
+ })).data)),
1714
+ milestonesPage: verb(true, milestonesPage),
1715
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/collaborators`, listOptions, (raw) => ({
1716
+ actor: toActor(origin, raw),
1717
+ role: "read",
1718
+ raw
1719
+ }))),
1720
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
1721
+ const { data } = await fetcher.json(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}/permission`, { signal: options?.signal });
1722
+ return toRole(data.role_name ?? data.permission);
1723
+ }),
1724
+ branchRules: verb(true, async (repo, name, options) => toBranchRules((await fetcher.json(`${repoPath(repo)}/branches/${name.split("/").map(encodeURIComponent).join("/")}`, { signal: options?.signal })).data)),
1725
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
1726
+ await fetcher.raw(`${repoPath(repo)}/collaborators/${encodeURIComponent(actorLogin(actor))}`, {
1727
+ method: "PUT",
1728
+ json: { permission: role === "admin" ? "admin" : role === "read" || role === "triage" ? "read" : "write" },
1729
+ signal: options?.signal
1730
+ });
1731
+ return { status: "added" };
1732
+ }),
1733
+ assignableUsersPage: verb(!anonymous, (repo, listOptions = {}) => list(`${repoPath(repo)}/assignees`, listOptions, (raw) => toActor(origin, raw))),
1734
+ reviewerCandidatesPage: verb(!anonymous, (thread, listOptions = {}) => list(`${repoPath(requireThread(thread, context).repo)}/reviewers`, listOptions, (raw) => toActor(origin, raw))),
1735
+ templates: verb(true, templates),
1736
+ eventsPage: verb(released(ACTIVITY_FEEDS), (repo, listOptions = {}) => feedPage(`${repoPath(repo)}/activities/feeds`, listOptions))
1737
+ },
1738
+ orgs: {
1739
+ teamsPage: verb(!anonymous, (org, listOptions = {}) => list(`/orgs/${encodeURIComponent(org.owner)}/teams`, listOptions, (raw) => toTeam(origin, teamOrg(org), raw))),
1740
+ teamMembersPage: verb(!anonymous, async (team, listOptions = {}) => {
1741
+ const id = team.id ?? (await teamIdsOf(team.org.owner)).get(team.slug.toLowerCase());
1742
+ if (id === void 0) throw new NotFoundError(`${team.org.owner} has no team named ${team.slug}`, 404, "", context);
1743
+ return list(`/teams/${encodeURIComponent(id)}/members`, listOptions, (raw) => toActor(origin, raw));
1744
+ }),
1745
+ blocking: verb(released(isGitea ? GITEA_BLOCKS : FORGEJO_BLOCKS), {
1746
+ block: (org, login, options) => setBlocked(`/orgs/${encodeURIComponent(org.owner)}`, login, true, options),
1747
+ unblock: (org, login, options) => setBlocked(`/orgs/${encodeURIComponent(org.owner)}`, login, false, options)
1748
+ })
1749
+ },
1750
+ notifications: {
1751
+ listPage: verb(true, notificationPage),
1752
+ markRead: verb(true, (ref, options) => setStatus(ref, "read", options)),
1753
+ markDone: verb("emulated", (ref, writeOptions) => setStatus(ref, "read", writeOptions)),
1754
+ unsubscribe: verb(true, unsubscribe),
1755
+ markAllRead: verb(true, async (bulk = {}) => {
1756
+ await fetcher.raw(bulk.repo ? `${repoPath(bulk.repo)}/notifications` : "/notifications", {
1757
+ method: "PUT",
1758
+ query: {
1759
+ "last_read_at": bulk.before?.toISOString(),
1760
+ "to-status": "read"
1761
+ },
1762
+ signal: bulk.signal
1763
+ });
1764
+ }),
1765
+ unreadCount: verb(true, async (options) => (await fetcher.json("/notifications/new", { signal: options?.signal })).data.new)
1766
+ },
1767
+ checks: {
1768
+ list: verb(true, async (repo, sha, options) => ({ items: await statusChecks(repo, sha, options?.signal) })),
1769
+ report: verb(true, async (repo, sha, input, options) => toStatusCheck(repo, (await fetcher.json(`${repoPath(repo)}/statuses/${sha}`, {
1770
+ method: "POST",
1771
+ json: {
1772
+ state: STATUS_STATES[input.state],
1773
+ context: input.name,
1774
+ description: input.description,
1775
+ target_url: input.url
1776
+ },
1777
+ signal: options?.signal
1778
+ })).data))
1779
+ },
1780
+ ci: {
1781
+ runsPage: verb(giteaAnonymous ? false : actions(FORGEJO_ACTION_RUNS, GITEA_ACTION_RUNS), runsPage),
1782
+ getRun: verb(actions(FORGEJO_ACTION_RUNS, GITEA_ACTION_RUNS), async (ref, options) => {
1783
+ const path = `${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}`;
1784
+ return isGitea ? toGiteaActionRun(ref.repo, (await fetcher.json(path, { signal: options?.signal })).data) : toActionRun(ref.repo, (await fetcher.json(path, { signal: options?.signal })).data);
1785
+ }),
1786
+ jobsPage: verb(actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_RUNS), jobsPage),
1787
+ getJob: verb(isGitea && (anonymous ? "unverified" : actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_RUNS)), async (ref, options) => {
1788
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
1789
+ const run = ref.run ?? (data.run_id === void 0 ? void 0 : {
1790
+ ...origin,
1791
+ repo: ref.repo,
1792
+ id: String(data.run_id)
1793
+ });
1794
+ if (!run) throw new UnsupportedOperationError(`Gitea returned job ${ref.id} without its run, and the ref names no run`, context);
1795
+ return toGiteaActionJob(run, data);
1796
+ }),
1797
+ log: verb(giteaAnonymous ? false : actions(FORGEJO_ACTION_JOBS, GITEA_ACTION_LOGS), async (ref, options) => (await fetcher.stream(`${repoPath(ref.repo)}/actions/jobs/${encodeURIComponent(ref.id)}/logs`, { signal: options?.signal })).body),
1798
+ rerunFailed: verb(isGitea && released(GITEA_RERUN_FAILED), async (ref, options) => {
1799
+ await fetcher.raw(`${repoPath(ref.repo)}/actions/runs/${encodeURIComponent(ref.id)}/rerun-failed-jobs`, {
1800
+ method: "POST",
1801
+ signal: options?.signal
1802
+ });
1803
+ })
1804
+ },
1805
+ contents: {
1806
+ getFile: verb(true, readFile),
1807
+ treePage: verb(true, async (repo, treeOptions = {}) => {
1808
+ const ref = treeOptions.ref ?? "HEAD";
1809
+ const { data, response } = await fetcher.json(`${repoPath(repo)}/git/trees/${encodeURIComponent(ref)}`, {
1810
+ query: {
1811
+ recursive: treeOptions.recursive ? "true" : void 0,
1812
+ per_page: treeOptions.perPage
1813
+ },
1814
+ signal: treeOptions.signal
1815
+ });
1816
+ const prefix = treeOptions.path?.replace(/^\/|\/$/g, "");
1817
+ const entries = (data.tree ?? []).filter((entry) => !prefix || entry.path.startsWith(`${prefix}/`));
1818
+ const warnings = data.truncated ? [{
1819
+ code: "tree_truncated",
1820
+ message: `${profile.forge} truncated the tree; read it directory by directory instead`,
1821
+ subject: ref
1822
+ }] : [];
1823
+ return toPage({
1824
+ data: entries,
1825
+ response,
1826
+ notModified: false
1827
+ }, toTreeEntry, warnings);
1828
+ }),
1829
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/branches`, listOptions, toBranch)),
1830
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${repoPath(repo)}/tags`, listOptions, toTag)),
1831
+ resolveRef: verb(true, async (repo, ref, options) => {
1832
+ const { data } = await fetcher.json(`${repoPath(repo)}/commits`, {
1833
+ query: {
1834
+ sha: ref,
1835
+ limit: 1,
1836
+ stat: "false"
1837
+ },
1838
+ signal: options?.signal
1839
+ });
1840
+ const sha = data[0]?.sha;
1841
+ if (!sha) throw new NotFoundError(`${profile.forge} has no commit for ${ref}`, 404, "", context);
1842
+ return sha;
1843
+ }),
1844
+ compare: verb(true, async (repo, base, head, options) => {
1845
+ const { data } = await fetcher.json(`${repoPath(repo)}/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`, {
1846
+ query: { files: options?.files === false ? false : void 0 },
1847
+ signal: options?.signal
1848
+ });
1849
+ return {
1850
+ base,
1851
+ head,
1852
+ aheadBy: data.total_commits ?? data.commits?.length,
1853
+ commits: (data.commits ?? []).map((raw) => toCommit(repo, raw)),
1854
+ files: (data.files ?? []).map(toChangedFile),
1855
+ raw: data
1856
+ };
1857
+ }),
1858
+ commitFiles: verb(true, commitFiles)
1859
+ },
1860
+ commits: {
1861
+ listPage: verb(true, (repo, query = {}) => list(`${repoPath(repo)}/commits`, query, (raw) => toCommit(repo, raw), { query: {
1862
+ sha: query.ref,
1863
+ path: query.path,
1864
+ since: query.since?.toISOString(),
1865
+ until: query.until?.toISOString()
1866
+ } })),
1867
+ get: verb(true, async ({ repo, sha }, options) => toCommit(repo, (await fetcher.json(`${repoPath(repo)}/git/commits/${sha}`, {
1868
+ query: {
1869
+ stat: "true",
1870
+ files: "true"
1871
+ },
1872
+ signal: options?.signal
1873
+ })).data))
1874
+ },
1875
+ releases: {
1876
+ listPage: verb(true, releasesPage),
1877
+ get: verb(true, async (ref, options) => toRelease(ref.repo, (await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data)),
1878
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/tags/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
1879
+ downloadAsset: verb(true, async (ref, downloadOptions = {}) => {
1880
+ const { data } = await fetcher.json(`${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.release.id)}/assets/${encodeURIComponent(ref.id)}`, { signal: downloadOptions.signal });
1881
+ return (await fetcher.stream(data.browser_download_url, { signal: downloadOptions.signal })).body;
1882
+ }),
1883
+ latest: verb(true, async (repo, options) => {
1884
+ try {
1885
+ return toRelease(repo, (await fetcher.json(`${repoPath(repo)}/releases/latest`, { signal: options?.signal })).data);
1886
+ } catch (error) {
1887
+ if (error instanceof NotFoundError) return;
1888
+ throw error;
1889
+ }
1890
+ }),
1891
+ create: verb(true, (repo, input, options) => writeRelease(repo, `${repoPath(repo)}/releases`, "POST", input, options)),
1892
+ update: verb(true, (ref, update, options) => writeRelease(ref.repo, `${repoPath(ref.repo)}/releases/${encodeURIComponent(ref.id)}`, "PATCH", update, options))
1893
+ },
1894
+ threads: {
1895
+ checks: perKind({ pull_request: true }, async (thread, options) => {
1896
+ const ref = requireThread(thread, context);
1897
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1898
+ return { items: data.head?.sha ? await statusChecks(ref.repo, data.head.sha, options?.signal) : [] };
1899
+ }),
1900
+ reviewsPage: verb(true, async (thread, listOptions = {}) => {
1901
+ const ref = requirePull(thread, "reviewed");
1902
+ const result = await fetcher.page(`${pullPath(ref)}/reviews`, {
1903
+ query: { limit: listOptions.perPage },
1904
+ cursor: listOptions.cursor,
1905
+ signal: listOptions.signal,
1906
+ conditional: false
1907
+ });
1908
+ return {
1909
+ items: await Promise.all((result.data ?? []).map(async (raw) => {
1910
+ const comments = raw.comments_count === 0 ? [] : (await fetcher.json(`${pullPath(ref)}/reviews/${encodeURIComponent(raw.id)}/comments`, { signal: listOptions.signal })).data ?? [];
1911
+ return toReview(ref, raw, comments.map((comment) => toReviewComment(ref, comment)));
1912
+ })),
1913
+ cursor: result.cursor,
1914
+ ...rateLimitPart(result.response)
1915
+ };
1916
+ }),
1917
+ getReview: verb(true, async (ref, options) => {
1918
+ const pull = requirePull(ref.thread, "reviewed");
1919
+ const { data } = await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
1920
+ return toReview(pull, data, (data.comments_count === 0 ? [] : (await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}/comments`, { signal: options?.signal })).data ?? []).map((comment) => toReviewComment(pull, comment)));
1921
+ }),
1922
+ filesPage: verb(true, (ref, listOptions = {}) => list(`${pullPath(requirePull(ref, "read for changed files"))}/files`, listOptions, toChangedFile)),
1923
+ commitsPage: verb(true, (ref, listOptions = {}) => list(`${pullPath(requirePull(ref, "read for commits"))}/commits`, listOptions, (raw) => toCommit(ref.repo, raw))),
1924
+ createReview: verb(true, createReview),
1925
+ submitReview: verb(true, async (ref, event, body, options) => {
1926
+ const pull = requirePull(ref.thread, "reviewed");
1927
+ const { data } = await fetcher.json(`${pullPath(pull)}/reviews/${encodeURIComponent(ref.id)}`, {
1928
+ method: "POST",
1929
+ json: {
1930
+ event: REVIEW_EVENTS[event],
1931
+ body: body ?? ""
1932
+ },
1933
+ signal: options?.signal
1934
+ });
1935
+ return toReview(pull, data, []);
1936
+ }),
1937
+ replyToReviewComment: verb(isGitea ? released(GITEA_REVIEW_REPLIES) : "not_applicable", async (thread, comment, body, options) => {
1938
+ const pull = requirePull(thread, "reviewed");
1939
+ if (comment.ref === void 0) throw new UnsupportedOperationError(`${profile.forge} replies to a review comment by its id; pass the comment with its \`ref\``, context);
1940
+ const { data } = await fetcher.json(`${pullPath(pull)}/comments/${encodeURIComponent(comment.ref.id)}/replies`, {
1941
+ method: "POST",
1942
+ json: { body },
1943
+ signal: options?.signal
1944
+ });
1945
+ return toReviewComment(pull, data);
1946
+ }),
1947
+ get: perKind(ISSUE_AND_PULL, get),
1948
+ getMany: verb(true, (refs, options) => getManyConcurrently(refs, get, options)),
1949
+ listPage: perKind(ISSUE_AND_PULL, listPage),
1950
+ eventsPage: verb(true, async (thread, listOptions = {}) => {
1951
+ const ref = requireThread(thread, context);
1952
+ return list(`${issuePath(ref)}/timeline`, {
1953
+ perPage: TIMELINE_PAGE_SIZE,
1954
+ ...listOptions
1955
+ }, (entry) => toEvent(ref, entry));
1956
+ }),
1957
+ commentsPage: perKind(ISSUE_AND_PULL, async (thread, listOptions = {}) => {
1958
+ const ref = requireIssueOrPull(thread, context, "list comments on");
1959
+ return list(`${issuePath(ref)}/comments`, listOptions, (raw) => toComment(ref, raw), { query: { since: listOptions.since?.toISOString() } });
1960
+ }),
1961
+ getComment: perKind(ISSUE_AND_PULL, async (ref, options) => {
1962
+ const thread = requireThread(ref.thread, context);
1963
+ const { data } = await fetcher.json(`${repoPath(thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
1964
+ if (!data) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
1965
+ return toComment(thread, data);
1966
+ }),
1967
+ createComment: perKind({
1968
+ issue: true,
1969
+ pull_request: true
1970
+ }, async (thread, body, options) => {
1971
+ const ref = requireIssueOrPull(thread, context, "comment on");
1972
+ const { data } = await fetcher.json(`${issuePath(ref)}/comments`, {
1973
+ method: "POST",
1974
+ json: { body },
1975
+ signal: options?.signal
1976
+ });
1977
+ return toComment(ref, data);
1978
+ }),
1979
+ updateComment: perKind({
1980
+ issue: true,
1981
+ pull_request: true
1982
+ }, async (ref, body, options) => {
1983
+ const thread = requireThread(ref.thread, context);
1984
+ const { data } = await fetcher.json(`${repoPath(thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, {
1985
+ method: "PATCH",
1986
+ json: { body },
1987
+ signal: options?.signal
1988
+ });
1989
+ return toComment(thread, data);
1990
+ }),
1991
+ deleteComment: perKind({
1992
+ issue: true,
1993
+ pull_request: true
1994
+ }, async (ref, options) => {
1995
+ await fetcher.raw(`${repoPath(ref.thread.repo)}/issues/comments/${encodeURIComponent(ref.id)}`, {
1996
+ method: "DELETE",
1997
+ signal: options?.signal
1998
+ });
1999
+ }),
2000
+ create: perKind({
2001
+ issue: true,
2002
+ pull_request: true
2003
+ }, async (repo, input, options) => {
2004
+ const labels = input.labels?.length ? await resolveLabels(repo, input.labels) : void 0;
2005
+ const assignees = input.assignees?.map(actorLogin);
2006
+ if (input.kind === "issue") {
2007
+ const { data } = await fetcher.json(`${repoPath(repo)}/issues`, {
2008
+ method: "POST",
2009
+ json: {
2010
+ title: input.title,
2011
+ body: input.body,
2012
+ labels,
2013
+ assignees
2014
+ },
2015
+ signal: options?.signal
2016
+ });
2017
+ return toThread({
2018
+ ...origin,
2019
+ repo,
2020
+ kind: "issue",
2021
+ number: String(data.number)
2022
+ }, data);
2023
+ }
2024
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a pull request needs head and base branches", context);
2025
+ const { data } = await fetcher.json(`${repoPath(repo)}/pulls`, {
2026
+ method: "POST",
2027
+ json: {
2028
+ title: input.draft ? `WIP: ${input.title}` : input.title,
2029
+ body: input.body,
2030
+ head: input.head,
2031
+ base: input.base,
2032
+ labels,
2033
+ assignees
2034
+ },
2035
+ signal: options?.signal
2036
+ });
2037
+ return toThread({
2038
+ ...origin,
2039
+ repo,
2040
+ kind: "pull_request",
2041
+ number: String(data.number)
2042
+ }, data);
2043
+ }),
2044
+ /** An issue edit takes no labels, so an issue's labels are set first and the edit response includes them. */
2045
+ update: perKind({
2046
+ issue: true,
2047
+ pull_request: true
2048
+ }, async (thread, input, options) => {
2049
+ const ref = requireIssueOrPull(thread, context, "update");
2050
+ const labels = input.labels && await resolveLabels(ref.repo, input.labels);
2051
+ const pull = ref.kind === "pull_request";
2052
+ if (labels && !pull) await fetcher.raw(`${issuePath(ref)}/labels`, {
2053
+ method: "PUT",
2054
+ json: { labels },
2055
+ signal: options?.signal
2056
+ });
2057
+ const json = {
2058
+ title: input.title,
2059
+ body: input.body,
2060
+ state: input.state,
2061
+ assignees: input.assignees?.map(actorLogin),
2062
+ labels: pull ? labels : void 0
2063
+ };
2064
+ const { data } = await fetcher.json(pull ? threadPath(ref) : issuePath(ref), {
2065
+ method: "PATCH",
2066
+ json,
2067
+ signal: options?.signal
2068
+ });
2069
+ return toThread(ref, data);
2070
+ }),
2071
+ addLabels: perKind({
2072
+ issue: true,
2073
+ pull_request: true
2074
+ }, async (thread, labels, options) => {
2075
+ const ref = requireIssueOrPull(thread, context, "label");
2076
+ return (await fetcher.json(`${issuePath(ref)}/labels`, {
2077
+ method: "POST",
2078
+ json: { labels: await resolveLabels(ref.repo, labels) },
2079
+ signal: options?.signal
2080
+ })).data.map(toLabel);
2081
+ }),
2082
+ /** The delete response has no body, so the labels are read afterwards. */
2083
+ removeLabels: perKind({
2084
+ issue: true,
2085
+ pull_request: true
2086
+ }, async (thread, labels, options) => {
2087
+ const ref = requireIssueOrPull(thread, context, "label");
2088
+ for (const id of await resolveLabels(ref.repo, labels)) await fetcher.raw(`${issuePath(ref)}/labels/${id}`, {
2089
+ method: "DELETE",
2090
+ signal: options?.signal
2091
+ });
2092
+ return (await fetcher.json(`${issuePath(ref)}/labels`, { signal: options?.signal })).data.map(toLabel);
2093
+ }),
2094
+ setMilestone: perKind({
2095
+ issue: true,
2096
+ pull_request: true
2097
+ }, async (thread, milestone, options) => {
2098
+ const ref = requireIssueOrPull(thread, context, "set the milestone of");
2099
+ const { data } = await fetcher.json(issuePath(ref), {
2100
+ method: "PATCH",
2101
+ json: { milestone: milestone === void 0 ? 0 : await milestoneId(milestone, (page) => milestonesPage(ref.repo, page), context, options) },
2102
+ signal: options?.signal
2103
+ });
2104
+ return toMilestone(data.milestone);
2105
+ }),
2106
+ reactionsPage: perKind(ISSUE_AND_PULL, async (target, listOptions = {}) => {
2107
+ const result = await fetcher.page(reactionPath(target), {
2108
+ query: { limit: listOptions.perPage },
2109
+ cursor: listOptions.cursor,
2110
+ signal: listOptions.signal
2111
+ });
2112
+ return toPage(result, (raw) => {
2113
+ const reactor = toActor(context, raw.user);
2114
+ return reactor && {
2115
+ content: reactionContent(raw.content),
2116
+ contentRaw: raw.content,
2117
+ actor: reactor,
2118
+ createdAt: toDate(raw.created_at),
2119
+ raw
2120
+ };
2121
+ });
2122
+ }),
2123
+ reactions: perKind({
2124
+ issue: true,
2125
+ pull_request: true
2126
+ }, {
2127
+ react: (target, reaction, options) => setReaction(target, reaction, "POST", options),
2128
+ unreact: (target, reaction, options) => setReaction(target, reaction, "DELETE", options)
2129
+ }),
2130
+ setLabels: perKind({
2131
+ issue: true,
2132
+ pull_request: true
2133
+ }, async (thread, labels, options) => {
2134
+ const ref = requireIssueOrPull(thread, context, "label");
2135
+ return (await fetcher.json(`${issuePath(ref)}/labels`, {
2136
+ method: "PUT",
2137
+ json: { labels: await resolveLabels(ref.repo, labels) },
2138
+ signal: options?.signal
2139
+ })).data.map(toLabel);
2140
+ }),
2141
+ setAssignees: perKind({
2142
+ issue: true,
2143
+ pull_request: true
2144
+ }, async (thread, assignees, options) => {
2145
+ const ref = requireIssueOrPull(thread, context, "assign");
2146
+ const { data } = await fetcher.json(issuePath(ref), {
2147
+ method: "PATCH",
2148
+ json: { assignees: assignees.map(actorLogin) },
2149
+ signal: options?.signal
2150
+ });
2151
+ return (data.assignees ?? []).flatMap((user) => toActor(context, user) ?? []);
2152
+ }),
2153
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
2154
+ await fetcher.raw(`${threadPath(requireThread(thread, context))}/requested_reviewers`, {
2155
+ method: "POST",
2156
+ json: { reviewers: reviewers.map(actorLogin) },
2157
+ signal: options?.signal
2158
+ });
2159
+ }),
2160
+ close: perKind({
2161
+ issue: true,
2162
+ pull_request: true
2163
+ }, (ref, options) => setState(ref, "closed", options)),
2164
+ reopen: perKind({
2165
+ issue: true,
2166
+ pull_request: true
2167
+ }, (ref, options) => setState(ref, "open", options)),
2168
+ ...isGitea ? { locking: perKind({
2169
+ issue: released(GITEA_LOCKS),
2170
+ pull_request: released(GITEA_LOCKS)
2171
+ }, {
2172
+ lock: (thread, options) => setLocked(thread, true, options),
2173
+ unlock: (thread, options) => setLocked(thread, false, options)
2174
+ }) } : {},
2175
+ merge: verb(true, merge),
2176
+ updateBranch: verb(true, updateBranch),
2177
+ subscriptions: perKind(ISSUE_AND_PULL, {
2178
+ async subscription(thread, options) {
2179
+ const ref = requireIssueOrPull(thread, context, "read the subscription of");
2180
+ const { data } = await fetcher.json(`${issuePath(ref)}/subscriptions/check`, { signal: options?.signal });
2181
+ return data.ignored ? "ignored" : data.subscribed ? "subscribed" : "none";
2182
+ },
2183
+ async subscribe(thread, options) {
2184
+ const ref = requireIssueOrPull(thread, context, "subscribe to");
2185
+ await fetcher.raw(await subscriptionPath({
2186
+ owner: ref.repo.owner,
2187
+ name: ref.repo.name,
2188
+ number: ref.number
2189
+ }), {
2190
+ method: "PUT",
2191
+ signal: options?.signal
2192
+ });
2193
+ },
2194
+ async unsubscribe(thread, options) {
2195
+ const ref = requireIssueOrPull(thread, context, "unsubscribe from");
2196
+ await fetcher.raw(await subscriptionPath({
2197
+ owner: ref.repo.owner,
2198
+ name: ref.repo.name,
2199
+ number: ref.number
2200
+ }), {
2201
+ method: "DELETE",
2202
+ signal: options?.signal
2203
+ });
2204
+ }
2205
+ })
2206
+ },
2207
+ web: profile.web.links({
2208
+ baseUrl,
2209
+ instance: origin.instance
2210
+ }),
2211
+ webhooks: {
2212
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw))),
2213
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
2214
+ method: "POST",
2215
+ json: {
2216
+ type: "gitea",
2217
+ active: input.active ?? true,
2218
+ events: nativeEventsFor(FORGEJO_NATIVE_EVENTS, input.events, input.nativeEvents),
2219
+ config: {
2220
+ url: input.url,
2221
+ content_type: input.contentType ?? "json",
2222
+ ...input.secret ? { secret: input.secret } : {}
2223
+ }
2224
+ },
2225
+ signal: options?.signal
2226
+ })).data)),
2227
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2228
+ method: "PATCH",
2229
+ json: {
2230
+ ...update.active === void 0 ? {} : { active: update.active },
2231
+ ...update.events || update.nativeEvents ? { events: nativeEventsFor(FORGEJO_NATIVE_EVENTS, update.events, update.nativeEvents) } : {},
2232
+ ...update.url || update.secret || update.contentType ? { config: {
2233
+ ...update.url ? { url: update.url } : {},
2234
+ content_type: update.contentType ?? "json",
2235
+ ...update.secret ? { secret: update.secret } : {}
2236
+ } } : {}
2237
+ },
2238
+ signal: options?.signal
2239
+ })).data)),
2240
+ delete: verb(true, async (ref, options) => {
2241
+ await fetcher.raw(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2242
+ method: "DELETE",
2243
+ signal: options?.signal
2244
+ });
2245
+ }),
2246
+ rotateSecret: verb(true, async (ref, secret, options) => {
2247
+ const current = toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, { signal: options?.signal })).data);
2248
+ const { data } = await fetcher.json(`${hooksPath(ref.target)}/${encodeURIComponent(ref.id)}`, {
2249
+ method: "PATCH",
2250
+ json: { config: {
2251
+ url: current.url,
2252
+ content_type: current.contentType ?? "json",
2253
+ secret
2254
+ } },
2255
+ signal: options?.signal
2256
+ });
2257
+ return toWebhook(ref.target, data);
2258
+ })
2259
+ },
2260
+ scopes: forgejoScopesFor
2261
+ };
2262
+ }
2263
+ /**
2264
+ * Forgejo and Gitea token scopes, which are per resource group with a
2265
+ * `read:` or `write:` prefix.
2266
+ */
2267
+ function forgejoScopesFor(verb) {
2268
+ const [group = "", name = ""] = verb.split(".");
2269
+ const write = WRITE_VERBS.has(verb);
2270
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : { token: ["write:repository", "write:organization"] };
2271
+ if (group === "notifications") return { token: [name === "list" || name === "page" || name === "unreadCount" ? "read:notification" : "write:notification"] };
2272
+ if (group === "users" || group === "search") return { token: [write ? "write:user" : "read:user"] };
2273
+ if (group === "orgs") return { token: [write ? "write:organization" : "read:organization"] };
2274
+ if (group === "threads" || group === "repos" || group === "contents" || group === "releases" || group === "checks" || group === "ci") return { token: [write ? "write:issue" : "read:issue", write ? "write:repository" : "read:repository"] };
2275
+ return {};
2276
+ }
2277
+ //#endregion
2278
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/forgejo/index.mjs
2279
+ /** Creates a Forgejo provider for Codeberg or any self-hosted Forgejo instance. */
2280
+ const forgejo = /* @__PURE__ */ defineForgeProvider(/* @__PURE__ */ forgejoDefinition(FORGEJO_PROFILE));
2281
+ //#endregion
2282
+ export { forgejo, toThread as i, toActor as n, toRepoRef as r, FORGEJO_HEADERS as t };