@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,2589 @@
1
+ import { $ as toDate, A as hexColour, B as milestoneId, C as createListing, E as firstPageEtag, G as requireIssueOrPull, I as mapConcurrent, K as requireThread, L as memo, M as isFirstPage, O as getManyConcurrently, P as iteratePages, Q as teamOrg, R as memoBy, T as degradesToWarning, U as rateLimitPart, V as phased, Y as soleMergeMethod, Z as syntheticReview, a as ForgeApiError, at as versionAtLeast, c as InsufficientScopeError, ct as isNamespaceRef, d as NotFoundError, g as UnsupportedOperationError, h as UnresolvedThreadError, i as ForbiddenError, it as toWarning, m as TokenRevokedError, n as BranchMovedError, nt as toPage, ot as withEtag, pt as reactionContent, q as resolveToken, t as AuthenticationRequiredError, tt as toMergeError, z as mergeCommitMessage } from "./utils-DC7MBR65-B7Vr2hFm.js";
2
+ import { C as verb, D as rangeOf, E as lineOf, O as webUrlFor, S as toFileContent, c as changeBase64, d as eventTime, f as existingFiles, g as perKind, l as defineForgeProvider, o as verifySharedToken, p as fromBase64, r as nativeEventsFor, s as WRITE_VERBS, t as eventKindsOf } from "./webhooks-Bc6QhmI8-CNgCERCq.js";
3
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/web-tZM874Sy.mjs
4
+ const SECTIONS = {
5
+ issue: "work_items",
6
+ pull_request: "merge_requests"
7
+ };
8
+ const KINDS = new Map([
9
+ ...Object.entries(SECTIONS).map(([kind, section]) => [section, kind]),
10
+ ["issues", "issue"],
11
+ ["work_items", "issue"]
12
+ ]);
13
+ const PREFIXES = {
14
+ issue: "#",
15
+ pull_request: "!"
16
+ };
17
+ const PAGES = {
18
+ issues: "work_items",
19
+ pullRequests: "merge_requests",
20
+ compare: "compare",
21
+ releases: "releases",
22
+ stargazers: "starrers",
23
+ forks: "forks"
24
+ };
25
+ const GROUP_PAGES = {
26
+ issues: "work_items",
27
+ pullRequests: "merge_requests"
28
+ };
29
+ const REFERENCES = {
30
+ threads: [{
31
+ prefix: "#",
32
+ kind: "issue"
33
+ }, {
34
+ prefix: "!",
35
+ kind: "pull_request"
36
+ }],
37
+ repo: String.raw`(?:[\w.-]+\/)+[\w.-]+`,
38
+ suffix: String.raw`\+s?`,
39
+ commits: true
40
+ };
41
+ const encode = (path) => path.split("/").map(encodeURIComponent).join("/");
42
+ const projectPath = (repo) => `/${encode(repo.owner)}/${encodeURIComponent(repo.name)}`;
43
+ function gitlabWeb(baseUrl) {
44
+ return {
45
+ baseUrl,
46
+ repo: (repo) => repo.kind === "namespace" ? `/${encode(repo.owner)}` : projectPath(repo),
47
+ section: (repo, section) => repo.kind === "namespace" ? GROUP_PAGES[section] && `/groups/${encode(repo.owner)}/-/${GROUP_PAGES[section]}` : PAGES[section] && `${projectPath(repo)}/-/${PAGES[section]}`,
48
+ thread: (ref) => ref.repo.kind === "namespace" || !SECTIONS[ref.kind] || !ref.number ? void 0 : `${projectPath(ref.repo)}/-/${SECTIONS[ref.kind]}/${encodeURIComponent(ref.number)}`,
49
+ comment: (ref) => ref.thread.repo.kind === "namespace" || !SECTIONS[ref.thread.kind] ? void 0 : `${projectPath(ref.thread.repo)}/-/${SECTIONS[ref.thread.kind]}/${encodeURIComponent(ref.thread.number)}#note_${ref.id}`,
50
+ commit: (repo, sha) => repo.kind === "namespace" ? void 0 : `${projectPath(repo)}/-/commit/${encodeURIComponent(sha)}`,
51
+ release: (ref) => ref.tag ? `${projectPath(ref.repo)}/-/releases/${encodeURIComponent(ref.tag)}` : void 0,
52
+ file: (repo, path, at, line) => `${projectPath(repo)}/-/blob/${encodeURIComponent(at)}/${encode(path)}${line ? `#L${line}` : ""}`,
53
+ raw: (repo, path, at) => `${projectPath(repo)}/-/raw/${encodeURIComponent(at)}/${encode(path)}`,
54
+ compare: (repo, base, head) => `${projectPath(repo)}/-/compare/${encodeURIComponent(base)}...${encodeURIComponent(head)}`,
55
+ parse: (segments, url, from) => {
56
+ const separator = segments.indexOf("-");
57
+ const path = separator < 0 ? segments : segments.slice(0, separator);
58
+ if (path.length < 2) return;
59
+ const repo = {
60
+ ...from,
61
+ owner: path.slice(0, -1).join("/"),
62
+ name: path.at(-1).replace(/\.git$/, "")
63
+ };
64
+ const [section, id] = separator < 0 ? [] : segments.slice(separator + 1);
65
+ if (section === "blob" && id && segments.length > separator + 3) return {
66
+ repo,
67
+ file: {
68
+ at: id,
69
+ path: segments.slice(separator + 3).join("/"),
70
+ ...lineOf(url.hash.replace(/^#L/, ""))
71
+ }
72
+ };
73
+ if (section === "releases" && id) return {
74
+ repo,
75
+ release: {
76
+ ...from,
77
+ repo,
78
+ id,
79
+ tag: id
80
+ }
81
+ };
82
+ if (section === "commit" && id) return {
83
+ repo,
84
+ commit: {
85
+ ...from,
86
+ repo,
87
+ sha: id
88
+ }
89
+ };
90
+ if (section === "tags" && id) return {
91
+ repo,
92
+ tag: segments.slice(separator + 2).join("/")
93
+ };
94
+ if (section === "compare" && id) return {
95
+ repo,
96
+ ...rangeOf(segments.slice(separator + 2).join("/"))
97
+ };
98
+ const kind = section ? KINDS.get(section) : void 0;
99
+ if (!kind || !id) return { repo };
100
+ const thread = {
101
+ ...from,
102
+ repo,
103
+ kind,
104
+ number: id
105
+ };
106
+ const sha = kind === "pull_request" ? url.searchParams.get("commit_id") : void 0;
107
+ if (sha) return {
108
+ repo,
109
+ thread,
110
+ commit: {
111
+ ...from,
112
+ repo,
113
+ sha
114
+ }
115
+ };
116
+ const note = url.hash.startsWith("#note_") ? url.hash.slice(6) : void 0;
117
+ return {
118
+ repo,
119
+ thread,
120
+ ...note ? { comment: {
121
+ ...from,
122
+ thread,
123
+ id: note
124
+ } } : {}
125
+ };
126
+ },
127
+ reference: (ref, same, expand) => {
128
+ if ("sha" in ref) return `${same ? "" : `${ref.repo.owner}/${ref.repo.name}@`}${ref.sha.slice(0, 8)}`;
129
+ const prefix = PREFIXES[ref.kind];
130
+ if (!prefix || ref.repo.kind === "namespace" || !ref.number) return;
131
+ return `${same ? "" : `${ref.repo.owner}/${ref.repo.name}`}${prefix}${ref.number}${expand ? "+" : ""}`;
132
+ },
133
+ references: REFERENCES
134
+ };
135
+ }
136
+ const GITLAB_WEB = {
137
+ forge: "gitlab",
138
+ baseUrl: "https://gitlab.com",
139
+ apiPath: "/api/v4",
140
+ links: ({ baseUrl }) => gitlabWeb(baseUrl.replace(/\/api\/v4$/, ""))
141
+ };
142
+ //#endregion
143
+ //#region ../../node_modules/.pnpm/forges@0.3.1/node_modules/forges/dist/gitlab-CoGcd7R7.mjs
144
+ /**
145
+ * GitLab subscribes per event with a boolean flag rather than an event name,
146
+ * so the flag names are the native events.
147
+ */
148
+ const GITLAB_NATIVE_EVENTS = {
149
+ comment: ["note_events", "confidential_note_events"],
150
+ review: ["merge_requests_events"],
151
+ review_comment: ["note_events"],
152
+ state_change: [
153
+ "issues_events",
154
+ "confidential_issues_events",
155
+ "merge_requests_events"
156
+ ],
157
+ label: ["issues_events", "merge_requests_events"],
158
+ assignment: ["issues_events", "merge_requests_events"],
159
+ push: ["push_events"],
160
+ ref: ["tag_push_events", "push_events"],
161
+ release: ["releases_events"],
162
+ membership: ["member_events"],
163
+ wiki: ["wiki_page_events"]
164
+ };
165
+ /** Normalised kinds and actions GitLab deliveries translate into. */
166
+ const GITLAB_WEBHOOK_EVENTS = [
167
+ {
168
+ kind: "comment",
169
+ action: "created"
170
+ },
171
+ {
172
+ kind: "review",
173
+ action: "submitted"
174
+ },
175
+ {
176
+ kind: "review_comment",
177
+ action: "created"
178
+ },
179
+ {
180
+ kind: "state_change",
181
+ action: "opened"
182
+ },
183
+ {
184
+ kind: "state_change",
185
+ action: "closed"
186
+ },
187
+ {
188
+ kind: "state_change",
189
+ action: "reopened"
190
+ },
191
+ {
192
+ kind: "state_change",
193
+ action: "merged"
194
+ },
195
+ {
196
+ kind: "label",
197
+ action: "labelled"
198
+ },
199
+ {
200
+ kind: "label",
201
+ action: "unlabelled"
202
+ },
203
+ {
204
+ kind: "assignment",
205
+ action: "assigned"
206
+ },
207
+ {
208
+ kind: "assignment",
209
+ action: "unassigned"
210
+ },
211
+ {
212
+ kind: "assignment",
213
+ action: "review_requested"
214
+ },
215
+ { kind: "push" },
216
+ {
217
+ kind: "ref",
218
+ action: "created"
219
+ },
220
+ {
221
+ kind: "ref",
222
+ action: "deleted"
223
+ },
224
+ {
225
+ kind: "release",
226
+ action: "published"
227
+ },
228
+ {
229
+ kind: "release",
230
+ action: "edited"
231
+ },
232
+ {
233
+ kind: "release",
234
+ action: "deleted"
235
+ },
236
+ { kind: "membership" },
237
+ {
238
+ kind: "wiki",
239
+ action: "created"
240
+ },
241
+ {
242
+ kind: "wiki",
243
+ action: "edited"
244
+ },
245
+ {
246
+ kind: "wiki",
247
+ action: "deleted"
248
+ }
249
+ ];
250
+ const FORGE = "gitlab";
251
+ function toActor(instance, user) {
252
+ if (!user) return;
253
+ return {
254
+ forge: FORGE,
255
+ instance,
256
+ login: user.username,
257
+ id: String(user.id),
258
+ name: user.name,
259
+ avatarUrl: user.avatar_url ?? void 0,
260
+ url: user.web_url,
261
+ typeRaw: user.bot === void 0 ? void 0 : user.bot ? "bot" : "user",
262
+ isBotHint: user.bot === true || /^(?:project|group)_\d+_bot(?:_|$)/.test(user.username)
263
+ };
264
+ }
265
+ /** Splits a full project path into the namespace (which may contain slashes) and the project name. */
266
+ function toRepoRef(instance, pathWithNamespace, id) {
267
+ const index = pathWithNamespace.lastIndexOf("/");
268
+ return {
269
+ forge: FORGE,
270
+ instance,
271
+ owner: pathWithNamespace.slice(0, index),
272
+ name: pathWithNamespace.slice(index + 1),
273
+ externalId: id === void 0 ? void 0 : String(id)
274
+ };
275
+ }
276
+ /** Reads the project path out of a `/-/`-style web URL, which cross-project listings carry instead of a project path. */
277
+ function repoRefFromWebUrl(instance, webUrl, id) {
278
+ const path = webUrl?.match(/^https?:\/\/[^/]+\/(.+?)\/-\//)?.[1];
279
+ return path ? toRepoRef(instance, path, id) : void 0;
280
+ }
281
+ function toNamespaceRef(instance, fullPath, id) {
282
+ return {
283
+ forge: FORGE,
284
+ instance,
285
+ kind: "namespace",
286
+ owner: fullPath,
287
+ name: "",
288
+ externalId: id === void 0 ? void 0 : String(id)
289
+ };
290
+ }
291
+ /** GitLab has no teams of its own; a subgroup stands in for one, with its path below `org` as the slug. */
292
+ function toTeam(instance, org, raw) {
293
+ const slug = raw.full_path.slice(org.owner.length + 1);
294
+ const parent = slug.includes("/") ? slug.slice(0, slug.lastIndexOf("/")) : void 0;
295
+ return {
296
+ ref: {
297
+ forge: FORGE,
298
+ instance,
299
+ org,
300
+ id: String(raw.id),
301
+ slug
302
+ },
303
+ name: raw.name ?? raw.path ?? slug,
304
+ description: raw.description || void 0,
305
+ visibilityRaw: raw.visibility,
306
+ parent: parent === void 0 ? void 0 : {
307
+ forge: FORGE,
308
+ instance,
309
+ org,
310
+ id: raw.parent_id == null ? void 0 : String(raw.parent_id),
311
+ slug: parent
312
+ },
313
+ url: raw.web_url,
314
+ raw
315
+ };
316
+ }
317
+ /** Project id accepted by every `/projects/:id` route. */
318
+ function projectId(repo) {
319
+ return encodeURIComponent(`${repo.owner}/${repo.name}`);
320
+ }
321
+ function toThreadKind(targetType) {
322
+ switch (targetType) {
323
+ case "Issue": return "issue";
324
+ case "MergeRequest": return "pull_request";
325
+ default: return;
326
+ }
327
+ }
328
+ const REASONS = {
329
+ added_approver: "approval_requested",
330
+ approval_required: "approval_requested",
331
+ assigned: "assigned",
332
+ build_failed: "ci_activity",
333
+ directly_addressed: "mention",
334
+ marked: "manual",
335
+ member_access_requested: "access_requested",
336
+ mentioned: "mention",
337
+ merge_train_removed: "merge_blocked",
338
+ review_requested: "review_requested",
339
+ review_submitted: "review_submitted",
340
+ unmergeable: "merge_blocked"
341
+ };
342
+ function toReason(action) {
343
+ return REASONS[action] ?? "unknown";
344
+ }
345
+ function toState(state) {
346
+ switch (state) {
347
+ case "opened": return "open";
348
+ case "closed":
349
+ case "locked": return "closed";
350
+ case "merged": return "merged";
351
+ default: return "unknown";
352
+ }
353
+ }
354
+ function toNotification(instance, raw) {
355
+ const repo = raw.project ? toRepoRef(instance, raw.project.path_with_namespace, raw.project.id) : toNamespaceRef(instance, raw.group?.full_path ?? "", raw.group?.id);
356
+ const kind = toThreadKind(raw.target_type);
357
+ const target = raw.target ?? void 0;
358
+ const number = target?.iid === void 0 ? target?.id === void 0 ? void 0 : String(target.id) : String(target.iid);
359
+ let subject;
360
+ if (raw.target_type === "Vulnerability") subject = {
361
+ type: "security_alert",
362
+ alert: {
363
+ forge: FORGE,
364
+ instance,
365
+ repo,
366
+ id: number ?? String(raw.id)
367
+ }
368
+ };
369
+ else if (raw.target_type === "Project" || raw.target_type === "Namespace") subject = {
370
+ type: "repo",
371
+ repo
372
+ };
373
+ else if (raw.target_type === "Commit" && number) subject = {
374
+ type: "commit",
375
+ commit: {
376
+ forge: FORGE,
377
+ instance,
378
+ repo,
379
+ sha: number
380
+ }
381
+ };
382
+ else if (!kind) subject = {
383
+ type: "other",
384
+ typeRaw: raw.target_type,
385
+ repo,
386
+ id: number,
387
+ url: raw.target_url
388
+ };
389
+ else subject = {
390
+ type: "thread",
391
+ thread: {
392
+ forge: FORGE,
393
+ instance,
394
+ repo,
395
+ kind,
396
+ typeRaw: raw.target_type,
397
+ number
398
+ }
399
+ };
400
+ return {
401
+ ref: {
402
+ forge: FORGE,
403
+ instance,
404
+ id: String(raw.id)
405
+ },
406
+ subject,
407
+ subjectTypeRaw: raw.target_type,
408
+ reason: toReason(raw.action_name),
409
+ reasonRaw: raw.action_name,
410
+ unread: raw.state === "pending",
411
+ title: target?.title ?? raw.body ?? "",
412
+ subjectState: toState(target?.state),
413
+ subjectStateRaw: target?.state,
414
+ updatedAt: toDate(raw.updated_at ?? raw.created_at) ?? /* @__PURE__ */ new Date(0),
415
+ url: raw.target_url,
416
+ raw
417
+ };
418
+ }
419
+ const ACCESS_LEVELS$1 = {
420
+ admin: 50,
421
+ maintain: 40,
422
+ push: 30,
423
+ triage: 20,
424
+ pull: 10
425
+ };
426
+ /** GitLab access levels: 50 owner, 40 maintainer, 30 developer, 20 reporter, 10 guest. */
427
+ function toRole(level) {
428
+ return level >= 50 ? "admin" : level >= 40 ? "maintain" : level >= 30 ? "write" : level >= 20 ? "triage" : level >= 10 ? "read" : "none";
429
+ }
430
+ function toLabel(raw) {
431
+ return {
432
+ name: raw.name,
433
+ colour: raw.color?.replace(/^#/, ""),
434
+ description: raw.description ?? void 0
435
+ };
436
+ }
437
+ function toMilestone(raw) {
438
+ return raw ? {
439
+ id: String(raw.id),
440
+ title: raw.title,
441
+ state: raw.state === "closed" ? "closed" : "open",
442
+ description: raw.description ?? void 0,
443
+ dueOn: toDate(raw.due_date),
444
+ url: raw.web_url,
445
+ raw
446
+ } : void 0;
447
+ }
448
+ /** GitLab counts only thumbs up and down on a thread read; the full set needs the award emoji listing. */
449
+ function toVoteReactions(raw) {
450
+ if (raw.upvotes === void 0 && raw.downvotes === void 0) return;
451
+ return {
452
+ total: (raw.upvotes ?? 0) + (raw.downvotes ?? 0),
453
+ counts: {
454
+ ...raw.upvotes ? { "+1": raw.upvotes } : {},
455
+ ...raw.downvotes ? { "-1": raw.downvotes } : {}
456
+ }
457
+ };
458
+ }
459
+ const BASE_METHODS = {
460
+ merge: "merge",
461
+ rebase_merge: "rebase_merge",
462
+ ff: "fast_forward_only"
463
+ };
464
+ function toRepo(instance, raw) {
465
+ const level = Math.max(raw.permissions?.project_access?.access_level ?? 0, raw.permissions?.group_access?.access_level ?? 0);
466
+ const visibility = raw.visibility === "internal" ? "internal" : raw.visibility === "private" ? "private" : "public";
467
+ const merge = raw.merge_commit_template?.trim() ? { template: raw.merge_commit_template } : void 0;
468
+ const squash = raw.squash_commit_template?.trim() ? { template: raw.squash_commit_template } : void 0;
469
+ return {
470
+ ref: toRepoRef(instance, raw.path_with_namespace, raw.id),
471
+ description: raw.description ?? void 0,
472
+ defaultBranch: raw.default_branch ?? void 0,
473
+ visibility,
474
+ visibilityRaw: raw.visibility,
475
+ isFork: Boolean(raw.forked_from_project),
476
+ isArchived: raw.archived ?? false,
477
+ parent: raw.forked_from_project ? toRepoRef(instance, raw.forked_from_project.path_with_namespace, raw.forked_from_project.id) : void 0,
478
+ topics: raw.topics ?? [],
479
+ url: raw.web_url,
480
+ cloneUrls: raw.http_url_to_repo || raw.ssh_url_to_repo ? {
481
+ https: raw.http_url_to_repo,
482
+ ssh: raw.ssh_url_to_repo
483
+ } : void 0,
484
+ createdAt: toDate(raw.created_at),
485
+ updatedAt: toDate(raw.last_activity_at),
486
+ openIssueCount: raw.open_issues_count,
487
+ owner: toActor(instance, raw.owner),
488
+ licence: raw.license?.key && raw.license.key !== "other" ? raw.license.key : void 0,
489
+ stars: raw.star_count,
490
+ forks: raw.forks_count,
491
+ mergeMethods: raw.merge_method === void 0 ? void 0 : [
492
+ ...raw.merge_method === "merge" ? ["merge"] : [],
493
+ ...raw.merge_method === "rebase_merge" ? ["rebase_merge"] : [],
494
+ ...raw.merge_method === "ff" ? ["fast_forward_only"] : [],
495
+ ...raw.squash_option && raw.squash_option !== "never" ? ["squash"] : []
496
+ ],
497
+ defaultMergeMethod: raw.merge_method === void 0 ? void 0 : raw.squash_option === "always" || raw.squash_option === "default_on" ? "squash" : BASE_METHODS[raw.merge_method],
498
+ deleteBranchOnMerge: raw.remove_source_branch_after_merge ?? void 0,
499
+ mergeCommit: merge || squash ? {
500
+ merge,
501
+ squash
502
+ } : void 0,
503
+ features: raw.issues_access_level === void 0 && raw.issues_enabled === void 0 ? void 0 : {
504
+ issues: raw.issues_enabled ?? raw.issues_access_level !== "disabled",
505
+ pullRequests: raw.merge_requests_enabled ?? raw.merge_requests_access_level !== "disabled",
506
+ discussions: false,
507
+ wiki: raw.wiki_enabled ?? raw.wiki_access_level !== "disabled",
508
+ projects: false,
509
+ releases: raw.releases_access_level !== "disabled"
510
+ },
511
+ permissions: raw.permissions ? {
512
+ admin: level >= ACCESS_LEVELS$1.admin,
513
+ maintain: level >= ACCESS_LEVELS$1.maintain,
514
+ push: level >= ACCESS_LEVELS$1.push,
515
+ triage: level >= ACCESS_LEVELS$1.triage,
516
+ pull: level >= ACCESS_LEVELS$1.pull
517
+ } : void 0,
518
+ raw
519
+ };
520
+ }
521
+ function toThread(ref, raw) {
522
+ const isMerge = ref.kind === "pull_request";
523
+ const reviewers = (raw.reviewers ?? []).flatMap((user) => {
524
+ const actor = toActor(ref.instance, user);
525
+ return actor ? [{
526
+ actor,
527
+ state: "unknown"
528
+ }] : [];
529
+ });
530
+ return {
531
+ ref: {
532
+ ...ref,
533
+ externalId: raw.id === void 0 ? ref.externalId : String(raw.id)
534
+ },
535
+ kind: ref.kind,
536
+ title: raw.title,
537
+ body: raw.description ?? void 0,
538
+ state: toState(raw.state),
539
+ stateRaw: raw.state,
540
+ isDraft: raw.draft ?? false,
541
+ assignees: (raw.assignees ?? []).flatMap((user) => toActor(ref.instance, user) ?? []),
542
+ reviewers,
543
+ lastActivityAt: toDate(raw.updated_at),
544
+ branches: isMerge && raw.source_branch && raw.target_branch ? {
545
+ head: {
546
+ ref: raw.source_branch,
547
+ sha: raw.diff_refs?.head_sha ?? raw.sha,
548
+ repo: raw.source_project_id !== void 0 && raw.source_project_id === raw.target_project_id ? ref.repo : void 0
549
+ },
550
+ base: {
551
+ ref: raw.target_branch,
552
+ sha: raw.diff_refs?.base_sha
553
+ },
554
+ mergeCommitSha: raw.merge_commit_sha ?? raw.squash_commit_sha ?? void 0
555
+ } : void 0,
556
+ stats: isMerge && raw.changes_count && /^\d+$/.test(raw.changes_count) ? { changedFileCount: Number(raw.changes_count) } : void 0,
557
+ author: toActor(ref.instance, raw.author),
558
+ url: raw.web_url,
559
+ createdAt: toDate(raw.created_at),
560
+ updatedAt: toDate(raw.updated_at),
561
+ closedAt: toDate(raw.closed_at),
562
+ mergedAt: isMerge ? toDate(raw.merged_at) : void 0,
563
+ mergedBy: isMerge ? toActor(ref.instance, raw.merge_user ?? raw.merged_by) : void 0,
564
+ labels: (raw.labels ?? []).map((label) => typeof label === "string" ? { name: label } : {
565
+ name: label.name,
566
+ colour: label.color,
567
+ description: label.description ?? void 0
568
+ }),
569
+ locked: raw.discussion_locked ?? void 0,
570
+ commentCount: raw.user_notes_count,
571
+ milestone: toMilestone(raw.milestone),
572
+ reactions: toVoteReactions(raw),
573
+ raw
574
+ };
575
+ }
576
+ /** System notes are the only record of label, state and assignment changes in the notes API. */
577
+ const SYSTEM_NOTE_KINDS = [
578
+ [/^approved this merge request/i, "review"],
579
+ [/^added \d+ (?:new )?commits?/i, "commit"],
580
+ [/^(?:added|removed) .*label/i, "label"],
581
+ [/^(?:closed|reopened|merged|marked this merge request as|status changed to)/i, "state_change"],
582
+ [/^(?:assigned to|reassigned to|unassigned|requested review from)/i, "assignment"],
583
+ [/^mentioned in /i, "referenced"]
584
+ ];
585
+ function toNoteKind(note) {
586
+ if (!note.system) return note.type === "DiffNote" ? "review_comment" : "comment";
587
+ return SYSTEM_NOTE_KINDS.find(([pattern]) => pattern.test(note.body))?.[1] ?? "other";
588
+ }
589
+ /**
590
+ * A "mentioned in" system note names the subject that mentioned this thread:
591
+ * `!5` or `acme/widgets!5` for a merge request, `#5` for an issue, or a sha
592
+ * for a commit. The reference is read from that wording, since the note
593
+ * carries no structured source.
594
+ */
595
+ function crossReference(ref, body) {
596
+ const text = body.match(/^mentioned in (?:merge request|issue|commit) (\S+)/i)?.[1];
597
+ if (!text) return {
598
+ type: "referenced",
599
+ text: body
600
+ };
601
+ const thread = text.match(/^(?:([^!#]+)([!#]))?[!#]?(\d+)$/);
602
+ if (thread) {
603
+ const repo = thread[1] ? toRepoRef(ref.instance, thread[1]) : ref.repo;
604
+ return {
605
+ type: "referenced",
606
+ from: {
607
+ forge: FORGE,
608
+ instance: ref.instance,
609
+ repo,
610
+ kind: text.includes("!") ? "pull_request" : "issue",
611
+ number: thread[3]
612
+ },
613
+ fromRepo: repo,
614
+ text
615
+ };
616
+ }
617
+ return /^[0-9a-f]{7,40}$/i.test(text) ? {
618
+ type: "referenced",
619
+ from: {
620
+ forge: FORGE,
621
+ instance: ref.instance,
622
+ repo: ref.repo,
623
+ sha: text
624
+ },
625
+ fromRepo: ref.repo,
626
+ text
627
+ } : {
628
+ type: "referenced",
629
+ text
630
+ };
631
+ }
632
+ /** The review id that `threads.reviews()` gives an approval by `user`. */
633
+ function approvalId(user) {
634
+ return `approval:${user?.username ?? user?.id ?? ""}`;
635
+ }
636
+ function noteDetail(ref, note, kind) {
637
+ switch (kind) {
638
+ case "comment":
639
+ case "review_comment": return {
640
+ type: kind,
641
+ comment: {
642
+ forge: FORGE,
643
+ instance: ref.instance,
644
+ thread: ref,
645
+ id: String(note.id)
646
+ },
647
+ body: note.body
648
+ };
649
+ case "review": return {
650
+ type: "review",
651
+ state: "approved",
652
+ stateRaw: "approved",
653
+ review: {
654
+ forge: FORGE,
655
+ instance: ref.instance,
656
+ thread: ref,
657
+ id: approvalId(note.author)
658
+ }
659
+ };
660
+ case "referenced": return crossReference(ref, note.body);
661
+ default: return;
662
+ }
663
+ }
664
+ function toNoteEvent(ref, note) {
665
+ const actor = toActor(ref.instance, note.author);
666
+ const kind = toNoteKind(note);
667
+ const who = actor?.login ?? "someone";
668
+ return {
669
+ forge: FORGE,
670
+ instance: ref.instance,
671
+ id: String(note.id),
672
+ kind,
673
+ kindRaw: note.system ? "system" : note.type ?? "Note",
674
+ summary: note.system ? `${who} ${note.body.split("\n")[0]}` : `${who} ${kind === "review_comment" ? "commented on a line" : "commented"}`,
675
+ ...eventTime(toDate(note.created_at), /* @__PURE__ */ new Date(0)),
676
+ actor,
677
+ repo: ref.repo,
678
+ thread: ref,
679
+ detail: noteDetail(ref, note, kind),
680
+ source: "poll",
681
+ payload: note
682
+ };
683
+ }
684
+ /** GitLab commit comments carry no id, so they are keyed by creation time and author. */
685
+ function commitCommentId(comment) {
686
+ return `${comment.created_at ?? ""}:${comment.author?.id ?? ""}`;
687
+ }
688
+ function toNoteComment(thread, note, discussion) {
689
+ return {
690
+ ref: {
691
+ forge: FORGE,
692
+ instance: thread.instance,
693
+ thread,
694
+ id: String(note.id)
695
+ },
696
+ body: note.body,
697
+ author: toActor(thread.instance, note.author),
698
+ createdAt: toDate(note.created_at),
699
+ updatedAt: toDate(note.updated_at),
700
+ ...discussion && note.resolvable && { thread: {
701
+ id: discussion.id,
702
+ resolved: Boolean(note.resolved)
703
+ } },
704
+ raw: note
705
+ };
706
+ }
707
+ /** A line of a diff note: the new side where it has one, else the old side. */
708
+ function notedLine(position) {
709
+ if (typeof position?.new_line === "number") return {
710
+ line: position.new_line,
711
+ side: "right"
712
+ };
713
+ return typeof position?.old_line === "number" ? {
714
+ line: position.old_line,
715
+ side: "left"
716
+ } : {};
717
+ }
718
+ /** A resolvable discussion, read as a review conversation. GitLab doesn't say whether one is outdated. */
719
+ function toDiscussionThread(thread, discussion) {
720
+ const notes = discussion.notes.filter((note) => !note.system);
721
+ const position = notes.find((note) => note.position)?.position ?? void 0;
722
+ const path = position?.new_path ?? position?.old_path ?? void 0;
723
+ const { line, side } = notedLine(position);
724
+ const start = notedLine(position?.line_range?.start).line;
725
+ const resolved = notes.every((note) => !note.resolvable || Boolean(note.resolved));
726
+ return {
727
+ id: discussion.id,
728
+ resolved,
729
+ path,
730
+ line,
731
+ startLine: start !== void 0 && start !== line ? start : void 0,
732
+ side,
733
+ comments: notes.map((note) => ({
734
+ ref: {
735
+ forge: FORGE,
736
+ instance: thread.instance,
737
+ thread,
738
+ id: String(note.id)
739
+ },
740
+ body: note.body,
741
+ author: toActor(thread.instance, note.author),
742
+ ...note.position && {
743
+ path: note.position.new_path ?? note.position.old_path ?? void 0,
744
+ ...notedLine(note.position)
745
+ },
746
+ thread: {
747
+ id: discussion.id,
748
+ resolved
749
+ },
750
+ createdAt: toDate(note.created_at),
751
+ raw: note
752
+ })),
753
+ raw: discussion
754
+ };
755
+ }
756
+ function toCommitComment(commit, comment) {
757
+ return {
758
+ ref: {
759
+ forge: FORGE,
760
+ instance: commit.instance,
761
+ commit,
762
+ id: commitCommentId(comment)
763
+ },
764
+ body: comment.note,
765
+ author: toActor(commit.instance, comment.author),
766
+ createdAt: toDate(comment.created_at),
767
+ raw: comment
768
+ };
769
+ }
770
+ /** Pipeline and job statuses. `manual` jobs wait for a person, so they neither pass nor fail. */
771
+ function pipelineState(status) {
772
+ switch (status) {
773
+ case "success": return "success";
774
+ case "failed":
775
+ case "canceled": return "failure";
776
+ case "skipped":
777
+ case "manual": return "neutral";
778
+ case "created":
779
+ case "waiting_for_resource":
780
+ case "preparing":
781
+ case "pending":
782
+ case "running":
783
+ case "scheduled": return "pending";
784
+ default: return "unknown";
785
+ }
786
+ }
787
+ /** The merge request's head pipeline, which GitLab reports as one combined status. */
788
+ function toPipelineSummary(pipeline) {
789
+ const state = pipelineState(pipeline.status);
790
+ return {
791
+ state: state === "neutral" ? "pending" : state,
792
+ stateRaw: pipeline.status,
793
+ ...pipeline.web_url ? { url: pipeline.web_url } : {}
794
+ };
795
+ }
796
+ function toJobCheck(repo, job, run) {
797
+ const state = pipelineState(job.status);
798
+ return {
799
+ ref: {
800
+ forge: FORGE,
801
+ instance: repo.instance,
802
+ repo,
803
+ id: String(job.id),
804
+ type: "job"
805
+ },
806
+ name: job.stage ? `${job.stage}: ${job.name}` : job.name,
807
+ state: state === "failure" && job.allow_failure ? "neutral" : state,
808
+ stateRaw: job.status,
809
+ url: job.web_url,
810
+ startedAt: toDate(job.started_at),
811
+ completedAt: toDate(job.finished_at),
812
+ ...run ? { run } : {},
813
+ raw: job
814
+ };
815
+ }
816
+ /** GitLab keys releases by tag and has no drafts or prereleases. */
817
+ function toRelease(repo, raw) {
818
+ return {
819
+ ref: {
820
+ forge: FORGE,
821
+ instance: repo.instance,
822
+ repo,
823
+ id: raw.tag_name,
824
+ tag: raw.tag_name
825
+ },
826
+ name: raw.name ?? void 0,
827
+ tag: raw.tag_name,
828
+ body: raw.description ?? void 0,
829
+ isDraft: false,
830
+ isPrerelease: false,
831
+ author: toActor(repo.instance, raw.author),
832
+ publishedAt: raw.upcoming_release ? void 0 : toDate(raw.released_at),
833
+ createdAt: toDate(raw.created_at),
834
+ url: raw._links?.self,
835
+ assets: raw.assets?.links?.map((link) => ({
836
+ name: link.name,
837
+ url: link.direct_asset_url ?? link.url
838
+ })),
839
+ raw
840
+ };
841
+ }
842
+ const REPORT_KINDS = {
843
+ DEPENDENCY_SCANNING: "dependency",
844
+ CONTAINER_SCANNING: "dependency",
845
+ CLUSTER_IMAGE_SCANNING: "dependency",
846
+ SAST: "code_scanning",
847
+ SECRET_DETECTION: "secret"
848
+ };
849
+ const REPORT_TYPES = {
850
+ dependency: [
851
+ "DEPENDENCY_SCANNING",
852
+ "CONTAINER_SCANNING",
853
+ "CLUSTER_IMAGE_SCANNING"
854
+ ],
855
+ code_scanning: ["SAST"],
856
+ secret: ["SECRET_DETECTION"],
857
+ advisory: []
858
+ };
859
+ /** `INFO` findings are informational and carry no severity. */
860
+ function toSeverity(raw) {
861
+ const severity = raw.toLowerCase();
862
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low" ? severity : "unknown";
863
+ }
864
+ function toVulnerability(repo, raw) {
865
+ const kind = REPORT_KINDS[raw.reportType] ?? "other";
866
+ const state = raw.state === "DETECTED" || raw.state === "CONFIRMED" ? "open" : raw.state === "RESOLVED" ? "fixed" : raw.state === "DISMISSED" ? "dismissed" : "unknown";
867
+ const id = raw.id.replace(/^gid:\/\/gitlab\/Vulnerability\//, "");
868
+ return {
869
+ ref: {
870
+ forge: FORGE,
871
+ instance: repo.instance,
872
+ repo,
873
+ id,
874
+ kind,
875
+ severityRaw: raw.severity.toLowerCase()
876
+ },
877
+ kind,
878
+ kindRaw: raw.reportType.toLowerCase(),
879
+ severity: toSeverity(raw.severity),
880
+ severityRaw: raw.severity.toLowerCase(),
881
+ state,
882
+ stateRaw: raw.state.toLowerCase(),
883
+ title: raw.title,
884
+ url: raw.webUrl ?? void 0,
885
+ createdAt: toDate(raw.detectedAt),
886
+ updatedAt: toDate(raw.updatedAt),
887
+ dismissedAt: toDate(raw.dismissedAt),
888
+ raw
889
+ };
890
+ }
891
+ function toStatusCheck(repo, raw) {
892
+ const state = pipelineState(raw.status);
893
+ return {
894
+ ref: {
895
+ forge: FORGE,
896
+ instance: repo.instance,
897
+ repo,
898
+ id: String(raw.id),
899
+ type: "status"
900
+ },
901
+ name: raw.name ?? String(raw.id),
902
+ state: state === "failure" && raw.allow_failure ? "neutral" : state,
903
+ stateRaw: raw.status,
904
+ url: raw.target_url ?? void 0,
905
+ startedAt: toDate(raw.created_at),
906
+ completedAt: toDate(raw.finished_at),
907
+ raw
908
+ };
909
+ }
910
+ function toPipeline(repo, raw) {
911
+ return {
912
+ ref: {
913
+ forge: FORGE,
914
+ instance: repo.instance,
915
+ repo,
916
+ id: String(raw.id)
917
+ },
918
+ name: raw.name || raw.source || `pipeline ${raw.id}`,
919
+ state: pipelineState(raw.status),
920
+ stateRaw: raw.status,
921
+ number: raw.iid === void 0 ? void 0 : String(raw.iid),
922
+ eventRaw: raw.source,
923
+ branch: raw.ref,
924
+ sha: raw.sha,
925
+ url: raw.web_url,
926
+ actor: toActor(repo.instance, raw.user),
927
+ createdAt: toDate(raw.created_at),
928
+ startedAt: toDate(raw.started_at),
929
+ completedAt: toDate(raw.finished_at),
930
+ raw
931
+ };
932
+ }
933
+ function toCiJob(run, raw) {
934
+ const state = pipelineState(raw.status);
935
+ return {
936
+ ref: {
937
+ forge: FORGE,
938
+ instance: run.instance,
939
+ repo: run.repo,
940
+ id: String(raw.id),
941
+ run
942
+ },
943
+ name: raw.name,
944
+ state: state === "failure" && raw.allow_failure ? "neutral" : state,
945
+ stateRaw: raw.status,
946
+ stage: raw.stage,
947
+ url: raw.web_url,
948
+ startedAt: toDate(raw.started_at),
949
+ completedAt: toDate(raw.finished_at),
950
+ raw
951
+ };
952
+ }
953
+ function toCommit(repo, raw, files) {
954
+ return {
955
+ ref: {
956
+ forge: FORGE,
957
+ instance: repo.instance,
958
+ repo,
959
+ sha: raw.id
960
+ },
961
+ sha: raw.id,
962
+ message: raw.message ?? raw.title,
963
+ author: {
964
+ name: raw.author_name,
965
+ email: raw.author_email,
966
+ date: toDate(raw.authored_date ?? raw.created_at)
967
+ },
968
+ committer: {
969
+ name: raw.committer_name,
970
+ email: raw.committer_email,
971
+ date: toDate(raw.committed_date)
972
+ },
973
+ parents: raw.parent_ids ?? [],
974
+ url: raw.web_url,
975
+ ...raw.stats ? { stats: {
976
+ additions: raw.stats.additions ?? 0,
977
+ deletions: raw.stats.deletions ?? 0,
978
+ total: raw.stats.total
979
+ } } : {},
980
+ ...files ? { files } : {},
981
+ raw
982
+ };
983
+ }
984
+ /** GitLab reports a change by three booleans and a unified diff, with no counts. */
985
+ function toChangedFile(raw) {
986
+ const path = raw.new_path ?? raw.old_path ?? "";
987
+ const status = raw.new_file ? "added" : raw.deleted_file ? "removed" : raw.renamed_file ? "renamed" : "modified";
988
+ return {
989
+ path,
990
+ previousPath: raw.renamed_file ? raw.old_path : void 0,
991
+ status,
992
+ statusRaw: status,
993
+ patch: raw.diff
994
+ };
995
+ }
996
+ function toBranch(raw) {
997
+ return {
998
+ name: raw.name,
999
+ sha: raw.commit?.id ?? "",
1000
+ isDefault: raw.default,
1001
+ isProtected: raw.protected,
1002
+ url: raw.web_url,
1003
+ raw
1004
+ };
1005
+ }
1006
+ /** Whether a branch name matches a protected branch name, where `*` stands for any run of characters. */
1007
+ function matchesBranch(pattern, name) {
1008
+ return new RegExp(`^${pattern.split("*").map((part) => part.replace(/[\\^$.|?+()[\]{}]/g, "\\$&")).join(".*")}$`).test(name);
1009
+ }
1010
+ /** Code owner and report rules apply only to some changes, so just `any_approver` and `regular` set the floor. */
1011
+ function toBranchRules(branch, project, rules, warnings) {
1012
+ const applies = (rule) => rule.protected_branches?.length ? rule.protected_branches.some((protectedBranch) => matchesBranch(protectedBranch.name, branch.name)) : !rule.applies_to_all_protected_branches || branch.protected === true;
1013
+ const approvals = rules?.filter((rule) => (rule.rule_type === "any_approver" || rule.rule_type === "regular") && applies(rule)).map((rule) => rule.approvals_required);
1014
+ return {
1015
+ branch: branch.name,
1016
+ requiredChecks: [],
1017
+ requiresAllChecks: project.only_allow_merge_if_pipeline_succeeds ?? void 0,
1018
+ requiredApprovals: approvals && Math.max(0, ...approvals),
1019
+ ...warnings.length ? { warnings } : {},
1020
+ raw: {
1021
+ branch,
1022
+ project,
1023
+ rules
1024
+ }
1025
+ };
1026
+ }
1027
+ function toTag(raw) {
1028
+ return {
1029
+ name: raw.name,
1030
+ sha: raw.commit?.id ?? raw.target ?? "",
1031
+ raw
1032
+ };
1033
+ }
1034
+ function toTreeEntry(raw) {
1035
+ return {
1036
+ path: raw.path,
1037
+ type: raw.mode === "120000" ? "symlink" : raw.type === "tree" ? "directory" : raw.type === "commit" ? "submodule" : "file",
1038
+ sha: raw.id,
1039
+ mode: raw.mode
1040
+ };
1041
+ }
1042
+ function toWebhook(target, raw) {
1043
+ const nativeEvents = Object.entries(raw).filter(([key, value]) => key.endsWith("_events") && value === true).map(([key]) => key);
1044
+ return {
1045
+ ref: {
1046
+ forge: FORGE,
1047
+ instance: target.instance,
1048
+ target,
1049
+ id: String(raw.id)
1050
+ },
1051
+ url: raw.url,
1052
+ events: eventKindsOf(GITLAB_NATIVE_EVENTS, nativeEvents),
1053
+ nativeEvents,
1054
+ active: !raw.disabled_until,
1055
+ createdAt: toDate(raw.created_at),
1056
+ raw
1057
+ };
1058
+ }
1059
+ function toWebhookDelivery(hook, raw) {
1060
+ const status = Number(raw.response_status) || 0;
1061
+ return {
1062
+ ref: {
1063
+ forge: FORGE,
1064
+ instance: hook.instance,
1065
+ hook,
1066
+ id: String(raw.id)
1067
+ },
1068
+ event: raw.trigger ?? "",
1069
+ status,
1070
+ ok: status >= 200 && status < 300,
1071
+ deliveredAt: toDate(raw.created_at),
1072
+ duration: raw.execution_duration === void 0 ? void 0 : Math.round(raw.execution_duration * 1e3),
1073
+ raw
1074
+ };
1075
+ }
1076
+ const TOKEN_HEADER = "x-gitlab-token";
1077
+ /**
1078
+ * GitLab sends the configured secret verbatim in `X-Gitlab-Token`; there is no
1079
+ * body signature to compute.
1080
+ */
1081
+ async function verifyGitLabToken(delivery, secret) {
1082
+ return verifySharedToken(delivery, secret, TOKEN_HEADER);
1083
+ }
1084
+ const gitlabWebhooks = ({ options, instance }) => ({
1085
+ events: GITLAB_WEBHOOK_EVENTS,
1086
+ verify: (delivery) => verifyGitLabToken(delivery, options.webhookSecret),
1087
+ translate: async (delivery) => (await import("./events-uCMi3LHU-Bz79PQtq.js")).translateGitLabWebhook(instance, delivery)
1088
+ });
1089
+ const PROJECT_ORDER = {
1090
+ created: "created_at",
1091
+ updated: "updated_at",
1092
+ pushed: "last_activity_at",
1093
+ name: "name"
1094
+ };
1095
+ /** GitLab versions with the webhook event log and resend endpoints. */
1096
+ const GITLAB_HOOK_EVENTS = "17.0";
1097
+ const ISSUE_LIKE = {
1098
+ issue: true,
1099
+ pull_request: true
1100
+ };
1101
+ const STATE_EVENTS = {
1102
+ open: "reopen",
1103
+ closed: "close"
1104
+ };
1105
+ /** Access level per normalised role, as `POST /projects/:id/members` takes it. */
1106
+ const ACCESS_LEVELS = {
1107
+ admin: 50,
1108
+ maintain: 40,
1109
+ write: 30,
1110
+ triage: 20,
1111
+ read: 10,
1112
+ none: 0
1113
+ };
1114
+ /** GitLab awards emoji by name; these are the names behind the normalised reactions. */
1115
+ const AWARD_EMOJI = {
1116
+ "+1": "thumbsup",
1117
+ "-1": "thumbsdown",
1118
+ "laugh": "laughing",
1119
+ "confused": "confused",
1120
+ "heart": "heart",
1121
+ "hooray": "tada",
1122
+ "rocket": "rocket",
1123
+ "eyes": "eyes"
1124
+ };
1125
+ /** The model's name for each award emoji `forges` writes. */
1126
+ const REACTION_NAMES = Object.fromEntries(Object.entries(AWARD_EMOJI).map(([content, name]) => [name, content]));
1127
+ const VULNERABILITIES_QUERY = `query ProjectVulnerabilities($fullPath: ID!, $first: Int, $after: String, $state: [VulnerabilityState!], $reportType: [VulnerabilityReportType!]) {
1128
+ project(fullPath: $fullPath) {
1129
+ vulnerabilities(first: $first, after: $after, state: $state, reportType: $reportType) {
1130
+ pageInfo { hasNextPage endCursor }
1131
+ nodes { id title severity state reportType detectedAt updatedAt dismissedAt resolvedAt webUrl }
1132
+ }
1133
+ }
1134
+ }`;
1135
+ const PROJECTS_QUERY = `query CodeSearchProjects($ids: [ID!]) {
1136
+ projects(ids: $ids) {
1137
+ nodes { id fullPath }
1138
+ }
1139
+ }`;
1140
+ function threadPath(ref) {
1141
+ const project = `/projects/${projectId(ref.repo)}`;
1142
+ switch (ref.kind) {
1143
+ case "pull_request": return `${project}/merge_requests/${encodeURIComponent(ref.number)}`;
1144
+ default: return `${project}/issues/${encodeURIComponent(ref.number)}`;
1145
+ }
1146
+ }
1147
+ /** Creates a GitLab provider for gitlab.com or a self-managed instance. */
1148
+ const gitlab = /* @__PURE__ */ defineForgeProvider({
1149
+ forge: FORGE,
1150
+ hasWeb: true,
1151
+ baseUrl: "https://gitlab.com",
1152
+ anonymous: true,
1153
+ apiPath: "/api/v4",
1154
+ headers: { accept: "application/json" },
1155
+ webhooks: gitlabWebhooks,
1156
+ authHeaders: ({ options: { auth } }) => auth?.type === "token" ? async () => ({ authorization: `Bearer ${await resolveToken(auth)}` }) : void 0,
1157
+ setup({ options, instance, baseUrl, origin: context, fetcher }) {
1158
+ /** GitLab serves notes, labels, milestones, members, commit statuses, commit and code search and vulnerabilities only to signed-in users. */
1159
+ const anonymous = options.auth?.type === "anonymous";
1160
+ const web = GITLAB_WEB.links({
1161
+ baseUrl,
1162
+ instance
1163
+ });
1164
+ /**
1165
+ * GitLab lists pending and done to-dos separately. With `all`, pending
1166
+ * pages are followed by done pages; `cursor.token` marks the switch. Only
1167
+ * the pending listing on its own is conditional.
1168
+ */
1169
+ async function notificationPage(listOptions = {}) {
1170
+ const cursor = listOptions.cursor;
1171
+ const state = cursor?.token === "done" ? "done" : "pending";
1172
+ const conditional = !listOptions.all && isFirstPage(cursor);
1173
+ const result = await fetcher.json(cursor?.nextUrl ?? "/todos", {
1174
+ query: cursor?.nextUrl ? void 0 : {
1175
+ state,
1176
+ per_page: listOptions.perPage
1177
+ },
1178
+ etag: conditional ? firstPageEtag(cursor) : void 0,
1179
+ signal: listOptions.signal
1180
+ });
1181
+ const since = listOptions.since?.getTime();
1182
+ const items = (result.data ?? []).map((raw) => toNotification(instance, raw)).filter((item) => since === void 0 || item.updatedAt.getTime() >= since);
1183
+ const phase = cursor?.token ?? "pending";
1184
+ const next = result.cursor?.nextUrl ? {
1185
+ ...result.cursor,
1186
+ token: phase === "done" ? "done" : void 0
1187
+ } : listOptions.all && phase !== "done" ? { token: "done" } : void 0;
1188
+ const page = {
1189
+ items,
1190
+ cursor: result.notModified ? void 0 : next,
1191
+ notModified: result.notModified,
1192
+ ...rateLimitPart(result.response)
1193
+ };
1194
+ return conditional ? withEtag(page, result, cursor) : page;
1195
+ }
1196
+ /** GitLab assigns by user id, so logins are resolved once each. */
1197
+ /** Award emoji hang off the issue, the merge request or a note, all under the same path. */
1198
+ function awardPath(target) {
1199
+ return "thread" in target ? `${threadPath(requireIssueOrPull(target.thread, context, "react to"))}/notes/${target.id}` : threadPath(requireIssueOrPull(target, context, "react to"));
1200
+ }
1201
+ /** The authenticated username, read once; removing an award needs its id, which is found by owner. */
1202
+ const viewerLogin = memo(() => fetcher.json("/user").then((result) => result.data.username, () => void 0));
1203
+ const userIdByName = memoBy((username) => fetcher.json("/users", { query: { username } }).then(({ data }) => {
1204
+ if (!data[0]) throw new UnsupportedOperationError(`No GitLab user named ${username}`, context);
1205
+ return data[0].id;
1206
+ }));
1207
+ function userId(actor) {
1208
+ if (typeof actor !== "string" && /^\d+$/.test(actor.id)) return Promise.resolve(Number(actor.id));
1209
+ return userIdByName(typeof actor === "string" ? actor : actor.login);
1210
+ }
1211
+ const STATUS_STATES = {
1212
+ pending: "pending",
1213
+ success: "success",
1214
+ failure: "failed",
1215
+ neutral: "success",
1216
+ unknown: "pending"
1217
+ };
1218
+ const PIPELINE_STATES = {
1219
+ pending: "running",
1220
+ success: "success",
1221
+ failure: "failed",
1222
+ neutral: "manual",
1223
+ unknown: void 0
1224
+ };
1225
+ async function setDiscussionResolved(thread, id, resolved, options) {
1226
+ const ref = requireThread(thread, context);
1227
+ await fetcher.raw(`${threadPath(ref)}/discussions/${encodeURIComponent(id)}`, {
1228
+ method: "PUT",
1229
+ query: { resolved },
1230
+ signal: options?.signal
1231
+ });
1232
+ }
1233
+ const list = createListing(fetcher, "per_page");
1234
+ function milestonesPage(repo, listOptions = {}, includeAncestors) {
1235
+ return list(`${projectPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: {
1236
+ state: (listOptions.state ?? "open") === "all" ? void 0 : listOptions.state === "closed" ? "closed" : "active",
1237
+ include_ancestors: includeAncestors
1238
+ } });
1239
+ }
1240
+ async function readUser(path, signal) {
1241
+ const { data } = await fetcher.json(path, { signal });
1242
+ return {
1243
+ ...toActor(instance, data),
1244
+ bio: data.bio || void 0,
1245
+ company: data.organization || void 0,
1246
+ location: data.location || void 0,
1247
+ websiteUrl: data.website_url || void 0,
1248
+ createdAt: toDate(data.created_at),
1249
+ followers: data.followers,
1250
+ following: data.following,
1251
+ raw: data
1252
+ };
1253
+ }
1254
+ function projectPath(repo) {
1255
+ return `/projects/${projectId(repo)}`;
1256
+ }
1257
+ /**
1258
+ * The listing gives only names, group templates included, so every body costs one more request. A name in both
1259
+ * the project and a group reads as the group's template unless the project's id picks the project's own.
1260
+ */
1261
+ async function templates(repo, options = {}) {
1262
+ const signal = options.signal;
1263
+ const kinds = options.kind ? [options.kind] : ["issue", "pull_request"];
1264
+ return (await Promise.all(kinds.map(async (kind) => {
1265
+ const type = kind === "issue" ? "issues" : "merge_requests";
1266
+ const names = await Array.fromAsync(iteratePages((listOptions) => list(`${projectPath(repo)}/templates/${type}`, {
1267
+ ...listOptions,
1268
+ perPage: 100,
1269
+ signal
1270
+ }, (raw) => raw)));
1271
+ const keys = [...new Set(names.map(({ key }) => key))];
1272
+ const shared = keys.filter((key) => names.filter((name) => name.key === key).length > 1);
1273
+ const id = shared.length ? repo.externalId ?? String((await fetcher.json(projectPath(repo), { signal })).data.id) : void 0;
1274
+ const read = async (key, source) => {
1275
+ const { data } = await fetcher.json(`${projectPath(repo)}/templates/${type}/${encodeURIComponent(key)}`, {
1276
+ query: { source_template_project_id: source },
1277
+ signal
1278
+ });
1279
+ return {
1280
+ kind,
1281
+ name: data.name,
1282
+ format: "markdown",
1283
+ body: data.content,
1284
+ raw: data
1285
+ };
1286
+ };
1287
+ const [inherited, own] = await Promise.all([mapConcurrent(keys, 4, (key) => read(key)), mapConcurrent(shared, 4, (key) => read(key, id).catch((error) => {
1288
+ if (error instanceof NotFoundError) return;
1289
+ throw error;
1290
+ }))]);
1291
+ return [...inherited, ...own.filter((template) => template !== void 0)];
1292
+ }))).flat();
1293
+ }
1294
+ /** GitLab has no write that creates or updates, so each file is looked up first, at the commit the change builds on. */
1295
+ async function commitFiles(repo, input, options) {
1296
+ const signal = options?.signal;
1297
+ const start = input.createFrom === void 0 ? void 0 : (await fetcher.json(`${projectPath(repo)}/repository/commits/${encodeURIComponent(input.createFrom)}`, { signal })).data.id;
1298
+ if (input.expectedHead !== void 0) {
1299
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/branches/${encodeURIComponent(input.branch)}`, { signal });
1300
+ if (data.commit?.id !== input.expectedHead.toLowerCase()) throw new BranchMovedError(`${input.branch} is at ${data.commit?.id}, not ${input.expectedHead}`, 409, "", context);
1301
+ }
1302
+ const ref = start ?? input.expectedHead ?? input.branch;
1303
+ const existing = await existingFiles(input.changes, async (path) => {
1304
+ try {
1305
+ return await fetcher.raw(`${projectPath(repo)}/repository/files/${encodeURIComponent(path)}`, {
1306
+ method: "HEAD",
1307
+ query: { ref },
1308
+ signal
1309
+ });
1310
+ } catch (error) {
1311
+ if (error instanceof NotFoundError) return;
1312
+ throw error;
1313
+ }
1314
+ }, context);
1315
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/commits`, {
1316
+ method: "POST",
1317
+ json: {
1318
+ branch: input.branch,
1319
+ commit_message: input.message,
1320
+ ...start && { start_sha: start },
1321
+ ...input.author && {
1322
+ author_name: input.author.name,
1323
+ author_email: input.author.email
1324
+ },
1325
+ actions: input.changes.map(({ path, content }) => content === null ? {
1326
+ action: "delete",
1327
+ file_path: path
1328
+ } : {
1329
+ action: existing.has(path) ? "update" : "create",
1330
+ file_path: path,
1331
+ ...typeof content === "string" ? { content } : {
1332
+ content: changeBase64(content),
1333
+ encoding: "base64"
1334
+ }
1335
+ })
1336
+ },
1337
+ signal
1338
+ });
1339
+ return toCommit(repo, data);
1340
+ }
1341
+ async function ownerReposPage(owner, query = {}) {
1342
+ const read = (path, extra) => list(path, query, (raw) => toRepo(instance, raw), {
1343
+ query: {
1344
+ visibility: query.visibility === "all" ? void 0 : query.visibility,
1345
+ order_by: query.sort && PROJECT_ORDER[query.sort],
1346
+ sort: query.direction,
1347
+ ...extra
1348
+ },
1349
+ warnings: query.sort === "pushed" && isFirstPage(query.cursor) ? [{
1350
+ code: "sort_unsupported",
1351
+ message: "GitLab does not report pushes; sorted by last activity, which includes issues and merge requests"
1352
+ }] : void 0
1353
+ });
1354
+ try {
1355
+ return await read(`/groups/${encodeURIComponent(owner.externalId ?? owner.owner)}/projects`, {
1356
+ include_subgroups: query.subgroups || void 0,
1357
+ with_shared: false
1358
+ });
1359
+ } catch (error) {
1360
+ if (!(error instanceof NotFoundError) || !isFirstPage(query.cursor) || !owner.owner || owner.owner.includes("/")) throw error;
1361
+ }
1362
+ return read(`/users/${encodeURIComponent(owner.owner)}/projects`, {});
1363
+ }
1364
+ /** Project hooks, or group hooks for a namespace ref. */
1365
+ function hooksPath(target) {
1366
+ return isNamespaceRef(target) ? `/groups/${encodeURIComponent(target.externalId ?? target.owner)}/hooks` : `${projectPath(target)}/hooks`;
1367
+ }
1368
+ /** GitLab subscribes with one boolean per event group rather than a list of names. */
1369
+ function hookFlags(input) {
1370
+ return Object.fromEntries(nativeEventsFor(GITLAB_NATIVE_EVENTS, input.events, input.nativeEvents).map((flag) => [flag, true]));
1371
+ }
1372
+ function requireMerge(thread, action) {
1373
+ const ref = requireThread(thread, context);
1374
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only merge requests can be ${action}`, context);
1375
+ return ref;
1376
+ }
1377
+ /** GitLab's file endpoint needs an explicit ref, so the project's default branch stands in. */
1378
+ async function defaultBranch(repo, options) {
1379
+ const { data } = await fetcher.json(projectPath(repo), { signal: options?.signal });
1380
+ return data.default_branch ?? "HEAD";
1381
+ }
1382
+ async function get(thread, options) {
1383
+ const ref = requireThread(thread, context);
1384
+ if (ref.kind === "discussion") throw new UnsupportedOperationError("GitLab has no discussion threads", context);
1385
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1386
+ const result = toThread(ref, data);
1387
+ if (data.head_pipeline) result.checks = toPipelineSummary(data.head_pipeline);
1388
+ return result;
1389
+ }
1390
+ const graphqlUrl = `${baseUrl.replace(/\/api\/v4$/, "")}/api/graphql`;
1391
+ async function vulnerabilitiesPage(repo, listOptions = {}) {
1392
+ const state = listOptions.state ?? "open";
1393
+ const { data, response } = await fetcher.json(graphqlUrl, {
1394
+ method: "POST",
1395
+ json: {
1396
+ operationName: "ProjectVulnerabilities",
1397
+ query: VULNERABILITIES_QUERY,
1398
+ variables: {
1399
+ fullPath: `${repo.owner}/${repo.name}`,
1400
+ first: Math.min(listOptions.perPage ?? 50, 100),
1401
+ after: listOptions.cursor?.token ?? null,
1402
+ state: state === "open" ? ["DETECTED", "CONFIRMED"] : state === "closed" ? ["RESOLVED", "DISMISSED"] : null,
1403
+ reportType: listOptions.kind ? REPORT_TYPES[listOptions.kind] : null
1404
+ }
1405
+ },
1406
+ signal: listOptions.signal
1407
+ });
1408
+ const vulnerabilities = data.data?.project?.vulnerabilities;
1409
+ if (!vulnerabilities) {
1410
+ const error = new InsufficientScopeError(data.errors?.[0]?.message ?? "The token cannot read vulnerabilities for this project, or its licence has no vulnerability report", 403, "", context);
1411
+ if (listOptions.kind) throw error;
1412
+ return {
1413
+ items: [],
1414
+ warnings: [toWarning("insufficient_scope", error, `${repo.owner}/${repo.name}`)]
1415
+ };
1416
+ }
1417
+ return {
1418
+ items: vulnerabilities.nodes.map((node) => toVulnerability(repo, node)),
1419
+ cursor: vulnerabilities.pageInfo.hasNextPage && vulnerabilities.pageInfo.endCursor ? { token: vulnerabilities.pageInfo.endCursor } : void 0,
1420
+ ...rateLimitPart(response)
1421
+ };
1422
+ }
1423
+ async function releasesPage(repo, listOptions = {}) {
1424
+ return list(`${projectPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
1425
+ }
1426
+ function requirePublishedRelease(input) {
1427
+ if (input.draft) throw new UnsupportedOperationError("GitLab has no draft releases", context);
1428
+ if (input.prerelease) throw new UnsupportedOperationError("GitLab has no prereleases", context);
1429
+ }
1430
+ async function listPage(repo, query = {}) {
1431
+ if (query.kind === "discussion") return {
1432
+ items: [],
1433
+ warnings: [{
1434
+ code: "kind_unsupported",
1435
+ message: "GitLab has no discussion threads"
1436
+ }]
1437
+ };
1438
+ const warnings = isFirstPage(query.cursor) && query.sort === "comments" ? [{
1439
+ code: "sort_unsupported",
1440
+ message: "GitLab cannot sort by comment count; sorted by creation time"
1441
+ }] : [];
1442
+ const state = query.state ?? "open";
1443
+ const kinds = query.kind ? [query.kind] : ["issue", "pull_request"];
1444
+ const page = await phased(kinds.map((kind) => async (cursor) => {
1445
+ const merges = kind === "pull_request";
1446
+ const result = await fetcher.page(`${projectPath(repo)}/${merges ? "merge_requests" : "issues"}`, {
1447
+ query: {
1448
+ state: state === "open" ? "opened" : state === "merged" ? "merged" : state === "closed" && !merges ? "closed" : void 0,
1449
+ labels: query.labels?.join(","),
1450
+ author_username: query.author,
1451
+ assignee_username: query.assignee,
1452
+ updated_after: query.since?.toISOString(),
1453
+ created_after: query.createdAfter?.toISOString(),
1454
+ order_by: query.sort === "updated" ? "updated_at" : "created_at",
1455
+ sort: query.direction ?? "desc",
1456
+ per_page: query.perPage
1457
+ },
1458
+ cursor,
1459
+ signal: query.signal
1460
+ });
1461
+ return toPage(result, (raw) => merges && state === "closed" && raw.state === "opened" ? void 0 : toThread({
1462
+ forge: FORGE,
1463
+ instance,
1464
+ repo,
1465
+ kind,
1466
+ number: String(raw.iid)
1467
+ }, raw));
1468
+ }), query.cursor);
1469
+ return warnings.length ? {
1470
+ ...page,
1471
+ warnings
1472
+ } : page;
1473
+ }
1474
+ /** Cross-project search runs on the global issue and merge request listings, which take `search` and `in`. */
1475
+ async function searchThreadsPage(query) {
1476
+ const warnings = [];
1477
+ if (isFirstPage(query.cursor) && query.involves) warnings.push({
1478
+ code: "filter_unsupported",
1479
+ message: "GitLab has no involves filter; it was ignored"
1480
+ });
1481
+ if (isFirstPage(query.cursor) && query.sort === "comments") warnings.push({
1482
+ code: "sort_unsupported",
1483
+ message: "GitLab cannot sort by comment count; sorted by update time"
1484
+ });
1485
+ const state = query.state ?? "all";
1486
+ const kinds = query.kind ? [query.kind] : ["issue", "pull_request"];
1487
+ const page = await phased(kinds.map((kind) => async (cursor) => {
1488
+ const merges = kind === "pull_request";
1489
+ const base = query.repo ? `${projectPath(query.repo)}/` : query.owner ? `/groups/${encodeURIComponent(query.owner)}/` : "/";
1490
+ const result = await fetcher.page(`${base}${merges ? "merge_requests" : "issues"}`, {
1491
+ query: {
1492
+ scope: query.repo ? void 0 : "all",
1493
+ search: query.text,
1494
+ in: query.text ? "title,description" : void 0,
1495
+ state: state === "open" ? "opened" : state === "closed" ? "closed" : void 0,
1496
+ labels: query.labels?.join(","),
1497
+ author_username: query.author,
1498
+ assignee_username: query.assignee,
1499
+ updated_after: query.since?.toISOString(),
1500
+ order_by: query.sort === "created" ? "created_at" : "updated_at",
1501
+ sort: query.direction ?? "desc",
1502
+ per_page: query.perPage
1503
+ },
1504
+ cursor,
1505
+ signal: query.signal
1506
+ });
1507
+ return toPage(result, (raw) => {
1508
+ const repo = query.repo ?? repoRefFromWebUrl(instance, raw.web_url, merges ? raw.target_project_id : void 0);
1509
+ return repo ? toThread({
1510
+ forge: FORGE,
1511
+ instance,
1512
+ repo,
1513
+ kind,
1514
+ number: String(raw.iid)
1515
+ }, raw) : void 0;
1516
+ });
1517
+ }), query.cursor);
1518
+ return warnings.length ? {
1519
+ ...page,
1520
+ warnings: [...warnings, ...page.warnings ?? []]
1521
+ } : page;
1522
+ }
1523
+ async function searchReposPage(query) {
1524
+ const path = query.owner ? `/groups/${encodeURIComponent(query.owner)}/projects` : "/projects";
1525
+ const result = await fetcher.page(path, {
1526
+ query: {
1527
+ search: query.text,
1528
+ order_by: query.sort === "created" ? "created_at" : query.sort === "stars" ? "star_count" : query.sort === "updated" ? "updated_at" : void 0,
1529
+ sort: query.direction,
1530
+ per_page: query.perPage
1531
+ },
1532
+ cursor: query.cursor,
1533
+ signal: query.signal
1534
+ });
1535
+ return toPage(result, (raw) => toRepo(instance, raw));
1536
+ }
1537
+ /** Needs Advanced Search, which no endpoint reports; an instance without it returns an empty page. */
1538
+ async function searchCommitsPage(query) {
1539
+ const unsupported = [
1540
+ "author",
1541
+ "committer",
1542
+ "since",
1543
+ "until",
1544
+ "sort"
1545
+ ].filter((field) => query[field] !== void 0);
1546
+ const warnings = unsupported.length ? [{
1547
+ code: "filter_unsupported",
1548
+ message: `GitLab commit search cannot filter or sort by ${unsupported.join(", ")}`
1549
+ }] : [];
1550
+ const result = await fetcher.page(query.repo ? `${projectPath(query.repo)}/search` : "/search", {
1551
+ query: {
1552
+ scope: "commits",
1553
+ search: query.text ?? "",
1554
+ per_page: query.perPage
1555
+ },
1556
+ cursor: query.cursor,
1557
+ signal: query.signal
1558
+ });
1559
+ const repo = query.repo;
1560
+ return toPage(result, (raw) => repo && toCommit(repo, raw), warnings);
1561
+ }
1562
+ /** Projects that code searches and user events named by id, kept so later pages skip the lookup. */
1563
+ const projectRefs = /* @__PURE__ */ new Map();
1564
+ /** A project the token cannot read costs its blobs and a warning, not the page. */
1565
+ async function resolveProjects(ids, signal, warnings) {
1566
+ if (!ids.length) return;
1567
+ try {
1568
+ const { data } = await fetcher.json(graphqlUrl, {
1569
+ method: "POST",
1570
+ json: {
1571
+ operationName: "CodeSearchProjects",
1572
+ query: PROJECTS_QUERY,
1573
+ variables: { ids: ids.map((id) => `gid://gitlab/Project/${id}`) }
1574
+ },
1575
+ signal
1576
+ });
1577
+ for (const node of data.data?.projects?.nodes ?? []) {
1578
+ const id = Number(node.id.slice(node.id.lastIndexOf("/") + 1));
1579
+ projectRefs.set(id, toRepoRef(instance, node.fullPath, id));
1580
+ }
1581
+ } catch (error) {
1582
+ if (!degradesToWarning(error)) throw error;
1583
+ warnings.push(...ids.map((id) => toWarning("record_unreachable", error, `project ${id}`)));
1584
+ return;
1585
+ }
1586
+ for (const id of ids.filter((id) => !projectRefs.has(id))) warnings.push({
1587
+ code: "record_unreachable",
1588
+ message: "GitLab returned no project for this id",
1589
+ subject: `project ${id}`
1590
+ });
1591
+ }
1592
+ /** Any tier searches a project; a group or the instance needs Advanced Search or exact code search. */
1593
+ async function searchCodePage(query) {
1594
+ const path = query.repo ? `${projectPath(query.repo)}/search` : query.owner ? `/groups/${encodeURIComponent(query.owner)}/search` : "/search";
1595
+ const result = await fetcher.page(path, {
1596
+ query: {
1597
+ scope: "blobs",
1598
+ search: query.text ?? "",
1599
+ per_page: query.perPage
1600
+ },
1601
+ cursor: query.cursor,
1602
+ signal: query.signal
1603
+ });
1604
+ const warnings = [];
1605
+ await resolveProjects(query.repo ? [] : [...new Set((result.data ?? []).map((raw) => raw.project_id))].filter((id) => !projectRefs.has(id)), query.signal, warnings);
1606
+ /** GitLab returns one blob per excerpt; basic search lists a file again, with the same first excerpt, when its name matches too. */
1607
+ const files = /* @__PURE__ */ new Map();
1608
+ for (const blob of result.data ?? []) {
1609
+ const key = `${blob.project_id}:${blob.ref}:${blob.path}`;
1610
+ const excerpts = files.get(key);
1611
+ if (!excerpts) files.set(key, [blob]);
1612
+ else if (!excerpts.some((seen) => seen.startline === blob.startline && seen.data === blob.data)) excerpts.push(blob);
1613
+ }
1614
+ return toPage({
1615
+ ...result,
1616
+ data: [...files.values()]
1617
+ }, (excerpts) => {
1618
+ const [first] = excerpts;
1619
+ const repo = query.repo ?? projectRefs.get(first.project_id);
1620
+ if (!repo) return;
1621
+ const url = webUrlFor(web, { file: {
1622
+ repo,
1623
+ path: first.path,
1624
+ at: first.ref,
1625
+ line: first.startline
1626
+ } });
1627
+ return {
1628
+ repo,
1629
+ path: first.path,
1630
+ ref: first.ref,
1631
+ fragments: excerpts.map((raw) => ({
1632
+ text: raw.data,
1633
+ line: raw.startline
1634
+ })),
1635
+ url,
1636
+ raw: excerpts
1637
+ };
1638
+ }, warnings);
1639
+ }
1640
+ /** A user's events name each project by id alone, so the page resolves the ids it has not seen. */
1641
+ async function feedPage(path, listOptions, repo) {
1642
+ const result = await fetcher.page(path, {
1643
+ query: { per_page: listOptions.perPage },
1644
+ cursor: listOptions.cursor,
1645
+ signal: listOptions.signal
1646
+ });
1647
+ const warnings = [];
1648
+ if (!repo) await resolveProjects([...new Set((result.data ?? []).flatMap((raw) => typeof raw.project_id === "number" ? [raw.project_id] : []))].filter((id) => !projectRefs.has(id)), listOptions.signal, warnings);
1649
+ const { toFeedEvent } = await import("./feed-BlzdKdNv-DbxuSgsx.js");
1650
+ return toPage(result, (raw) => toFeedEvent(instance, raw, repo ?? (typeof raw.project_id === "number" ? projectRefs.get(raw.project_id) : void 0)), warnings);
1651
+ }
1652
+ async function setSubscribed(thread, subscribed, options) {
1653
+ const ref = requireIssueOrPull(thread, context, subscribed ? "subscribe to" : "unsubscribe from");
1654
+ await fetcher.raw(`${threadPath(ref)}/${subscribed ? "subscribe" : "unsubscribe"}`, {
1655
+ method: "POST",
1656
+ signal: options?.signal
1657
+ });
1658
+ }
1659
+ async function unsubscribe(_ref, writeOptions = {}) {
1660
+ if (!writeOptions.thread) throw new UnresolvedThreadError("GitLab cannot look up a to-do by id; pass { thread } to unsubscribe", context);
1661
+ const thread = requireThread(writeOptions.thread, context);
1662
+ if (thread.kind !== "issue" && thread.kind !== "pull_request") throw new UnsupportedOperationError(`GitLab cannot unsubscribe from a ${thread.kind}`, context);
1663
+ await fetcher.raw(`${threadPath(thread)}/unsubscribe`, {
1664
+ method: "POST",
1665
+ signal: writeOptions.signal
1666
+ });
1667
+ }
1668
+ async function setState(thread, stateEvent, options) {
1669
+ const ref = requireIssueOrPull(thread, context, stateEvent);
1670
+ const { data } = await fetcher.json(threadPath(ref), {
1671
+ method: "PUT",
1672
+ json: { state_event: stateEvent },
1673
+ signal: options?.signal
1674
+ });
1675
+ return toThread(ref, data);
1676
+ }
1677
+ async function setLocked(thread, locked, options) {
1678
+ const ref = requireIssueOrPull(thread, context, locked ? "lock" : "unlock");
1679
+ await fetcher.raw(threadPath(ref), {
1680
+ method: "PUT",
1681
+ json: { discussion_locked: locked },
1682
+ signal: options?.signal
1683
+ });
1684
+ }
1685
+ async function resolveMergeMethod(ref, requested, signal) {
1686
+ if (requested === "squash") return requested;
1687
+ const { data: project } = await fetcher.json(`/projects/${projectId(ref.repo)}`, { signal });
1688
+ const base = BASE_METHODS[project.merge_method ?? "merge"];
1689
+ const squash = project.squash_option ?? "default_off";
1690
+ if (requested) {
1691
+ if (requested !== base || squash === "always") throw new UnsupportedOperationError(`This project merges with ${squash === "always" ? "squash" : base}; GitLab cannot override it per merge request`, context);
1692
+ return requested;
1693
+ }
1694
+ return soleMergeMethod({
1695
+ [base]: squash !== "always",
1696
+ squash: squash !== "never"
1697
+ }, context);
1698
+ }
1699
+ /** GitLab has approvals, not reviews: one synthesised review per approver, with no comments to hang on it. */
1700
+ function toApprovalReviews(ref, approvals) {
1701
+ return (approvals.approved_by ?? []).map(({ user }) => syntheticReview(ref, approvalId(user), "approved", {
1702
+ author: toActor(instance, user),
1703
+ stateRaw: "approved",
1704
+ raw: user
1705
+ }));
1706
+ }
1707
+ async function approve(thread, body, options) {
1708
+ const ref = requireThread(thread, context);
1709
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be approved", context);
1710
+ if (body) throw new UnsupportedOperationError("GitLab approvals carry no body; leave a comment instead", context);
1711
+ const { data } = await fetcher.json(`${threadPath(ref)}/approve`, {
1712
+ method: "POST",
1713
+ signal: options?.signal,
1714
+ mapError: (error) => error instanceof TokenRevokedError ? new InsufficientScopeError("Not allowed to approve this merge request", 401, error.body, {
1715
+ ...context,
1716
+ url: error.url,
1717
+ method: error.method
1718
+ }, { cause: error }) : error
1719
+ });
1720
+ const reviews = toApprovalReviews(ref, data);
1721
+ const viewer = reviews.length > 1 ? await viewerLogin() : void 0;
1722
+ return reviews.find((review) => viewer !== void 0 && review.author?.login === viewer) ?? reviews.at(-1) ?? {
1723
+ ref: {
1724
+ forge: "gitlab",
1725
+ instance,
1726
+ thread: ref,
1727
+ id: "approval:"
1728
+ },
1729
+ state: "approved",
1730
+ stateRaw: "approved",
1731
+ comments: false,
1732
+ raw: data
1733
+ };
1734
+ }
1735
+ async function merge(thread, mergeOptions = {}) {
1736
+ const ref = requireThread(thread, context);
1737
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be merged", context);
1738
+ const method = await resolveMergeMethod(ref, mergeOptions.method, mergeOptions.signal);
1739
+ const message = mergeCommitMessage(mergeOptions);
1740
+ const { data } = await fetcher.json(`${threadPath(ref)}/merge`, {
1741
+ method: "PUT",
1742
+ json: {
1743
+ sha: mergeOptions.sha,
1744
+ ...message ? { [method === "squash" ? "squash_commit_message" : "merge_commit_message"]: message } : {},
1745
+ squash: method === "squash",
1746
+ merge_when_pipeline_succeeds: mergeOptions.whenChecksPass ?? false
1747
+ },
1748
+ mapError: toMergeError,
1749
+ signal: mergeOptions.signal
1750
+ });
1751
+ return data.state === "merged" ? {
1752
+ status: "merged",
1753
+ sha: data.merge_commit_sha ?? data.squash_commit_sha ?? void 0,
1754
+ raw: data
1755
+ } : {
1756
+ status: "queued",
1757
+ raw: data
1758
+ };
1759
+ }
1760
+ /** An issue or merge request from a listing that spans projects, or `undefined` for one from an external issue tracker. */
1761
+ function referencedThread(raw, kind) {
1762
+ const path = raw.references?.full?.replace(/[#!]\d+$/, "");
1763
+ const project = kind === "pull_request" ? raw.target_project_id : raw.project_id;
1764
+ const repo = path ? toRepoRef(instance, path, project) : repoRefFromWebUrl(instance, raw.web_url, project);
1765
+ return repo && raw.iid !== void 0 ? toThread({
1766
+ forge: FORGE,
1767
+ instance,
1768
+ repo,
1769
+ kind,
1770
+ number: String(raw.iid)
1771
+ }, raw) : void 0;
1772
+ }
1773
+ /** GitLab rebases only, in the background, and takes no expected head, so `sha` is compared against a read of the merge request first. */
1774
+ async function updateBranch(thread, updateOptions = {}) {
1775
+ const ref = requireThread(thread, context);
1776
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be updated", context);
1777
+ if (updateOptions.method === "merge") throw new UnsupportedOperationError("GitLab updates a merge request by rebasing it only", context);
1778
+ const { sha, signal } = updateOptions;
1779
+ if (sha !== void 0) {
1780
+ const { data } = await fetcher.json(threadPath(ref), { signal });
1781
+ if (data.sha !== sha) throw new BranchMovedError(`Source branch of merge request ${ref.number} is at ${data.sha}, not ${sha}`, 409, "", context);
1782
+ }
1783
+ const { data } = await fetcher.json(`${threadPath(ref)}/rebase`, {
1784
+ method: "PUT",
1785
+ signal
1786
+ });
1787
+ return {
1788
+ status: "queued",
1789
+ raw: data
1790
+ };
1791
+ }
1792
+ return {
1793
+ traits: {
1794
+ eventKinds: "heuristic",
1795
+ authKinds: ["token", "anonymous"],
1796
+ limits: {
1797
+ bodyLength: 1048576,
1798
+ commentLength: 1e6,
1799
+ labelLength: 255
1800
+ }
1801
+ },
1802
+ notApplicable: ["threads.hideComment"],
1803
+ probeVersion: async () => (await fetcher.json("/version")).data.version,
1804
+ web,
1805
+ webhooks: {
1806
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw))),
1807
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
1808
+ method: "POST",
1809
+ json: {
1810
+ url: input.url,
1811
+ token: input.secret,
1812
+ ...hookFlags(input)
1813
+ },
1814
+ signal: options?.signal
1815
+ })).data)),
1816
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${ref.id}`, {
1817
+ method: "PUT",
1818
+ json: {
1819
+ ...update.url ? { url: update.url } : {},
1820
+ ...update.secret ? { token: update.secret } : {},
1821
+ ...hookFlags(update)
1822
+ },
1823
+ signal: options?.signal
1824
+ })).data)),
1825
+ delete: verb(true, async (ref, options) => {
1826
+ await fetcher.raw(`${hooksPath(ref.target)}/${ref.id}`, {
1827
+ method: "DELETE",
1828
+ signal: options?.signal
1829
+ });
1830
+ }),
1831
+ rotateSecret: verb(true, async (ref, secret, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${ref.id}`, {
1832
+ method: "PUT",
1833
+ json: { token: secret },
1834
+ signal: options?.signal
1835
+ })).data)),
1836
+ deliveriesPage: verb(({ version }) => versionAtLeast(version, GITLAB_HOOK_EVENTS), (ref, listOptions = {}) => list(`${hooksPath(ref.target)}/${ref.id}/events`, listOptions, (raw) => toWebhookDelivery(ref, raw))),
1837
+ redeliver: verb(({ version }) => versionAtLeast(version, GITLAB_HOOK_EVENTS), async (ref, options) => {
1838
+ await fetcher.raw(`${hooksPath(ref.hook.target)}/${ref.hook.id}/events/${ref.id}/resend`, {
1839
+ method: "POST",
1840
+ signal: options?.signal
1841
+ });
1842
+ })
1843
+ },
1844
+ scopes: gitlabScopesFor,
1845
+ users: {
1846
+ get: verb(true, async (login, options) => {
1847
+ const { data: matches } = await fetcher.json("/users", {
1848
+ query: { username: login },
1849
+ signal: options?.signal
1850
+ });
1851
+ const [match] = matches ?? [];
1852
+ if (!match) throw new NotFoundError(`No GitLab user named ${login}`, 404, "", context);
1853
+ try {
1854
+ return await readUser(`/users/${match.id}`, options?.signal);
1855
+ } catch (error) {
1856
+ if (error instanceof InsufficientScopeError || error instanceof AuthenticationRequiredError) return {
1857
+ ...toActor(instance, match),
1858
+ raw: match
1859
+ };
1860
+ throw error;
1861
+ }
1862
+ }),
1863
+ me: verb(true, (options) => readUser("/user", options?.signal)),
1864
+ eventsPage: verb(true, (login, listOptions = {}) => feedPage(`/users/${encodeURIComponent(login)}/events`, listOptions))
1865
+ },
1866
+ repos: {
1867
+ get: verb(true, async (ref, options) => {
1868
+ const query = options?.licence ? { license: true } : void 0;
1869
+ return toRepo(instance, (await fetcher.json(projectPath(ref), {
1870
+ query,
1871
+ signal: options?.signal
1872
+ })).data);
1873
+ }),
1874
+ listPage: verb(true, (listOptions = {}) => list("/projects", listOptions, (raw) => toRepo(instance, raw), { query: { membership: true } })),
1875
+ byOwnerPage: verb(true, ownerReposPage),
1876
+ labelsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${projectPath(repo)}/labels`, listOptions, toLabel)),
1877
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${projectPath(repo)}/labels`, {
1878
+ method: "POST",
1879
+ json: {
1880
+ name: label.name,
1881
+ color: hexColour(label.colour, "#"),
1882
+ description: label.description
1883
+ },
1884
+ signal: options?.signal
1885
+ })).data)),
1886
+ milestonesPage: verb(!anonymous, milestonesPage),
1887
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${projectPath(repo)}/members/all`, listOptions, (raw) => ({
1888
+ actor: toActor(instance, raw),
1889
+ role: toRole(raw.access_level),
1890
+ roleRaw: String(raw.access_level),
1891
+ raw
1892
+ }))),
1893
+ templates: verb(true, templates),
1894
+ contributorsPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/contributors`, listOptions, (raw) => ({
1895
+ name: raw.name || void 0,
1896
+ email: raw.email || void 0,
1897
+ contributions: raw.commits,
1898
+ raw
1899
+ }), {
1900
+ query: {
1901
+ order_by: "commits",
1902
+ sort: "desc"
1903
+ },
1904
+ warnings: listOptions.includeUnlinked === false && isFirstPage(listOptions.cursor) ? [{
1905
+ code: "filter_unsupported",
1906
+ message: "GitLab links no contributor accounts, so it cannot leave the unlinked ones out; the option was ignored"
1907
+ }] : []
1908
+ })),
1909
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
1910
+ try {
1911
+ const { data } = await fetcher.json(`${projectPath(repo)}/members/all/${await userId(actor)}`, { signal: options?.signal });
1912
+ return toRole(data.access_level);
1913
+ } catch (error) {
1914
+ if (error instanceof NotFoundError) return "none";
1915
+ throw error;
1916
+ }
1917
+ }),
1918
+ branchRules: verb(!anonymous, async (repo, name, options) => {
1919
+ const warnings = [];
1920
+ const [{ data: branch }, { data: project }, rules] = await Promise.all([
1921
+ fetcher.json(`${projectPath(repo)}/repository/branches/${encodeURIComponent(name)}`, { signal: options?.signal }),
1922
+ fetcher.json(projectPath(repo), { signal: options?.signal }),
1923
+ Array.fromAsync(fetcher.items(`${projectPath(repo)}/approval_rules`, {
1924
+ query: { per_page: 100 },
1925
+ signal: options?.signal
1926
+ })).catch((error) => {
1927
+ if (!(error instanceof ForbiddenError || error instanceof InsufficientScopeError || error instanceof NotFoundError)) throw error;
1928
+ warnings.push(toWarning("insufficient_scope", error, "approval_rules"));
1929
+ })
1930
+ ]);
1931
+ return toBranchRules(branch, project, rules, warnings);
1932
+ }),
1933
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
1934
+ await fetcher.raw(`${projectPath(repo)}/members`, {
1935
+ method: "POST",
1936
+ json: {
1937
+ user_id: await userId(actor),
1938
+ access_level: ACCESS_LEVELS[role]
1939
+ },
1940
+ signal: options?.signal
1941
+ });
1942
+ return { status: "added" };
1943
+ }),
1944
+ assignableUsersPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/users`, listOptions, (raw) => toActor(instance, raw))),
1945
+ reviewerCandidatesPage: verb("emulated", (thread, listOptions = {}) => list(`${projectPath(requireThread(thread, context).repo)}/users`, listOptions, (raw) => toActor(instance, raw))),
1946
+ eventsPage: verb(true, (repo, listOptions = {}) => feedPage(`${projectPath(repo)}/events`, listOptions, repo))
1947
+ },
1948
+ orgs: {
1949
+ /** GitLab has no teams, so a subgroup stands in for one. With a token, GitLab lists only the account's own subgroups unless `all_available` is set. */
1950
+ teamsPage: verb(true, (org, listOptions = {}) => list(`/groups/${encodeURIComponent(org.externalId ?? org.owner)}/descendant_groups`, listOptions, (raw) => toTeam(instance, teamOrg(org), raw), { query: { all_available: true } })),
1951
+ teamMembersPage: verb(!anonymous, (team, listOptions = {}) => list(`/groups/${encodeURIComponent(team.id ?? `${team.org.owner}/${team.slug}`)}/members`, listOptions, (raw) => toActor(instance, raw)))
1952
+ },
1953
+ notifications: {
1954
+ listPage: verb(true, notificationPage),
1955
+ markDone: verb(true, async (ref, options) => {
1956
+ await fetcher.raw(`/todos/${ref.id}/mark_as_done`, {
1957
+ method: "POST",
1958
+ signal: options?.signal
1959
+ });
1960
+ }),
1961
+ unsubscribe: verb(true, unsubscribe),
1962
+ markAllDone: verb(true, async (bulk = {}) => {
1963
+ if (bulk.repo || bulk.before) throw new UnsupportedOperationError("GitLab marks every to-do done at once; repo and before filters are not supported", context);
1964
+ await fetcher.raw("/todos/mark_as_done", {
1965
+ method: "POST",
1966
+ signal: bulk.signal
1967
+ });
1968
+ }),
1969
+ unreadCount: verb(true, async (options) => {
1970
+ const total = (await fetcher.raw("/todos", {
1971
+ query: {
1972
+ state: "pending",
1973
+ per_page: 1
1974
+ },
1975
+ signal: options?.signal
1976
+ })).headers.get("x-total");
1977
+ if (total === null) throw new UnsupportedOperationError("GitLab omitted X-Total; the to-do count is too large to report", context);
1978
+ return Number(total);
1979
+ })
1980
+ },
1981
+ contents: {
1982
+ getFile: verb(true, async (repo, path, fileOptions = {}) => {
1983
+ const target = `${projectPath(repo)}/repository/files/${encodeURIComponent(path.replace(/^\//, ""))}`;
1984
+ if (fileOptions.metadata === false) {
1985
+ const response = await fetcher.raw(`${target}/raw`, {
1986
+ query: { ref: fileOptions.ref },
1987
+ signal: fileOptions.signal
1988
+ });
1989
+ const bytes = new Uint8Array(await response.arrayBuffer());
1990
+ return toFileContent(bytes, {
1991
+ path: path.replace(/^\//, ""),
1992
+ size: bytes.byteLength
1993
+ }, fileOptions, context);
1994
+ }
1995
+ const ref = fileOptions.ref ?? await defaultBranch(repo, fileOptions);
1996
+ const { data } = await fetcher.json(target, {
1997
+ query: { ref },
1998
+ signal: fileOptions.signal
1999
+ });
2000
+ const file = {
2001
+ path: data.file_path,
2002
+ sha: data.blob_id,
2003
+ size: data.size
2004
+ };
2005
+ return toFileContent(fromBase64(data.content ?? ""), file, fileOptions, context);
2006
+ }),
2007
+ treePage: verb(true, (repo, treeOptions = {}) => list(`${projectPath(repo)}/repository/tree`, treeOptions, toTreeEntry, { query: {
2008
+ ref: treeOptions.ref,
2009
+ path: treeOptions.path,
2010
+ recursive: treeOptions.recursive ? "true" : void 0
2011
+ } })),
2012
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/branches`, listOptions, toBranch)),
2013
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/tags`, listOptions, toTag)),
2014
+ resolveRef: verb(true, async (repo, ref, options) => (await fetcher.json(`${projectPath(repo)}/repository/commits/${encodeURIComponent(ref)}`, { signal: options?.signal })).data.id),
2015
+ compare: verb(true, async (repo, base, head, options) => {
2016
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/compare`, {
2017
+ query: {
2018
+ from: base,
2019
+ to: head
2020
+ },
2021
+ signal: options?.signal
2022
+ });
2023
+ return {
2024
+ base,
2025
+ head,
2026
+ aheadBy: data.commits?.length,
2027
+ commits: (data.commits ?? []).map((raw) => toCommit(repo, raw)).toReversed(),
2028
+ files: (data.diffs ?? []).map(toChangedFile),
2029
+ raw: data
2030
+ };
2031
+ }),
2032
+ commitFiles: verb(true, commitFiles)
2033
+ },
2034
+ commits: {
2035
+ listPage: verb(true, (repo, query = {}) => list(`${projectPath(repo)}/repository/commits`, query, (raw) => toCommit(repo, raw), { query: {
2036
+ ref_name: query.ref,
2037
+ path: query.path,
2038
+ author: query.author,
2039
+ since: query.since?.toISOString(),
2040
+ until: query.until?.toISOString()
2041
+ } })),
2042
+ get: verb(true, async ({ repo, sha }, options) => {
2043
+ const [commit, diffs] = await Promise.all([fetcher.json(`${projectPath(repo)}/repository/commits/${sha}`, {
2044
+ query: { stats: "true" },
2045
+ signal: options?.signal
2046
+ }), fetcher.json(`${projectPath(repo)}/repository/commits/${sha}/diff`, { signal: options?.signal })]);
2047
+ return toCommit(repo, commit.data, (diffs.data ?? []).map(toChangedFile));
2048
+ }),
2049
+ commentsPage: verb(true, (commit, listOptions = {}) => list(`${projectPath(commit.repo)}/repository/commits/${encodeURIComponent(commit.sha)}/comments`, listOptions, (comment) => toCommitComment(commit, comment))),
2050
+ createComment: verb(true, async (commit, body, options) => {
2051
+ const { data } = await fetcher.json(`${projectPath(commit.repo)}/repository/commits/${encodeURIComponent(commit.sha)}/comments`, {
2052
+ method: "POST",
2053
+ json: { note: body },
2054
+ signal: options?.signal
2055
+ });
2056
+ return toCommitComment(commit, data);
2057
+ })
2058
+ },
2059
+ releases: {
2060
+ listPage: verb(true, releasesPage),
2061
+ get: verb(true, async (ref, options) => toRelease(ref.repo, (await fetcher.json(`${projectPath(ref.repo)}/releases/${encodeURIComponent(ref.tag ?? ref.id)}`, { signal: options?.signal })).data)),
2062
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${projectPath(repo)}/releases/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
2063
+ latest: verb(true, async (repo, options) => {
2064
+ const [newest] = (await releasesPage(repo, {
2065
+ perPage: 1,
2066
+ signal: options?.signal
2067
+ })).items;
2068
+ if (!newest || newest.publishedAt) return newest;
2069
+ return (await releasesPage(repo, {
2070
+ perPage: 20,
2071
+ signal: options?.signal
2072
+ })).items.find((release) => release.publishedAt);
2073
+ }),
2074
+ create: verb(true, async (repo, input, options) => {
2075
+ requirePublishedRelease(input);
2076
+ const { data } = await fetcher.json(`${projectPath(repo)}/releases`, {
2077
+ method: "POST",
2078
+ json: {
2079
+ tag_name: input.tag,
2080
+ ref: input.target,
2081
+ name: input.name,
2082
+ description: input.body
2083
+ },
2084
+ signal: options?.signal
2085
+ });
2086
+ return toRelease(repo, data);
2087
+ }),
2088
+ update: verb(true, async (ref, update, options) => {
2089
+ requirePublishedRelease(update);
2090
+ const tag = ref.tag ?? ref.id;
2091
+ if (update.tag !== void 0 && update.tag !== tag) throw new UnsupportedOperationError("GitLab keys a release by its tag, so the tag cannot change", context);
2092
+ if (update.target !== void 0) throw new UnsupportedOperationError("GitLab cannot change the commit a release points to", context);
2093
+ const { data } = await fetcher.json(`${projectPath(ref.repo)}/releases/${encodeURIComponent(tag)}`, {
2094
+ method: "PUT",
2095
+ json: {
2096
+ name: update.name,
2097
+ description: update.body
2098
+ },
2099
+ signal: options?.signal
2100
+ });
2101
+ return toRelease(ref.repo, data);
2102
+ })
2103
+ },
2104
+ search: {
2105
+ threadsPage: verb(true, searchThreadsPage),
2106
+ reposPage: verb(true, searchReposPage),
2107
+ commitsPage: verb(!anonymous && "experimental", searchCommitsPage),
2108
+ codePage: verb(!anonymous, searchCodePage)
2109
+ },
2110
+ checks: {
2111
+ list: verb(!anonymous, async (repo, sha, options) => ({ items: await Array.fromAsync(fetcher.items(`${projectPath(repo)}/repository/commits/${sha}/statuses`, {
2112
+ query: { per_page: 100 },
2113
+ signal: options?.signal
2114
+ }), (raw) => toStatusCheck(repo, raw)) })),
2115
+ report: verb(true, async (repo, sha, input, options) => toStatusCheck(repo, (await fetcher.json(`${projectPath(repo)}/statuses/${sha}`, {
2116
+ method: "POST",
2117
+ json: {
2118
+ state: STATUS_STATES[input.state],
2119
+ name: input.name,
2120
+ description: input.description,
2121
+ target_url: input.url
2122
+ },
2123
+ signal: options?.signal
2124
+ })).data)),
2125
+ rerun: verb(true, async (ref, options) => {
2126
+ if (ref.type !== "job" && ref.type !== "status") throw new UnsupportedOperationError(`GitLab cannot re-run a ${ref.type}`, context);
2127
+ await fetcher.raw(`${projectPath(ref.repo)}/jobs/${ref.id}/retry`, {
2128
+ method: "POST",
2129
+ signal: options?.signal
2130
+ });
2131
+ })
2132
+ },
2133
+ ci: {
2134
+ runsPage: verb(true, (repo, query = {}) => list(`${projectPath(repo)}/pipelines`, query, (raw) => toPipeline(repo, raw), { query: {
2135
+ ref: query.branch,
2136
+ status: PIPELINE_STATES[query.state ?? "unknown"]
2137
+ } })),
2138
+ getRun: verb(true, async (ref, options) => toPipeline(ref.repo, (await fetcher.json(`${projectPath(ref.repo)}/pipelines/${ref.id}`, { signal: options?.signal })).data)),
2139
+ jobsPage: verb(true, (ref, listOptions = {}) => list(`${projectPath(ref.repo)}/pipelines/${ref.id}/jobs`, listOptions, (raw) => toCiJob(ref, raw))),
2140
+ getJob: verb(!anonymous, async (ref, options) => {
2141
+ const { data } = await fetcher.json(`${projectPath(ref.repo)}/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2142
+ const run = ref.run ?? (data.pipeline && {
2143
+ forge: "gitlab",
2144
+ instance,
2145
+ repo: ref.repo,
2146
+ id: String(data.pipeline.id)
2147
+ });
2148
+ if (!run) throw new UnsupportedOperationError(`GitLab returned job ${ref.id} without its pipeline, and the ref names no run`, context);
2149
+ return toCiJob(run, data);
2150
+ }),
2151
+ log: verb(!anonymous, async (ref, options) => (await fetcher.stream(`${projectPath(ref.repo)}/jobs/${encodeURIComponent(ref.id)}/trace`, { signal: options?.signal })).body),
2152
+ rerunFailed: verb(true, async (ref, options) => {
2153
+ await fetcher.raw(`${projectPath(ref.repo)}/pipelines/${encodeURIComponent(ref.id)}/retry`, {
2154
+ method: "POST",
2155
+ signal: options?.signal
2156
+ });
2157
+ })
2158
+ },
2159
+ securityAlerts: {
2160
+ kinds: {
2161
+ dependency: !anonymous,
2162
+ code_scanning: !anonymous,
2163
+ secret: !anonymous
2164
+ },
2165
+ listPage: vulnerabilitiesPage
2166
+ },
2167
+ emulated: { getCommitComment: anonymous ? "unverified" : "emulated" },
2168
+ threads: {
2169
+ filesPage: verb(true, (thread, listOptions = {}) => list(`${threadPath(requireMerge(thread, "read for changed files"))}/diffs`, listOptions, toChangedFile)),
2170
+ commitsPage: verb(true, (thread, listOptions = {}) => list(`${threadPath(requireMerge(thread, "read for commits"))}/commits`, listOptions, (raw) => toCommit(thread.repo, raw))),
2171
+ reviewsPage: verb("emulated", async (thread, listOptions) => {
2172
+ const ref = requireThread(thread, context);
2173
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests have approvals", context);
2174
+ const { data, response } = await fetcher.json(`${threadPath(ref)}/approvals`, { signal: listOptions?.signal });
2175
+ return {
2176
+ items: toApprovalReviews(ref, data),
2177
+ ...rateLimitPart(response)
2178
+ };
2179
+ }),
2180
+ approve: verb(true, approve),
2181
+ createReview: verb("emulated", async (thread, input, options) => {
2182
+ if (input.comments?.length) throw new UnsupportedOperationError("GitLab reviews carry no inline comments yet", context);
2183
+ const ref = requireThread(thread, context);
2184
+ if (input.event === "comment" && input.body) {
2185
+ const { data } = await fetcher.json(`${threadPath(ref)}/discussions`, {
2186
+ method: "POST",
2187
+ json: { body: input.body },
2188
+ signal: options?.signal
2189
+ });
2190
+ const note = data.notes[0];
2191
+ return {
2192
+ ...syntheticReview(ref, `discussion:${data.id}`, "commented", {
2193
+ author: toActor(instance, note.author),
2194
+ stateRaw: "discussion",
2195
+ submittedAt: toDate(note.created_at),
2196
+ raw: data
2197
+ }),
2198
+ body: note.body,
2199
+ comments: [{
2200
+ ...toNoteComment(ref, note, data),
2201
+ raw: note
2202
+ }]
2203
+ };
2204
+ }
2205
+ if (input.event !== "approve") throw new UnsupportedOperationError("GitLab has approvals and discussions, not reviews; use `threads.approve()`, or `threads.createComment()` with a body", context);
2206
+ return approve(ref, input.body, options);
2207
+ }),
2208
+ replyToReviewComment: verb(true, async (thread, comment, body, options) => {
2209
+ const ref = requireMerge(thread, "reviewed");
2210
+ if (comment.thread === void 0) throw new UnsupportedOperationError("GitLab replies inside a discussion; pass a comment with its `thread` from `comments()`", context);
2211
+ const { data } = await fetcher.json(`${threadPath(ref)}/discussions/${encodeURIComponent(comment.thread.id)}/notes`, {
2212
+ method: "POST",
2213
+ json: { body },
2214
+ signal: options?.signal
2215
+ });
2216
+ return {
2217
+ ...toNoteComment(ref, data),
2218
+ thread: {
2219
+ id: comment.thread.id,
2220
+ resolved: Boolean(data.resolved)
2221
+ }
2222
+ };
2223
+ }),
2224
+ reviewThreadsPage: verb(!anonymous, async (thread, listOptions = {}) => {
2225
+ const ref = requireMerge(thread, "read for review threads");
2226
+ const page = await list(`${threadPath(ref)}/discussions`, listOptions, (discussion) => discussion);
2227
+ return {
2228
+ ...page,
2229
+ items: page.items.filter((discussion) => discussion.notes.some((note) => note.resolvable)).map((discussion) => toDiscussionThread(ref, discussion))
2230
+ };
2231
+ }),
2232
+ reviewThreads: verb(true, {
2233
+ resolveReviewThread: (thread, id, options) => setDiscussionResolved(thread, id, true, options),
2234
+ unresolveReviewThread: (thread, id, options) => setDiscussionResolved(thread, id, false, options)
2235
+ }),
2236
+ checks: perKind({ pull_request: true }, async (thread, options) => {
2237
+ const ref = requireThread(thread, context);
2238
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
2239
+ if (!data.head_pipeline) return { items: [] };
2240
+ const pipelineProject = data.head_pipeline.project_id;
2241
+ const own = pipelineProject === void 0 || pipelineProject === data.target_project_id;
2242
+ const project = own ? projectPath(ref.repo) : `/projects/${pipelineProject}`;
2243
+ const repo = own ? ref.repo : repoRefFromWebUrl(instance, data.head_pipeline.web_url, pipelineProject);
2244
+ const run = repo && {
2245
+ forge: "gitlab",
2246
+ instance,
2247
+ repo,
2248
+ id: String(data.head_pipeline.id)
2249
+ };
2250
+ return { items: await Array.fromAsync(fetcher.items(`${project}/pipelines/${data.head_pipeline.id}/jobs`, {
2251
+ query: { per_page: 100 },
2252
+ signal: options?.signal
2253
+ }), (job) => toJobCheck(repo ?? ref.repo, job, run)) };
2254
+ }),
2255
+ get: perKind({
2256
+ issue: true,
2257
+ pull_request: true
2258
+ }, get),
2259
+ getMany: verb(true, (refs, options) => getManyConcurrently(refs, get, options)),
2260
+ closingIssuesPage: verb(true, async (thread, listOptions = {}) => {
2261
+ const ref = requireThread(thread, context);
2262
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests close issues", context);
2263
+ return list(`${threadPath(ref)}/closes_issues`, listOptions, (raw) => referencedThread(raw, "issue"));
2264
+ }),
2265
+ closingPullRequestsPage: verb(true, async (thread, listOptions = {}) => {
2266
+ const ref = requireThread(thread, context);
2267
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("Only issues are closed by merge requests", context);
2268
+ return list(`${threadPath(ref)}/closed_by`, listOptions, (raw) => referencedThread(raw, "pull_request"));
2269
+ }),
2270
+ listPage: perKind(ISSUE_LIKE, listPage),
2271
+ eventsPage: verb(!anonymous, async (thread, listOptions = {}) => {
2272
+ const ref = requireThread(thread, context);
2273
+ return list(`${threadPath(ref)}/notes`, listOptions, (note) => toNoteEvent(ref, note), { query: {
2274
+ sort: "asc",
2275
+ order_by: "created_at"
2276
+ } });
2277
+ }),
2278
+ commentsPage: perKind({
2279
+ issue: !anonymous,
2280
+ pull_request: !anonymous
2281
+ }, async (thread, listOptions = {}) => {
2282
+ const ref = requireThread(thread, context);
2283
+ const page = await list(`${threadPath(requireIssueOrPull(ref, context, "list comments on"))}/discussions`, listOptions, (discussion) => discussion);
2284
+ return {
2285
+ ...page,
2286
+ items: page.items.flatMap((discussion) => discussion.notes.filter((note) => !note.system).map((note) => toNoteComment(ref, note, discussion)))
2287
+ };
2288
+ }),
2289
+ getComment: perKind({
2290
+ issue: !anonymous,
2291
+ pull_request: !anonymous
2292
+ }, async (ref, options) => {
2293
+ const thread = requireIssueOrPull(ref.thread, context, "read comments on");
2294
+ const { data } = await fetcher.json(`${threadPath(thread)}/notes/${ref.id}`, { signal: options?.signal });
2295
+ if (data.system) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2296
+ if (!data.resolvable) return toNoteComment(thread, data);
2297
+ for await (const discussion of fetcher.items(`${threadPath(thread)}/discussions`, {
2298
+ query: { per_page: 100 },
2299
+ signal: options?.signal
2300
+ })) {
2301
+ const note = discussion.notes.find((candidate) => String(candidate.id) === ref.id);
2302
+ if (note) return toNoteComment(thread, note, discussion);
2303
+ }
2304
+ return toNoteComment(thread, data);
2305
+ }),
2306
+ createComment: perKind({
2307
+ issue: true,
2308
+ pull_request: true
2309
+ }, async (thread, body, options) => {
2310
+ const ref = requireThread(thread, context);
2311
+ const { data } = await fetcher.json(`${threadPath(requireIssueOrPull(ref, context, "comment on"))}/notes`, {
2312
+ method: "POST",
2313
+ json: { body },
2314
+ signal: options?.signal
2315
+ });
2316
+ return toNoteComment(ref, data);
2317
+ }),
2318
+ updateComment: perKind({
2319
+ issue: true,
2320
+ pull_request: true
2321
+ }, async (ref, body, options) => {
2322
+ const thread = requireIssueOrPull(ref.thread, context, "edit comments on");
2323
+ const { data } = await fetcher.json(`${threadPath(thread)}/notes/${ref.id}`, {
2324
+ method: "PUT",
2325
+ json: { body },
2326
+ signal: options?.signal
2327
+ });
2328
+ return toNoteComment(thread, data);
2329
+ }),
2330
+ deleteComment: perKind({
2331
+ issue: true,
2332
+ pull_request: true
2333
+ }, async (ref, options) => {
2334
+ const thread = requireIssueOrPull(ref.thread, context, "delete comments on");
2335
+ await fetcher.raw(`${threadPath(thread)}/notes/${ref.id}`, {
2336
+ method: "DELETE",
2337
+ signal: options?.signal
2338
+ });
2339
+ }),
2340
+ create: perKind({
2341
+ issue: true,
2342
+ pull_request: true
2343
+ }, async (repo, input, options) => {
2344
+ if (input.kind === "discussion") throw new UnsupportedOperationError("GitLab has no discussion threads", context);
2345
+ const assignee_ids = input.assignees?.length ? await Promise.all(input.assignees.map(userId)) : void 0;
2346
+ const labels = input.labels?.join(",");
2347
+ if (input.kind === "issue") {
2348
+ const { data } = await fetcher.json(`${projectPath(repo)}/issues`, {
2349
+ method: "POST",
2350
+ json: {
2351
+ title: input.title,
2352
+ description: input.body,
2353
+ labels,
2354
+ assignee_ids
2355
+ },
2356
+ signal: options?.signal
2357
+ });
2358
+ return toThread({
2359
+ forge: FORGE,
2360
+ instance,
2361
+ repo,
2362
+ kind: "issue",
2363
+ number: String(data.iid)
2364
+ }, data);
2365
+ }
2366
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a merge request needs head and base branches", context);
2367
+ const { data } = await fetcher.json(`${projectPath(repo)}/merge_requests`, {
2368
+ method: "POST",
2369
+ json: {
2370
+ title: input.draft ? `Draft: ${input.title}` : input.title,
2371
+ description: input.body,
2372
+ source_branch: input.head,
2373
+ target_branch: input.base,
2374
+ labels,
2375
+ assignee_ids
2376
+ },
2377
+ signal: options?.signal
2378
+ });
2379
+ return toThread({
2380
+ forge: FORGE,
2381
+ instance,
2382
+ repo,
2383
+ kind: "pull_request",
2384
+ number: String(data.iid)
2385
+ }, data);
2386
+ }),
2387
+ update: perKind({
2388
+ issue: true,
2389
+ pull_request: true
2390
+ }, async (thread, input, options) => {
2391
+ const ref = requireIssueOrPull(thread, context, "update");
2392
+ const { data } = await fetcher.json(threadPath(ref), {
2393
+ method: "PUT",
2394
+ json: {
2395
+ title: input.title,
2396
+ description: input.body,
2397
+ state_event: input.state && STATE_EVENTS[input.state],
2398
+ labels: input.labels?.join(","),
2399
+ assignee_ids: input.assignees && await Promise.all(input.assignees.map(userId))
2400
+ },
2401
+ signal: options?.signal
2402
+ });
2403
+ return toThread(ref, data);
2404
+ }),
2405
+ addLabels: perKind({
2406
+ issue: true,
2407
+ pull_request: true
2408
+ }, async (thread, labels, options) => {
2409
+ const ref = requireIssueOrPull(thread, context, "label");
2410
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2411
+ method: "PUT",
2412
+ json: { add_labels: labels.join(",") },
2413
+ signal: options?.signal
2414
+ })).data).labels;
2415
+ }),
2416
+ removeLabels: perKind({
2417
+ issue: true,
2418
+ pull_request: true
2419
+ }, async (thread, labels, options) => {
2420
+ const ref = requireIssueOrPull(thread, context, "label");
2421
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2422
+ method: "PUT",
2423
+ json: { remove_labels: labels.join(",") },
2424
+ signal: options?.signal
2425
+ })).data).labels;
2426
+ }),
2427
+ setMilestone: perKind({
2428
+ issue: true,
2429
+ pull_request: true
2430
+ }, async (thread, milestone, options) => {
2431
+ const ref = requireIssueOrPull(thread, context, "set the milestone of");
2432
+ const { data } = await fetcher.json(threadPath(ref), {
2433
+ method: "PUT",
2434
+ json: { milestone_id: milestone === void 0 ? 0 : await milestoneId(milestone, (page) => milestonesPage(ref.repo, page, true), context, options) },
2435
+ signal: options?.signal
2436
+ });
2437
+ return toMilestone(data.milestone);
2438
+ }),
2439
+ reactionsPage: perKind(ISSUE_LIKE, async (target, listOptions = {}) => {
2440
+ const result = await fetcher.page(`${awardPath(target)}/award_emoji`, {
2441
+ query: { per_page: listOptions.perPage },
2442
+ cursor: listOptions.cursor,
2443
+ signal: listOptions.signal
2444
+ });
2445
+ return toPage(result, (raw) => {
2446
+ const reactor = toActor(instance, raw.user);
2447
+ return reactor && {
2448
+ content: reactionContent(REACTION_NAMES[raw.name] ?? raw.name),
2449
+ contentRaw: raw.name,
2450
+ actor: reactor,
2451
+ createdAt: toDate(raw.created_at),
2452
+ raw
2453
+ };
2454
+ });
2455
+ }),
2456
+ reactions: perKind({
2457
+ issue: true,
2458
+ pull_request: true
2459
+ }, {
2460
+ async react(target, reaction, options) {
2461
+ try {
2462
+ await fetcher.raw(`${awardPath(target)}/award_emoji`, {
2463
+ method: "POST",
2464
+ json: { name: AWARD_EMOJI[reaction] },
2465
+ signal: options?.signal
2466
+ });
2467
+ } catch (error) {
2468
+ if (!(error instanceof ForgeApiError && error.body.includes("has already been taken"))) throw error;
2469
+ }
2470
+ },
2471
+ async unreact(target, reaction, options) {
2472
+ const path = `${awardPath(target)}/award_emoji`;
2473
+ const { data } = await fetcher.json(path, {
2474
+ query: { per_page: 100 },
2475
+ signal: options?.signal
2476
+ });
2477
+ const login = await viewerLogin();
2478
+ const mine = data.find((award) => award.name === AWARD_EMOJI[reaction] && award.user?.username === login);
2479
+ if (mine) await fetcher.raw(`${path}/${mine.id}`, {
2480
+ method: "DELETE",
2481
+ signal: options?.signal
2482
+ });
2483
+ }
2484
+ }),
2485
+ transfer: verb(true, async (thread, repo, options) => {
2486
+ const ref = requireIssueOrPull(thread, context, "transfer");
2487
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("GitLab moves issues only", context);
2488
+ const { data: target } = await fetcher.json(`/projects/${projectId(repo)}`, { signal: options?.signal });
2489
+ const { data } = await fetcher.json(`${threadPath(ref)}/move`, {
2490
+ method: "POST",
2491
+ json: { to_project_id: target.id },
2492
+ signal: options?.signal
2493
+ });
2494
+ return {
2495
+ forge: FORGE,
2496
+ instance,
2497
+ repo,
2498
+ kind: "issue",
2499
+ number: String(data.iid),
2500
+ externalId: data.id === void 0 ? void 0 : String(data.id)
2501
+ };
2502
+ }),
2503
+ markDuplicate: verb("emulated", async (thread, canonical, options) => {
2504
+ const ref = requireIssueOrPull(thread, context, "mark duplicate");
2505
+ const reference = canonical.repo.owner === ref.repo.owner && canonical.repo.name === ref.repo.name ? `#${canonical.number}` : `${canonical.repo.owner}/${canonical.repo.name}#${canonical.number}`;
2506
+ await fetcher.raw(`${threadPath(ref)}/notes`, {
2507
+ method: "POST",
2508
+ json: { body: `/duplicate ${reference}` },
2509
+ signal: options?.signal
2510
+ });
2511
+ }),
2512
+ setLabels: perKind({
2513
+ issue: true,
2514
+ pull_request: true
2515
+ }, async (thread, labels, options) => {
2516
+ const ref = requireIssueOrPull(thread, context, "label");
2517
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2518
+ method: "PUT",
2519
+ json: { labels: labels.join(",") },
2520
+ signal: options?.signal
2521
+ })).data).labels;
2522
+ }),
2523
+ setAssignees: perKind({
2524
+ issue: true,
2525
+ pull_request: true
2526
+ }, async (thread, assignees, options) => {
2527
+ const ref = requireIssueOrPull(thread, context, "assign");
2528
+ const { data } = await fetcher.json(threadPath(ref), {
2529
+ method: "PUT",
2530
+ json: { assignee_ids: await Promise.all(assignees.map(userId)) },
2531
+ signal: options?.signal
2532
+ });
2533
+ return (data.assignees ?? []).flatMap((user) => toActor(instance, user) ?? []);
2534
+ }),
2535
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
2536
+ const ref = requireThread(thread, context);
2537
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests have reviewers", context);
2538
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
2539
+ const ids = /* @__PURE__ */ new Set([...(data.reviewers ?? []).map((user) => user.id), ...await Promise.all(reviewers.map(userId))]);
2540
+ await fetcher.raw(threadPath(ref), {
2541
+ method: "PUT",
2542
+ json: { reviewer_ids: [...ids] },
2543
+ signal: options?.signal
2544
+ });
2545
+ }),
2546
+ close: perKind({
2547
+ issue: true,
2548
+ pull_request: true
2549
+ }, (ref, options) => setState(ref, "close", options)),
2550
+ reopen: perKind({
2551
+ issue: true,
2552
+ pull_request: true
2553
+ }, (ref, options) => setState(ref, "reopen", options)),
2554
+ locking: perKind({
2555
+ issue: true,
2556
+ pull_request: true
2557
+ }, {
2558
+ lock: (thread, options) => setLocked(thread, true, options),
2559
+ unlock: (thread, options) => setLocked(thread, false, options)
2560
+ }),
2561
+ merge: verb(true, merge),
2562
+ updateBranch: verb(true, updateBranch),
2563
+ subscriptions: perKind(ISSUE_LIKE, {
2564
+ subscription: async (thread, options) => {
2565
+ const ref = requireIssueOrPull(thread, context, "read the subscription of");
2566
+ return (await fetcher.json(threadPath(ref), { signal: options?.signal })).data.subscribed ? "subscribed" : "none";
2567
+ },
2568
+ subscribe: (thread, options) => setSubscribed(thread, true, options),
2569
+ unsubscribe: (thread, options) => setSubscribed(thread, false, options)
2570
+ })
2571
+ }
2572
+ };
2573
+ }
2574
+ });
2575
+ /** GitLab tokens carry coarse scopes; `api` covers writes and `read_api` reads. */
2576
+ function gitlabScopesFor(verb) {
2577
+ const [group = "", name = ""] = verb.split(".");
2578
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : {
2579
+ token: ["api"],
2580
+ note: "Maintainer on the project, or Owner on the group"
2581
+ };
2582
+ if (group === "orgs") return {
2583
+ token: ["read_api"],
2584
+ note: "A member of the group, for a private group"
2585
+ };
2586
+ return { token: [WRITE_VERBS.has(verb) ? "api" : "read_api"] };
2587
+ }
2588
+ //#endregion
2589
+ export { toRepoRef as a, gitlab, toLabel as i, approvalId as n, toState as o, toActor as r, toThreadKind as s, FORGE as t };