@vite-hub/forge 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2532 @@
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, _t as reactionContent, a as ForgeApiError, at as versionAtLeast, c as InsufficientScopeError, d as NotFoundError, g as UnsupportedOperationError, gt as rangeOf, h as UnresolvedThreadError, i as ForbiddenError, it as toWarning, m as TokenRevokedError, n as BranchMovedError, nt as toPage, ot as withEtag, pt as lineOf, q as resolveToken, t as AuthenticationRequiredError, tt as toMergeError, ut as isNamespaceRef, xt as webUrlFor, z as mergeCommitMessage } from "./utils-CA_4WJhJ-DNgT61X2.js";
2
+ import { C as verb, 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-DgHwxxYz-D1V2LOr1.js";
3
+ //#region ../../node_modules/.pnpm/forges@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/web-Zu3WSnnL.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] ? 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") 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@https+++pkg.pr.new+danielroe+forges@40d50b2f8bdc5585becfae405e1a3b8a325f7202/node_modules/forges/dist/gitlab-BesCdl-6.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
+ function toCommitComment(commit, comment) {
708
+ return {
709
+ ref: {
710
+ forge: FORGE,
711
+ instance: commit.instance,
712
+ commit,
713
+ id: commitCommentId(comment)
714
+ },
715
+ body: comment.note,
716
+ author: toActor(commit.instance, comment.author),
717
+ createdAt: toDate(comment.created_at),
718
+ raw: comment
719
+ };
720
+ }
721
+ /** Pipeline and job statuses. `manual` jobs wait for a person, so they neither pass nor fail. */
722
+ function pipelineState(status) {
723
+ switch (status) {
724
+ case "success": return "success";
725
+ case "failed":
726
+ case "canceled": return "failure";
727
+ case "skipped":
728
+ case "manual": return "neutral";
729
+ case "created":
730
+ case "waiting_for_resource":
731
+ case "preparing":
732
+ case "pending":
733
+ case "running":
734
+ case "scheduled": return "pending";
735
+ default: return "unknown";
736
+ }
737
+ }
738
+ /** The merge request's head pipeline, which GitLab reports as one combined status. */
739
+ function toPipelineSummary(pipeline) {
740
+ const state = pipelineState(pipeline.status);
741
+ return {
742
+ state: state === "neutral" ? "pending" : state,
743
+ stateRaw: pipeline.status,
744
+ ...pipeline.web_url ? { url: pipeline.web_url } : {}
745
+ };
746
+ }
747
+ function toJobCheck(repo, job, run) {
748
+ const state = pipelineState(job.status);
749
+ return {
750
+ ref: {
751
+ forge: FORGE,
752
+ instance: repo.instance,
753
+ repo,
754
+ id: String(job.id),
755
+ type: "job"
756
+ },
757
+ name: job.stage ? `${job.stage}: ${job.name}` : job.name,
758
+ state: state === "failure" && job.allow_failure ? "neutral" : state,
759
+ stateRaw: job.status,
760
+ url: job.web_url,
761
+ startedAt: toDate(job.started_at),
762
+ completedAt: toDate(job.finished_at),
763
+ ...run ? { run } : {},
764
+ raw: job
765
+ };
766
+ }
767
+ /** GitLab keys releases by tag and has no drafts or prereleases. */
768
+ function toRelease(repo, raw) {
769
+ return {
770
+ ref: {
771
+ forge: FORGE,
772
+ instance: repo.instance,
773
+ repo,
774
+ id: raw.tag_name,
775
+ tag: raw.tag_name
776
+ },
777
+ name: raw.name ?? void 0,
778
+ tag: raw.tag_name,
779
+ body: raw.description ?? void 0,
780
+ isDraft: false,
781
+ isPrerelease: false,
782
+ author: toActor(repo.instance, raw.author),
783
+ publishedAt: raw.upcoming_release ? void 0 : toDate(raw.released_at),
784
+ createdAt: toDate(raw.created_at),
785
+ url: raw._links?.self,
786
+ assets: raw.assets?.links?.map((link) => ({
787
+ name: link.name,
788
+ url: link.direct_asset_url ?? link.url
789
+ })),
790
+ raw
791
+ };
792
+ }
793
+ const REPORT_KINDS = {
794
+ DEPENDENCY_SCANNING: "dependency",
795
+ CONTAINER_SCANNING: "dependency",
796
+ CLUSTER_IMAGE_SCANNING: "dependency",
797
+ SAST: "code_scanning",
798
+ SECRET_DETECTION: "secret"
799
+ };
800
+ const REPORT_TYPES = {
801
+ dependency: [
802
+ "DEPENDENCY_SCANNING",
803
+ "CONTAINER_SCANNING",
804
+ "CLUSTER_IMAGE_SCANNING"
805
+ ],
806
+ code_scanning: ["SAST"],
807
+ secret: ["SECRET_DETECTION"],
808
+ advisory: []
809
+ };
810
+ /** `INFO` findings are informational and carry no severity. */
811
+ function toSeverity(raw) {
812
+ const severity = raw.toLowerCase();
813
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low" ? severity : "unknown";
814
+ }
815
+ function toVulnerability(repo, raw) {
816
+ const kind = REPORT_KINDS[raw.reportType] ?? "other";
817
+ const state = raw.state === "DETECTED" || raw.state === "CONFIRMED" ? "open" : raw.state === "RESOLVED" ? "fixed" : raw.state === "DISMISSED" ? "dismissed" : "unknown";
818
+ const id = raw.id.replace(/^gid:\/\/gitlab\/Vulnerability\//, "");
819
+ return {
820
+ ref: {
821
+ forge: FORGE,
822
+ instance: repo.instance,
823
+ repo,
824
+ id,
825
+ kind,
826
+ severityRaw: raw.severity.toLowerCase()
827
+ },
828
+ kind,
829
+ kindRaw: raw.reportType.toLowerCase(),
830
+ severity: toSeverity(raw.severity),
831
+ severityRaw: raw.severity.toLowerCase(),
832
+ state,
833
+ stateRaw: raw.state.toLowerCase(),
834
+ title: raw.title,
835
+ url: raw.webUrl ?? void 0,
836
+ createdAt: toDate(raw.detectedAt),
837
+ updatedAt: toDate(raw.updatedAt),
838
+ dismissedAt: toDate(raw.dismissedAt),
839
+ raw
840
+ };
841
+ }
842
+ function toStatusCheck(repo, raw) {
843
+ const state = pipelineState(raw.status);
844
+ return {
845
+ ref: {
846
+ forge: FORGE,
847
+ instance: repo.instance,
848
+ repo,
849
+ id: String(raw.id),
850
+ type: "status"
851
+ },
852
+ name: raw.name ?? String(raw.id),
853
+ state: state === "failure" && raw.allow_failure ? "neutral" : state,
854
+ stateRaw: raw.status,
855
+ url: raw.target_url ?? void 0,
856
+ startedAt: toDate(raw.created_at),
857
+ completedAt: toDate(raw.finished_at),
858
+ raw
859
+ };
860
+ }
861
+ function toPipeline(repo, raw) {
862
+ return {
863
+ ref: {
864
+ forge: FORGE,
865
+ instance: repo.instance,
866
+ repo,
867
+ id: String(raw.id)
868
+ },
869
+ name: raw.name || raw.source || `pipeline ${raw.id}`,
870
+ state: pipelineState(raw.status),
871
+ stateRaw: raw.status,
872
+ number: raw.iid === void 0 ? void 0 : String(raw.iid),
873
+ eventRaw: raw.source,
874
+ branch: raw.ref,
875
+ sha: raw.sha,
876
+ url: raw.web_url,
877
+ actor: toActor(repo.instance, raw.user),
878
+ createdAt: toDate(raw.created_at),
879
+ startedAt: toDate(raw.started_at),
880
+ completedAt: toDate(raw.finished_at),
881
+ raw
882
+ };
883
+ }
884
+ function toCiJob(run, raw) {
885
+ const state = pipelineState(raw.status);
886
+ return {
887
+ ref: {
888
+ forge: FORGE,
889
+ instance: run.instance,
890
+ repo: run.repo,
891
+ id: String(raw.id),
892
+ run
893
+ },
894
+ name: raw.name,
895
+ state: state === "failure" && raw.allow_failure ? "neutral" : state,
896
+ stateRaw: raw.status,
897
+ stage: raw.stage,
898
+ url: raw.web_url,
899
+ startedAt: toDate(raw.started_at),
900
+ completedAt: toDate(raw.finished_at),
901
+ raw
902
+ };
903
+ }
904
+ function toCommit(repo, raw, files) {
905
+ return {
906
+ ref: {
907
+ forge: FORGE,
908
+ instance: repo.instance,
909
+ repo,
910
+ sha: raw.id
911
+ },
912
+ sha: raw.id,
913
+ message: raw.message ?? raw.title,
914
+ author: {
915
+ name: raw.author_name,
916
+ email: raw.author_email,
917
+ date: toDate(raw.authored_date ?? raw.created_at)
918
+ },
919
+ committer: {
920
+ name: raw.committer_name,
921
+ email: raw.committer_email,
922
+ date: toDate(raw.committed_date)
923
+ },
924
+ parents: raw.parent_ids ?? [],
925
+ url: raw.web_url,
926
+ ...raw.stats ? { stats: {
927
+ additions: raw.stats.additions ?? 0,
928
+ deletions: raw.stats.deletions ?? 0,
929
+ total: raw.stats.total
930
+ } } : {},
931
+ ...files ? { files } : {},
932
+ raw
933
+ };
934
+ }
935
+ /** GitLab reports a change by three booleans and a unified diff, with no counts. */
936
+ function toChangedFile(raw) {
937
+ const path = raw.new_path ?? raw.old_path ?? "";
938
+ const status = raw.new_file ? "added" : raw.deleted_file ? "removed" : raw.renamed_file ? "renamed" : "modified";
939
+ return {
940
+ path,
941
+ previousPath: raw.renamed_file ? raw.old_path : void 0,
942
+ status,
943
+ statusRaw: status,
944
+ patch: raw.diff
945
+ };
946
+ }
947
+ function toBranch(raw) {
948
+ return {
949
+ name: raw.name,
950
+ sha: raw.commit?.id ?? "",
951
+ isDefault: raw.default,
952
+ isProtected: raw.protected,
953
+ url: raw.web_url,
954
+ raw
955
+ };
956
+ }
957
+ /** Whether a branch name matches a protected branch name, where `*` stands for any run of characters. */
958
+ function matchesBranch(pattern, name) {
959
+ return new RegExp(`^${pattern.split("*").map((part) => part.replace(/[\\^$.|?+()[\]{}]/g, "\\$&")).join(".*")}$`).test(name);
960
+ }
961
+ /** Code owner and report rules apply only to some changes, so just `any_approver` and `regular` set the floor. */
962
+ function toBranchRules(branch, project, rules, warnings) {
963
+ 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;
964
+ const approvals = rules?.filter((rule) => (rule.rule_type === "any_approver" || rule.rule_type === "regular") && applies(rule)).map((rule) => rule.approvals_required);
965
+ return {
966
+ branch: branch.name,
967
+ requiredChecks: [],
968
+ requiresAllChecks: project.only_allow_merge_if_pipeline_succeeds ?? void 0,
969
+ requiredApprovals: approvals && Math.max(0, ...approvals),
970
+ ...warnings.length ? { warnings } : {},
971
+ raw: {
972
+ branch,
973
+ project,
974
+ rules
975
+ }
976
+ };
977
+ }
978
+ function toTag(raw) {
979
+ return {
980
+ name: raw.name,
981
+ sha: raw.commit?.id ?? raw.target ?? "",
982
+ raw
983
+ };
984
+ }
985
+ function toTreeEntry(raw) {
986
+ return {
987
+ path: raw.path,
988
+ type: raw.mode === "120000" ? "symlink" : raw.type === "tree" ? "directory" : raw.type === "commit" ? "submodule" : "file",
989
+ sha: raw.id,
990
+ mode: raw.mode
991
+ };
992
+ }
993
+ function toWebhook(target, raw) {
994
+ const nativeEvents = Object.entries(raw).filter(([key, value]) => key.endsWith("_events") && value === true).map(([key]) => key);
995
+ return {
996
+ ref: {
997
+ forge: FORGE,
998
+ instance: target.instance,
999
+ target,
1000
+ id: String(raw.id)
1001
+ },
1002
+ url: raw.url,
1003
+ events: eventKindsOf(GITLAB_NATIVE_EVENTS, nativeEvents),
1004
+ nativeEvents,
1005
+ active: !raw.disabled_until,
1006
+ createdAt: toDate(raw.created_at),
1007
+ raw
1008
+ };
1009
+ }
1010
+ function toWebhookDelivery(hook, raw) {
1011
+ const status = Number(raw.response_status) || 0;
1012
+ return {
1013
+ ref: {
1014
+ forge: FORGE,
1015
+ instance: hook.instance,
1016
+ hook,
1017
+ id: String(raw.id)
1018
+ },
1019
+ event: raw.trigger ?? "",
1020
+ status,
1021
+ ok: status >= 200 && status < 300,
1022
+ deliveredAt: toDate(raw.created_at),
1023
+ duration: raw.execution_duration === void 0 ? void 0 : Math.round(raw.execution_duration * 1e3),
1024
+ raw
1025
+ };
1026
+ }
1027
+ const TOKEN_HEADER = "x-gitlab-token";
1028
+ /**
1029
+ * GitLab sends the configured secret verbatim in `X-Gitlab-Token`; there is no
1030
+ * body signature to compute.
1031
+ */
1032
+ async function verifyGitLabToken(delivery, secret) {
1033
+ return verifySharedToken(delivery, secret, TOKEN_HEADER);
1034
+ }
1035
+ const gitlabWebhooks = ({ options, instance }) => ({
1036
+ events: GITLAB_WEBHOOK_EVENTS,
1037
+ verify: (delivery) => verifyGitLabToken(delivery, options.webhookSecret),
1038
+ translate: async (delivery) => (await import("./events-7EBoeIPd-A2RUkJi5.js")).translateGitLabWebhook(instance, delivery)
1039
+ });
1040
+ const PROJECT_ORDER = {
1041
+ created: "created_at",
1042
+ updated: "updated_at",
1043
+ pushed: "last_activity_at",
1044
+ name: "name"
1045
+ };
1046
+ /** GitLab versions with the webhook event log and resend endpoints. */
1047
+ const GITLAB_HOOK_EVENTS = "17.0";
1048
+ const ISSUE_LIKE = {
1049
+ issue: true,
1050
+ pull_request: true
1051
+ };
1052
+ const STATE_EVENTS = {
1053
+ open: "reopen",
1054
+ closed: "close"
1055
+ };
1056
+ /** Access level per normalised role, as `POST /projects/:id/members` takes it. */
1057
+ const ACCESS_LEVELS = {
1058
+ admin: 50,
1059
+ maintain: 40,
1060
+ write: 30,
1061
+ triage: 20,
1062
+ read: 10,
1063
+ none: 0
1064
+ };
1065
+ /** GitLab awards emoji by name; these are the names behind the normalised reactions. */
1066
+ const AWARD_EMOJI = {
1067
+ "+1": "thumbsup",
1068
+ "-1": "thumbsdown",
1069
+ "laugh": "laughing",
1070
+ "confused": "confused",
1071
+ "heart": "heart",
1072
+ "hooray": "tada",
1073
+ "rocket": "rocket",
1074
+ "eyes": "eyes"
1075
+ };
1076
+ /** The model's name for each award emoji `forges` writes. */
1077
+ const REACTION_NAMES = Object.fromEntries(Object.entries(AWARD_EMOJI).map(([content, name]) => [name, content]));
1078
+ const VULNERABILITIES_QUERY = `query ProjectVulnerabilities($fullPath: ID!, $first: Int, $after: String, $state: [VulnerabilityState!], $reportType: [VulnerabilityReportType!]) {
1079
+ project(fullPath: $fullPath) {
1080
+ vulnerabilities(first: $first, after: $after, state: $state, reportType: $reportType) {
1081
+ pageInfo { hasNextPage endCursor }
1082
+ nodes { id title severity state reportType detectedAt updatedAt dismissedAt resolvedAt webUrl }
1083
+ }
1084
+ }
1085
+ }`;
1086
+ const PROJECTS_QUERY = `query CodeSearchProjects($ids: [ID!]) {
1087
+ projects(ids: $ids) {
1088
+ nodes { id fullPath }
1089
+ }
1090
+ }`;
1091
+ function threadPath(ref) {
1092
+ const project = `/projects/${projectId(ref.repo)}`;
1093
+ switch (ref.kind) {
1094
+ case "pull_request": return `${project}/merge_requests/${encodeURIComponent(ref.number)}`;
1095
+ default: return `${project}/issues/${encodeURIComponent(ref.number)}`;
1096
+ }
1097
+ }
1098
+ /** Creates a GitLab provider for gitlab.com or a self-managed instance. */
1099
+ const gitlab = /* @__PURE__ */ defineForgeProvider({
1100
+ forge: FORGE,
1101
+ hasWeb: true,
1102
+ baseUrl: "https://gitlab.com",
1103
+ anonymous: true,
1104
+ apiPath: "/api/v4",
1105
+ headers: { accept: "application/json" },
1106
+ webhooks: gitlabWebhooks,
1107
+ authHeaders: ({ options: { auth } }) => auth?.type === "token" ? async () => ({ authorization: `Bearer ${await resolveToken(auth)}` }) : void 0,
1108
+ setup({ options, instance, baseUrl, origin: context, fetcher }) {
1109
+ /** GitLab serves notes, labels, milestones, members, commit statuses, commit and code search and vulnerabilities only to signed-in users. */
1110
+ const anonymous = options.auth?.type === "anonymous";
1111
+ const web = GITLAB_WEB.links({
1112
+ baseUrl,
1113
+ instance
1114
+ });
1115
+ /**
1116
+ * GitLab lists pending and done to-dos separately. With `all`, pending
1117
+ * pages are followed by done pages; `cursor.token` marks the switch. Only
1118
+ * the pending listing on its own is conditional.
1119
+ */
1120
+ async function notificationPage(listOptions = {}) {
1121
+ const cursor = listOptions.cursor;
1122
+ const state = cursor?.token === "done" ? "done" : "pending";
1123
+ const conditional = !listOptions.all && isFirstPage(cursor);
1124
+ const result = await fetcher.json(cursor?.nextUrl ?? "/todos", {
1125
+ query: cursor?.nextUrl ? void 0 : {
1126
+ state,
1127
+ per_page: listOptions.perPage
1128
+ },
1129
+ etag: conditional ? firstPageEtag(cursor) : void 0,
1130
+ signal: listOptions.signal
1131
+ });
1132
+ const since = listOptions.since?.getTime();
1133
+ const items = (result.data ?? []).map((raw) => toNotification(instance, raw)).filter((item) => since === void 0 || item.updatedAt.getTime() >= since);
1134
+ const phase = cursor?.token ?? "pending";
1135
+ const next = result.cursor?.nextUrl ? {
1136
+ ...result.cursor,
1137
+ token: phase === "done" ? "done" : void 0
1138
+ } : listOptions.all && phase !== "done" ? { token: "done" } : void 0;
1139
+ const page = {
1140
+ items,
1141
+ cursor: result.notModified ? void 0 : next,
1142
+ notModified: result.notModified,
1143
+ ...rateLimitPart(result.response)
1144
+ };
1145
+ return conditional ? withEtag(page, result, cursor) : page;
1146
+ }
1147
+ /** GitLab assigns by user id, so logins are resolved once each. */
1148
+ /** Award emoji hang off the issue, the merge request or a note, all under the same path. */
1149
+ function awardPath(target) {
1150
+ return "thread" in target ? `${threadPath(requireIssueOrPull(target.thread, context, "react to"))}/notes/${target.id}` : threadPath(requireIssueOrPull(target, context, "react to"));
1151
+ }
1152
+ /** The authenticated username, read once; removing an award needs its id, which is found by owner. */
1153
+ const viewerLogin = memo(() => fetcher.json("/user").then((result) => result.data.username, () => void 0));
1154
+ const userIdByName = memoBy((username) => fetcher.json("/users", { query: { username } }).then(({ data }) => {
1155
+ if (!data[0]) throw new UnsupportedOperationError(`No GitLab user named ${username}`, context);
1156
+ return data[0].id;
1157
+ }));
1158
+ function userId(actor) {
1159
+ if (typeof actor !== "string" && /^\d+$/.test(actor.id)) return Promise.resolve(Number(actor.id));
1160
+ return userIdByName(typeof actor === "string" ? actor : actor.login);
1161
+ }
1162
+ const STATUS_STATES = {
1163
+ pending: "pending",
1164
+ success: "success",
1165
+ failure: "failed",
1166
+ neutral: "success",
1167
+ unknown: "pending"
1168
+ };
1169
+ const PIPELINE_STATES = {
1170
+ pending: "running",
1171
+ success: "success",
1172
+ failure: "failed",
1173
+ neutral: "manual",
1174
+ unknown: void 0
1175
+ };
1176
+ async function setDiscussionResolved(thread, id, resolved, options) {
1177
+ const ref = requireThread(thread, context);
1178
+ await fetcher.raw(`${threadPath(ref)}/discussions/${encodeURIComponent(id)}`, {
1179
+ method: "PUT",
1180
+ query: { resolved },
1181
+ signal: options?.signal
1182
+ });
1183
+ }
1184
+ const list = createListing(fetcher, "per_page");
1185
+ function milestonesPage(repo, listOptions = {}, includeAncestors) {
1186
+ return list(`${projectPath(repo)}/milestones`, listOptions, (raw) => toMilestone(raw), { query: {
1187
+ state: (listOptions.state ?? "open") === "all" ? void 0 : listOptions.state === "closed" ? "closed" : "active",
1188
+ include_ancestors: includeAncestors
1189
+ } });
1190
+ }
1191
+ async function readUser(path, signal) {
1192
+ const { data } = await fetcher.json(path, { signal });
1193
+ return {
1194
+ ...toActor(instance, data),
1195
+ bio: data.bio || void 0,
1196
+ company: data.organization || void 0,
1197
+ location: data.location || void 0,
1198
+ websiteUrl: data.website_url || void 0,
1199
+ createdAt: toDate(data.created_at),
1200
+ followers: data.followers,
1201
+ following: data.following,
1202
+ raw: data
1203
+ };
1204
+ }
1205
+ function projectPath(repo) {
1206
+ return `/projects/${projectId(repo)}`;
1207
+ }
1208
+ /**
1209
+ * The listing gives only names, group templates included, so every body costs one more request. A name in both
1210
+ * the project and a group reads as the group's template unless the project's id picks the project's own.
1211
+ */
1212
+ async function templates(repo, options = {}) {
1213
+ const signal = options.signal;
1214
+ const kinds = options.kind ? [options.kind] : ["issue", "pull_request"];
1215
+ return (await Promise.all(kinds.map(async (kind) => {
1216
+ const type = kind === "issue" ? "issues" : "merge_requests";
1217
+ const names = await Array.fromAsync(iteratePages((listOptions) => list(`${projectPath(repo)}/templates/${type}`, {
1218
+ ...listOptions,
1219
+ perPage: 100,
1220
+ signal
1221
+ }, (raw) => raw)));
1222
+ const keys = [...new Set(names.map(({ key }) => key))];
1223
+ const shared = keys.filter((key) => names.filter((name) => name.key === key).length > 1);
1224
+ const id = shared.length ? repo.externalId ?? String((await fetcher.json(projectPath(repo), { signal })).data.id) : void 0;
1225
+ const read = async (key, source) => {
1226
+ const { data } = await fetcher.json(`${projectPath(repo)}/templates/${type}/${encodeURIComponent(key)}`, {
1227
+ query: { source_template_project_id: source },
1228
+ signal
1229
+ });
1230
+ return {
1231
+ kind,
1232
+ name: data.name,
1233
+ format: "markdown",
1234
+ body: data.content,
1235
+ raw: data
1236
+ };
1237
+ };
1238
+ const [inherited, own] = await Promise.all([mapConcurrent(keys, 4, (key) => read(key)), mapConcurrent(shared, 4, (key) => read(key, id).catch((error) => {
1239
+ if (error instanceof NotFoundError) return;
1240
+ throw error;
1241
+ }))]);
1242
+ return [...inherited, ...own.filter((template) => template !== void 0)];
1243
+ }))).flat();
1244
+ }
1245
+ /** GitLab has no write that creates or updates, so each file is looked up first, at the commit the change builds on. */
1246
+ async function commitFiles(repo, input, options) {
1247
+ const signal = options?.signal;
1248
+ const start = input.createFrom === void 0 ? void 0 : (await fetcher.json(`${projectPath(repo)}/repository/commits/${encodeURIComponent(input.createFrom)}`, { signal })).data.id;
1249
+ if (input.expectedHead !== void 0) {
1250
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/branches/${encodeURIComponent(input.branch)}`, { signal });
1251
+ if (data.commit?.id !== input.expectedHead.toLowerCase()) throw new BranchMovedError(`${input.branch} is at ${data.commit?.id}, not ${input.expectedHead}`, 409, "", context);
1252
+ }
1253
+ const ref = start ?? input.expectedHead ?? input.branch;
1254
+ const existing = await existingFiles(input.changes, async (path) => {
1255
+ try {
1256
+ return await fetcher.raw(`${projectPath(repo)}/repository/files/${encodeURIComponent(path)}`, {
1257
+ method: "HEAD",
1258
+ query: { ref },
1259
+ signal
1260
+ });
1261
+ } catch (error) {
1262
+ if (error instanceof NotFoundError) return;
1263
+ throw error;
1264
+ }
1265
+ }, context);
1266
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/commits`, {
1267
+ method: "POST",
1268
+ json: {
1269
+ branch: input.branch,
1270
+ commit_message: input.message,
1271
+ ...start && { start_sha: start },
1272
+ ...input.author && {
1273
+ author_name: input.author.name,
1274
+ author_email: input.author.email
1275
+ },
1276
+ actions: input.changes.map(({ path, content }) => content === null ? {
1277
+ action: "delete",
1278
+ file_path: path
1279
+ } : {
1280
+ action: existing.has(path) ? "update" : "create",
1281
+ file_path: path,
1282
+ ...typeof content === "string" ? { content } : {
1283
+ content: changeBase64(content),
1284
+ encoding: "base64"
1285
+ }
1286
+ })
1287
+ },
1288
+ signal
1289
+ });
1290
+ return toCommit(repo, data);
1291
+ }
1292
+ async function ownerReposPage(owner, query = {}) {
1293
+ const read = (path, extra) => list(path, query, (raw) => toRepo(instance, raw), {
1294
+ query: {
1295
+ visibility: query.visibility === "all" ? void 0 : query.visibility,
1296
+ order_by: query.sort && PROJECT_ORDER[query.sort],
1297
+ sort: query.direction,
1298
+ ...extra
1299
+ },
1300
+ warnings: query.sort === "pushed" && isFirstPage(query.cursor) ? [{
1301
+ code: "sort_unsupported",
1302
+ message: "GitLab does not report pushes; sorted by last activity, which includes issues and merge requests"
1303
+ }] : void 0
1304
+ });
1305
+ try {
1306
+ return await read(`/groups/${encodeURIComponent(owner.externalId ?? owner.owner)}/projects`, {
1307
+ include_subgroups: query.subgroups || void 0,
1308
+ with_shared: false
1309
+ });
1310
+ } catch (error) {
1311
+ if (!(error instanceof NotFoundError) || !isFirstPage(query.cursor) || !owner.owner || owner.owner.includes("/")) throw error;
1312
+ }
1313
+ return read(`/users/${encodeURIComponent(owner.owner)}/projects`, {});
1314
+ }
1315
+ /** Project hooks, or group hooks for a namespace ref. */
1316
+ function hooksPath(target) {
1317
+ return isNamespaceRef(target) ? `/groups/${encodeURIComponent(target.externalId ?? target.owner)}/hooks` : `${projectPath(target)}/hooks`;
1318
+ }
1319
+ /** GitLab subscribes with one boolean per event group rather than a list of names. */
1320
+ function hookFlags(input) {
1321
+ return Object.fromEntries(nativeEventsFor(GITLAB_NATIVE_EVENTS, input.events, input.nativeEvents).map((flag) => [flag, true]));
1322
+ }
1323
+ function requireMerge(thread, action) {
1324
+ const ref = requireThread(thread, context);
1325
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError(`Only merge requests can be ${action}`, context);
1326
+ return ref;
1327
+ }
1328
+ /** GitLab's file endpoint needs an explicit ref, so the project's default branch stands in. */
1329
+ async function defaultBranch(repo, options) {
1330
+ const { data } = await fetcher.json(projectPath(repo), { signal: options?.signal });
1331
+ return data.default_branch ?? "HEAD";
1332
+ }
1333
+ async function get(thread, options) {
1334
+ const ref = requireThread(thread, context);
1335
+ if (ref.kind === "discussion") throw new UnsupportedOperationError("GitLab has no discussion threads", context);
1336
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
1337
+ const result = toThread(ref, data);
1338
+ if (data.head_pipeline) result.checks = toPipelineSummary(data.head_pipeline);
1339
+ return result;
1340
+ }
1341
+ const graphqlUrl = `${baseUrl.replace(/\/api\/v4$/, "")}/api/graphql`;
1342
+ async function vulnerabilitiesPage(repo, listOptions = {}) {
1343
+ const state = listOptions.state ?? "open";
1344
+ const { data, response } = await fetcher.json(graphqlUrl, {
1345
+ method: "POST",
1346
+ json: {
1347
+ operationName: "ProjectVulnerabilities",
1348
+ query: VULNERABILITIES_QUERY,
1349
+ variables: {
1350
+ fullPath: `${repo.owner}/${repo.name}`,
1351
+ first: Math.min(listOptions.perPage ?? 50, 100),
1352
+ after: listOptions.cursor?.token ?? null,
1353
+ state: state === "open" ? ["DETECTED", "CONFIRMED"] : state === "closed" ? ["RESOLVED", "DISMISSED"] : null,
1354
+ reportType: listOptions.kind ? REPORT_TYPES[listOptions.kind] : null
1355
+ }
1356
+ },
1357
+ signal: listOptions.signal
1358
+ });
1359
+ const vulnerabilities = data.data?.project?.vulnerabilities;
1360
+ if (!vulnerabilities) {
1361
+ 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);
1362
+ if (listOptions.kind) throw error;
1363
+ return {
1364
+ items: [],
1365
+ warnings: [toWarning("insufficient_scope", error, `${repo.owner}/${repo.name}`)]
1366
+ };
1367
+ }
1368
+ return {
1369
+ items: vulnerabilities.nodes.map((node) => toVulnerability(repo, node)),
1370
+ cursor: vulnerabilities.pageInfo.hasNextPage && vulnerabilities.pageInfo.endCursor ? { token: vulnerabilities.pageInfo.endCursor } : void 0,
1371
+ ...rateLimitPart(response)
1372
+ };
1373
+ }
1374
+ async function releasesPage(repo, listOptions = {}) {
1375
+ return list(`${projectPath(repo)}/releases`, listOptions, (raw) => toRelease(repo, raw));
1376
+ }
1377
+ function requirePublishedRelease(input) {
1378
+ if (input.draft) throw new UnsupportedOperationError("GitLab has no draft releases", context);
1379
+ if (input.prerelease) throw new UnsupportedOperationError("GitLab has no prereleases", context);
1380
+ }
1381
+ async function listPage(repo, query = {}) {
1382
+ if (query.kind === "discussion") return {
1383
+ items: [],
1384
+ warnings: [{
1385
+ code: "kind_unsupported",
1386
+ message: "GitLab has no discussion threads"
1387
+ }]
1388
+ };
1389
+ const warnings = isFirstPage(query.cursor) && query.sort === "comments" ? [{
1390
+ code: "sort_unsupported",
1391
+ message: "GitLab cannot sort by comment count; sorted by creation time"
1392
+ }] : [];
1393
+ const state = query.state ?? "open";
1394
+ const kinds = query.kind ? [query.kind] : ["issue", "pull_request"];
1395
+ const page = await phased(kinds.map((kind) => async (cursor) => {
1396
+ const merges = kind === "pull_request";
1397
+ const result = await fetcher.page(`${projectPath(repo)}/${merges ? "merge_requests" : "issues"}`, {
1398
+ query: {
1399
+ state: state === "open" ? "opened" : state === "merged" ? "merged" : state === "closed" && !merges ? "closed" : void 0,
1400
+ labels: query.labels?.join(","),
1401
+ author_username: query.author,
1402
+ assignee_username: query.assignee,
1403
+ updated_after: query.since?.toISOString(),
1404
+ created_after: query.createdAfter?.toISOString(),
1405
+ order_by: query.sort === "updated" ? "updated_at" : "created_at",
1406
+ sort: query.direction ?? "desc",
1407
+ per_page: query.perPage
1408
+ },
1409
+ cursor,
1410
+ signal: query.signal
1411
+ });
1412
+ return toPage(result, (raw) => merges && state === "closed" && raw.state === "opened" ? void 0 : toThread({
1413
+ forge: FORGE,
1414
+ instance,
1415
+ repo,
1416
+ kind,
1417
+ number: String(raw.iid)
1418
+ }, raw));
1419
+ }), query.cursor);
1420
+ return warnings.length ? {
1421
+ ...page,
1422
+ warnings
1423
+ } : page;
1424
+ }
1425
+ /** Cross-project search runs on the global issue and merge request listings, which take `search` and `in`. */
1426
+ async function searchThreadsPage(query) {
1427
+ const warnings = [];
1428
+ if (isFirstPage(query.cursor) && query.involves) warnings.push({
1429
+ code: "filter_unsupported",
1430
+ message: "GitLab has no involves filter; it was ignored"
1431
+ });
1432
+ if (isFirstPage(query.cursor) && query.sort === "comments") warnings.push({
1433
+ code: "sort_unsupported",
1434
+ message: "GitLab cannot sort by comment count; sorted by update time"
1435
+ });
1436
+ const state = query.state ?? "all";
1437
+ const kinds = query.kind ? [query.kind] : ["issue", "pull_request"];
1438
+ const page = await phased(kinds.map((kind) => async (cursor) => {
1439
+ const merges = kind === "pull_request";
1440
+ const base = query.repo ? `${projectPath(query.repo)}/` : query.owner ? `/groups/${encodeURIComponent(query.owner)}/` : "/";
1441
+ const result = await fetcher.page(`${base}${merges ? "merge_requests" : "issues"}`, {
1442
+ query: {
1443
+ scope: query.repo ? void 0 : "all",
1444
+ search: query.text,
1445
+ in: query.text ? "title,description" : void 0,
1446
+ state: state === "open" ? "opened" : state === "closed" ? "closed" : void 0,
1447
+ labels: query.labels?.join(","),
1448
+ author_username: query.author,
1449
+ assignee_username: query.assignee,
1450
+ updated_after: query.since?.toISOString(),
1451
+ order_by: query.sort === "created" ? "created_at" : "updated_at",
1452
+ sort: query.direction ?? "desc",
1453
+ per_page: query.perPage
1454
+ },
1455
+ cursor,
1456
+ signal: query.signal
1457
+ });
1458
+ return toPage(result, (raw) => {
1459
+ const repo = query.repo ?? repoRefFromWebUrl(instance, raw.web_url, merges ? raw.target_project_id : void 0);
1460
+ return repo ? toThread({
1461
+ forge: FORGE,
1462
+ instance,
1463
+ repo,
1464
+ kind,
1465
+ number: String(raw.iid)
1466
+ }, raw) : void 0;
1467
+ });
1468
+ }), query.cursor);
1469
+ return warnings.length ? {
1470
+ ...page,
1471
+ warnings: [...warnings, ...page.warnings ?? []]
1472
+ } : page;
1473
+ }
1474
+ async function searchReposPage(query) {
1475
+ const path = query.owner ? `/groups/${encodeURIComponent(query.owner)}/projects` : "/projects";
1476
+ const result = await fetcher.page(path, {
1477
+ query: {
1478
+ search: query.text,
1479
+ order_by: query.sort === "created" ? "created_at" : query.sort === "stars" ? "star_count" : query.sort === "updated" ? "updated_at" : void 0,
1480
+ sort: query.direction,
1481
+ per_page: query.perPage
1482
+ },
1483
+ cursor: query.cursor,
1484
+ signal: query.signal
1485
+ });
1486
+ return toPage(result, (raw) => toRepo(instance, raw));
1487
+ }
1488
+ /** Needs Advanced Search, which no endpoint reports; an instance without it returns an empty page. */
1489
+ async function searchCommitsPage(query) {
1490
+ const unsupported = [
1491
+ "author",
1492
+ "committer",
1493
+ "since",
1494
+ "until",
1495
+ "sort"
1496
+ ].filter((field) => query[field] !== void 0);
1497
+ const warnings = unsupported.length ? [{
1498
+ code: "filter_unsupported",
1499
+ message: `GitLab commit search cannot filter or sort by ${unsupported.join(", ")}`
1500
+ }] : [];
1501
+ const result = await fetcher.page(query.repo ? `${projectPath(query.repo)}/search` : "/search", {
1502
+ query: {
1503
+ scope: "commits",
1504
+ search: query.text ?? "",
1505
+ per_page: query.perPage
1506
+ },
1507
+ cursor: query.cursor,
1508
+ signal: query.signal
1509
+ });
1510
+ const repo = query.repo;
1511
+ return toPage(result, (raw) => repo && toCommit(repo, raw), warnings);
1512
+ }
1513
+ /** Projects that code searches and user events named by id, kept so later pages skip the lookup. */
1514
+ const projectRefs = /* @__PURE__ */ new Map();
1515
+ /** A project the token cannot read costs its blobs and a warning, not the page. */
1516
+ async function resolveProjects(ids, signal, warnings) {
1517
+ if (!ids.length) return;
1518
+ try {
1519
+ const { data } = await fetcher.json(graphqlUrl, {
1520
+ method: "POST",
1521
+ json: {
1522
+ operationName: "CodeSearchProjects",
1523
+ query: PROJECTS_QUERY,
1524
+ variables: { ids: ids.map((id) => `gid://gitlab/Project/${id}`) }
1525
+ },
1526
+ signal
1527
+ });
1528
+ for (const node of data.data?.projects?.nodes ?? []) {
1529
+ const id = Number(node.id.slice(node.id.lastIndexOf("/") + 1));
1530
+ projectRefs.set(id, toRepoRef(instance, node.fullPath, id));
1531
+ }
1532
+ } catch (error) {
1533
+ if (!degradesToWarning(error)) throw error;
1534
+ warnings.push(...ids.map((id) => toWarning("record_unreachable", error, `project ${id}`)));
1535
+ return;
1536
+ }
1537
+ for (const id of ids.filter((id) => !projectRefs.has(id))) warnings.push({
1538
+ code: "record_unreachable",
1539
+ message: "GitLab returned no project for this id",
1540
+ subject: `project ${id}`
1541
+ });
1542
+ }
1543
+ /** Any tier searches a project; a group or the instance needs Advanced Search or exact code search. */
1544
+ async function searchCodePage(query) {
1545
+ const path = query.repo ? `${projectPath(query.repo)}/search` : query.owner ? `/groups/${encodeURIComponent(query.owner)}/search` : "/search";
1546
+ const result = await fetcher.page(path, {
1547
+ query: {
1548
+ scope: "blobs",
1549
+ search: query.text ?? "",
1550
+ per_page: query.perPage
1551
+ },
1552
+ cursor: query.cursor,
1553
+ signal: query.signal
1554
+ });
1555
+ const warnings = [];
1556
+ await resolveProjects(query.repo ? [] : [...new Set((result.data ?? []).map((raw) => raw.project_id))].filter((id) => !projectRefs.has(id)), query.signal, warnings);
1557
+ /** GitLab returns one blob per excerpt; basic search lists a file again, with the same first excerpt, when its name matches too. */
1558
+ const files = /* @__PURE__ */ new Map();
1559
+ for (const blob of result.data ?? []) {
1560
+ const key = `${blob.project_id}:${blob.ref}:${blob.path}`;
1561
+ const excerpts = files.get(key);
1562
+ if (!excerpts) files.set(key, [blob]);
1563
+ else if (!excerpts.some((seen) => seen.startline === blob.startline && seen.data === blob.data)) excerpts.push(blob);
1564
+ }
1565
+ return toPage({
1566
+ ...result,
1567
+ data: [...files.values()]
1568
+ }, (excerpts) => {
1569
+ const [first] = excerpts;
1570
+ const repo = query.repo ?? projectRefs.get(first.project_id);
1571
+ if (!repo) return;
1572
+ const url = webUrlFor(web, { file: {
1573
+ repo,
1574
+ path: first.path,
1575
+ at: first.ref,
1576
+ line: first.startline
1577
+ } });
1578
+ return {
1579
+ repo,
1580
+ path: first.path,
1581
+ ref: first.ref,
1582
+ fragments: excerpts.map((raw) => ({
1583
+ text: raw.data,
1584
+ line: raw.startline
1585
+ })),
1586
+ url,
1587
+ raw: excerpts
1588
+ };
1589
+ }, warnings);
1590
+ }
1591
+ /** A user's events name each project by id alone, so the page resolves the ids it has not seen. */
1592
+ async function feedPage(path, listOptions, repo) {
1593
+ const result = await fetcher.page(path, {
1594
+ query: { per_page: listOptions.perPage },
1595
+ cursor: listOptions.cursor,
1596
+ signal: listOptions.signal
1597
+ });
1598
+ const warnings = [];
1599
+ 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);
1600
+ const { toFeedEvent } = await import("./feed-Dyf730Ys-D0HgBba6.js");
1601
+ return toPage(result, (raw) => toFeedEvent(instance, raw, repo ?? (typeof raw.project_id === "number" ? projectRefs.get(raw.project_id) : void 0)), warnings);
1602
+ }
1603
+ async function setSubscribed(thread, subscribed, options) {
1604
+ const ref = requireIssueOrPull(thread, context, subscribed ? "subscribe to" : "unsubscribe from");
1605
+ await fetcher.raw(`${threadPath(ref)}/${subscribed ? "subscribe" : "unsubscribe"}`, {
1606
+ method: "POST",
1607
+ signal: options?.signal
1608
+ });
1609
+ }
1610
+ async function unsubscribe(_ref, writeOptions = {}) {
1611
+ if (!writeOptions.thread) throw new UnresolvedThreadError("GitLab cannot look up a to-do by id; pass { thread } to unsubscribe", context);
1612
+ const thread = requireThread(writeOptions.thread, context);
1613
+ if (thread.kind !== "issue" && thread.kind !== "pull_request") throw new UnsupportedOperationError(`GitLab cannot unsubscribe from a ${thread.kind}`, context);
1614
+ await fetcher.raw(`${threadPath(thread)}/unsubscribe`, {
1615
+ method: "POST",
1616
+ signal: writeOptions.signal
1617
+ });
1618
+ }
1619
+ async function setState(thread, stateEvent, options) {
1620
+ const ref = requireIssueOrPull(thread, context, stateEvent);
1621
+ const { data } = await fetcher.json(threadPath(ref), {
1622
+ method: "PUT",
1623
+ json: { state_event: stateEvent },
1624
+ signal: options?.signal
1625
+ });
1626
+ return toThread(ref, data);
1627
+ }
1628
+ async function setLocked(thread, locked, options) {
1629
+ const ref = requireIssueOrPull(thread, context, locked ? "lock" : "unlock");
1630
+ await fetcher.raw(threadPath(ref), {
1631
+ method: "PUT",
1632
+ json: { discussion_locked: locked },
1633
+ signal: options?.signal
1634
+ });
1635
+ }
1636
+ async function resolveMergeMethod(ref, requested, signal) {
1637
+ if (requested === "squash") return requested;
1638
+ const { data: project } = await fetcher.json(`/projects/${projectId(ref.repo)}`, { signal });
1639
+ const base = BASE_METHODS[project.merge_method ?? "merge"];
1640
+ const squash = project.squash_option ?? "default_off";
1641
+ if (requested) {
1642
+ if (requested !== base || squash === "always") throw new UnsupportedOperationError(`This project merges with ${squash === "always" ? "squash" : base}; GitLab cannot override it per merge request`, context);
1643
+ return requested;
1644
+ }
1645
+ return soleMergeMethod({
1646
+ [base]: squash !== "always",
1647
+ squash: squash !== "never"
1648
+ }, context);
1649
+ }
1650
+ /** GitLab has approvals, not reviews: one synthesised review per approver, with no comments to hang on it. */
1651
+ function toApprovalReviews(ref, approvals) {
1652
+ return (approvals.approved_by ?? []).map(({ user }) => syntheticReview(ref, approvalId(user), "approved", {
1653
+ author: toActor(instance, user),
1654
+ stateRaw: "approved",
1655
+ raw: user
1656
+ }));
1657
+ }
1658
+ async function approve(thread, body, options) {
1659
+ const ref = requireThread(thread, context);
1660
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be approved", context);
1661
+ if (body) throw new UnsupportedOperationError("GitLab approvals carry no body; leave a comment instead", context);
1662
+ const { data } = await fetcher.json(`${threadPath(ref)}/approve`, {
1663
+ method: "POST",
1664
+ signal: options?.signal,
1665
+ mapError: (error) => error instanceof TokenRevokedError ? new InsufficientScopeError("Not allowed to approve this merge request", 401, error.body, {
1666
+ ...context,
1667
+ url: error.url,
1668
+ method: error.method
1669
+ }, { cause: error }) : error
1670
+ });
1671
+ const reviews = toApprovalReviews(ref, data);
1672
+ const viewer = reviews.length > 1 ? await viewerLogin() : void 0;
1673
+ return reviews.find((review) => viewer !== void 0 && review.author?.login === viewer) ?? reviews.at(-1) ?? {
1674
+ ref: {
1675
+ forge: "gitlab",
1676
+ instance,
1677
+ thread: ref,
1678
+ id: "approval:"
1679
+ },
1680
+ state: "approved",
1681
+ stateRaw: "approved",
1682
+ comments: false,
1683
+ raw: data
1684
+ };
1685
+ }
1686
+ async function merge(thread, mergeOptions = {}) {
1687
+ const ref = requireThread(thread, context);
1688
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be merged", context);
1689
+ const method = await resolveMergeMethod(ref, mergeOptions.method, mergeOptions.signal);
1690
+ const message = mergeCommitMessage(mergeOptions);
1691
+ const { data } = await fetcher.json(`${threadPath(ref)}/merge`, {
1692
+ method: "PUT",
1693
+ json: {
1694
+ sha: mergeOptions.sha,
1695
+ ...message ? { [method === "squash" ? "squash_commit_message" : "merge_commit_message"]: message } : {},
1696
+ squash: method === "squash",
1697
+ merge_when_pipeline_succeeds: mergeOptions.whenChecksPass ?? false
1698
+ },
1699
+ mapError: toMergeError,
1700
+ signal: mergeOptions.signal
1701
+ });
1702
+ return data.state === "merged" ? {
1703
+ status: "merged",
1704
+ sha: data.merge_commit_sha ?? data.squash_commit_sha ?? void 0,
1705
+ raw: data
1706
+ } : {
1707
+ status: "queued",
1708
+ raw: data
1709
+ };
1710
+ }
1711
+ /** An issue or merge request from a listing that spans projects, or `undefined` for one from an external issue tracker. */
1712
+ function referencedThread(raw, kind) {
1713
+ const path = raw.references?.full?.replace(/[#!]\d+$/, "");
1714
+ const project = kind === "pull_request" ? raw.target_project_id : raw.project_id;
1715
+ const repo = path ? toRepoRef(instance, path, project) : repoRefFromWebUrl(instance, raw.web_url, project);
1716
+ return repo && raw.iid !== void 0 ? toThread({
1717
+ forge: FORGE,
1718
+ instance,
1719
+ repo,
1720
+ kind,
1721
+ number: String(raw.iid)
1722
+ }, raw) : void 0;
1723
+ }
1724
+ /** GitLab rebases only, in the background, and takes no expected head, so `sha` is compared against a read of the merge request first. */
1725
+ async function updateBranch(thread, updateOptions = {}) {
1726
+ const ref = requireThread(thread, context);
1727
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests can be updated", context);
1728
+ if (updateOptions.method === "merge") throw new UnsupportedOperationError("GitLab updates a merge request by rebasing it only", context);
1729
+ const { sha, signal } = updateOptions;
1730
+ if (sha !== void 0) {
1731
+ const { data } = await fetcher.json(threadPath(ref), { signal });
1732
+ if (data.sha !== sha) throw new BranchMovedError(`Source branch of merge request ${ref.number} is at ${data.sha}, not ${sha}`, 409, "", context);
1733
+ }
1734
+ const { data } = await fetcher.json(`${threadPath(ref)}/rebase`, {
1735
+ method: "PUT",
1736
+ signal
1737
+ });
1738
+ return {
1739
+ status: "queued",
1740
+ raw: data
1741
+ };
1742
+ }
1743
+ return {
1744
+ traits: {
1745
+ eventKinds: "heuristic",
1746
+ authKinds: ["token", "anonymous"],
1747
+ limits: {
1748
+ bodyLength: 1048576,
1749
+ commentLength: 1e6,
1750
+ labelLength: 255
1751
+ }
1752
+ },
1753
+ notApplicable: ["threads.hideComment"],
1754
+ probeVersion: async () => (await fetcher.json("/version")).data.version,
1755
+ web,
1756
+ webhooks: {
1757
+ listPage: verb(true, (target, listOptions = {}) => list(hooksPath(target), listOptions, (raw) => toWebhook(target, raw))),
1758
+ create: verb(true, async (target, input, options) => toWebhook(target, (await fetcher.json(hooksPath(target), {
1759
+ method: "POST",
1760
+ json: {
1761
+ url: input.url,
1762
+ token: input.secret,
1763
+ ...hookFlags(input)
1764
+ },
1765
+ signal: options?.signal
1766
+ })).data)),
1767
+ update: verb(true, async (ref, update, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${ref.id}`, {
1768
+ method: "PUT",
1769
+ json: {
1770
+ ...update.url ? { url: update.url } : {},
1771
+ ...update.secret ? { token: update.secret } : {},
1772
+ ...hookFlags(update)
1773
+ },
1774
+ signal: options?.signal
1775
+ })).data)),
1776
+ delete: verb(true, async (ref, options) => {
1777
+ await fetcher.raw(`${hooksPath(ref.target)}/${ref.id}`, {
1778
+ method: "DELETE",
1779
+ signal: options?.signal
1780
+ });
1781
+ }),
1782
+ rotateSecret: verb(true, async (ref, secret, options) => toWebhook(ref.target, (await fetcher.json(`${hooksPath(ref.target)}/${ref.id}`, {
1783
+ method: "PUT",
1784
+ json: { token: secret },
1785
+ signal: options?.signal
1786
+ })).data)),
1787
+ deliveriesPage: verb(({ version }) => versionAtLeast(version, GITLAB_HOOK_EVENTS), (ref, listOptions = {}) => list(`${hooksPath(ref.target)}/${ref.id}/events`, listOptions, (raw) => toWebhookDelivery(ref, raw))),
1788
+ redeliver: verb(({ version }) => versionAtLeast(version, GITLAB_HOOK_EVENTS), async (ref, options) => {
1789
+ await fetcher.raw(`${hooksPath(ref.hook.target)}/${ref.hook.id}/events/${ref.id}/resend`, {
1790
+ method: "POST",
1791
+ signal: options?.signal
1792
+ });
1793
+ })
1794
+ },
1795
+ scopes: gitlabScopesFor,
1796
+ users: {
1797
+ get: verb(true, async (login, options) => {
1798
+ const { data: matches } = await fetcher.json("/users", {
1799
+ query: { username: login },
1800
+ signal: options?.signal
1801
+ });
1802
+ const [match] = matches ?? [];
1803
+ if (!match) throw new NotFoundError(`No GitLab user named ${login}`, 404, "", context);
1804
+ try {
1805
+ return await readUser(`/users/${match.id}`, options?.signal);
1806
+ } catch (error) {
1807
+ if (error instanceof InsufficientScopeError || error instanceof AuthenticationRequiredError) return {
1808
+ ...toActor(instance, match),
1809
+ raw: match
1810
+ };
1811
+ throw error;
1812
+ }
1813
+ }),
1814
+ me: verb(true, (options) => readUser("/user", options?.signal)),
1815
+ eventsPage: verb(true, (login, listOptions = {}) => feedPage(`/users/${encodeURIComponent(login)}/events`, listOptions))
1816
+ },
1817
+ repos: {
1818
+ get: verb(true, async (ref, options) => {
1819
+ const query = options?.licence ? { license: true } : void 0;
1820
+ return toRepo(instance, (await fetcher.json(projectPath(ref), {
1821
+ query,
1822
+ signal: options?.signal
1823
+ })).data);
1824
+ }),
1825
+ listPage: verb(true, (listOptions = {}) => list("/projects", listOptions, (raw) => toRepo(instance, raw), { query: { membership: true } })),
1826
+ byOwnerPage: verb(true, ownerReposPage),
1827
+ labelsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${projectPath(repo)}/labels`, listOptions, toLabel)),
1828
+ createLabel: verb(true, async (repo, label, options) => toLabel((await fetcher.json(`${projectPath(repo)}/labels`, {
1829
+ method: "POST",
1830
+ json: {
1831
+ name: label.name,
1832
+ color: hexColour(label.colour, "#"),
1833
+ description: label.description
1834
+ },
1835
+ signal: options?.signal
1836
+ })).data)),
1837
+ milestonesPage: verb(!anonymous, milestonesPage),
1838
+ collaboratorsPage: verb(!anonymous, (repo, listOptions = {}) => list(`${projectPath(repo)}/members/all`, listOptions, (raw) => ({
1839
+ actor: toActor(instance, raw),
1840
+ role: toRole(raw.access_level),
1841
+ roleRaw: String(raw.access_level),
1842
+ raw
1843
+ }))),
1844
+ templates: verb(true, templates),
1845
+ contributorsPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/contributors`, listOptions, (raw) => ({
1846
+ name: raw.name || void 0,
1847
+ email: raw.email || void 0,
1848
+ contributions: raw.commits,
1849
+ raw
1850
+ }), {
1851
+ query: {
1852
+ order_by: "commits",
1853
+ sort: "desc"
1854
+ },
1855
+ warnings: listOptions.includeUnlinked === false && isFirstPage(listOptions.cursor) ? [{
1856
+ code: "filter_unsupported",
1857
+ message: "GitLab links no contributor accounts, so it cannot leave the unlinked ones out; the option was ignored"
1858
+ }] : []
1859
+ })),
1860
+ permissionFor: verb(!anonymous, async (repo, actor, options) => {
1861
+ try {
1862
+ const { data } = await fetcher.json(`${projectPath(repo)}/members/all/${await userId(actor)}`, { signal: options?.signal });
1863
+ return toRole(data.access_level);
1864
+ } catch (error) {
1865
+ if (error instanceof NotFoundError) return "none";
1866
+ throw error;
1867
+ }
1868
+ }),
1869
+ branchRules: verb(!anonymous, async (repo, name, options) => {
1870
+ const warnings = [];
1871
+ const [{ data: branch }, { data: project }, rules] = await Promise.all([
1872
+ fetcher.json(`${projectPath(repo)}/repository/branches/${encodeURIComponent(name)}`, { signal: options?.signal }),
1873
+ fetcher.json(projectPath(repo), { signal: options?.signal }),
1874
+ Array.fromAsync(fetcher.items(`${projectPath(repo)}/approval_rules`, {
1875
+ query: { per_page: 100 },
1876
+ signal: options?.signal
1877
+ })).catch((error) => {
1878
+ if (!(error instanceof ForbiddenError || error instanceof InsufficientScopeError || error instanceof NotFoundError)) throw error;
1879
+ warnings.push(toWarning("insufficient_scope", error, "approval_rules"));
1880
+ })
1881
+ ]);
1882
+ return toBranchRules(branch, project, rules, warnings);
1883
+ }),
1884
+ addCollaborator: verb(true, async (repo, actor, role, options) => {
1885
+ await fetcher.raw(`${projectPath(repo)}/members`, {
1886
+ method: "POST",
1887
+ json: {
1888
+ user_id: await userId(actor),
1889
+ access_level: ACCESS_LEVELS[role]
1890
+ },
1891
+ signal: options?.signal
1892
+ });
1893
+ return { status: "added" };
1894
+ }),
1895
+ assignableUsersPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/users`, listOptions, (raw) => toActor(instance, raw))),
1896
+ reviewerCandidatesPage: verb("emulated", (thread, listOptions = {}) => list(`${projectPath(requireThread(thread, context).repo)}/users`, listOptions, (raw) => toActor(instance, raw))),
1897
+ eventsPage: verb(true, (repo, listOptions = {}) => feedPage(`${projectPath(repo)}/events`, listOptions, repo))
1898
+ },
1899
+ orgs: {
1900
+ /** 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. */
1901
+ 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 } })),
1902
+ teamMembersPage: verb(!anonymous, (team, listOptions = {}) => list(`/groups/${encodeURIComponent(team.id ?? `${team.org.owner}/${team.slug}`)}/members`, listOptions, (raw) => toActor(instance, raw)))
1903
+ },
1904
+ notifications: {
1905
+ listPage: verb(true, notificationPage),
1906
+ markDone: verb(true, async (ref, options) => {
1907
+ await fetcher.raw(`/todos/${ref.id}/mark_as_done`, {
1908
+ method: "POST",
1909
+ signal: options?.signal
1910
+ });
1911
+ }),
1912
+ unsubscribe: verb(true, unsubscribe),
1913
+ markAllDone: verb(true, async (bulk = {}) => {
1914
+ if (bulk.repo || bulk.before) throw new UnsupportedOperationError("GitLab marks every to-do done at once; repo and before filters are not supported", context);
1915
+ await fetcher.raw("/todos/mark_as_done", {
1916
+ method: "POST",
1917
+ signal: bulk.signal
1918
+ });
1919
+ }),
1920
+ unreadCount: verb(true, async (options) => {
1921
+ const total = (await fetcher.raw("/todos", {
1922
+ query: {
1923
+ state: "pending",
1924
+ per_page: 1
1925
+ },
1926
+ signal: options?.signal
1927
+ })).headers.get("x-total");
1928
+ if (total === null) throw new UnsupportedOperationError("GitLab omitted X-Total; the to-do count is too large to report", context);
1929
+ return Number(total);
1930
+ })
1931
+ },
1932
+ contents: {
1933
+ getFile: verb(true, async (repo, path, fileOptions = {}) => {
1934
+ const target = `${projectPath(repo)}/repository/files/${encodeURIComponent(path.replace(/^\//, ""))}`;
1935
+ if (fileOptions.metadata === false) {
1936
+ const response = await fetcher.raw(`${target}/raw`, {
1937
+ query: { ref: fileOptions.ref },
1938
+ signal: fileOptions.signal
1939
+ });
1940
+ const bytes = new Uint8Array(await response.arrayBuffer());
1941
+ return toFileContent(bytes, {
1942
+ path: path.replace(/^\//, ""),
1943
+ size: bytes.byteLength
1944
+ }, fileOptions, context);
1945
+ }
1946
+ const ref = fileOptions.ref ?? await defaultBranch(repo, fileOptions);
1947
+ const { data } = await fetcher.json(target, {
1948
+ query: { ref },
1949
+ signal: fileOptions.signal
1950
+ });
1951
+ const file = {
1952
+ path: data.file_path,
1953
+ sha: data.blob_id,
1954
+ size: data.size
1955
+ };
1956
+ return toFileContent(fromBase64(data.content ?? ""), file, fileOptions, context);
1957
+ }),
1958
+ treePage: verb(true, (repo, treeOptions = {}) => list(`${projectPath(repo)}/repository/tree`, treeOptions, toTreeEntry, { query: {
1959
+ ref: treeOptions.ref,
1960
+ path: treeOptions.path,
1961
+ recursive: treeOptions.recursive ? "true" : void 0
1962
+ } })),
1963
+ branchesPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/branches`, listOptions, toBranch)),
1964
+ tagsPage: verb(true, (repo, listOptions = {}) => list(`${projectPath(repo)}/repository/tags`, listOptions, toTag)),
1965
+ resolveRef: verb(true, async (repo, ref, options) => (await fetcher.json(`${projectPath(repo)}/repository/commits/${encodeURIComponent(ref)}`, { signal: options?.signal })).data.id),
1966
+ compare: verb(true, async (repo, base, head, options) => {
1967
+ const { data } = await fetcher.json(`${projectPath(repo)}/repository/compare`, {
1968
+ query: {
1969
+ from: base,
1970
+ to: head
1971
+ },
1972
+ signal: options?.signal
1973
+ });
1974
+ return {
1975
+ base,
1976
+ head,
1977
+ aheadBy: data.commits?.length,
1978
+ commits: (data.commits ?? []).map((raw) => toCommit(repo, raw)).toReversed(),
1979
+ files: (data.diffs ?? []).map(toChangedFile),
1980
+ raw: data
1981
+ };
1982
+ }),
1983
+ commitFiles: verb(true, commitFiles)
1984
+ },
1985
+ commits: {
1986
+ listPage: verb(true, (repo, query = {}) => list(`${projectPath(repo)}/repository/commits`, query, (raw) => toCommit(repo, raw), { query: {
1987
+ ref_name: query.ref,
1988
+ path: query.path,
1989
+ author: query.author,
1990
+ since: query.since?.toISOString(),
1991
+ until: query.until?.toISOString()
1992
+ } })),
1993
+ get: verb(true, async ({ repo, sha }, options) => {
1994
+ const [commit, diffs] = await Promise.all([fetcher.json(`${projectPath(repo)}/repository/commits/${sha}`, {
1995
+ query: { stats: "true" },
1996
+ signal: options?.signal
1997
+ }), fetcher.json(`${projectPath(repo)}/repository/commits/${sha}/diff`, { signal: options?.signal })]);
1998
+ return toCommit(repo, commit.data, (diffs.data ?? []).map(toChangedFile));
1999
+ }),
2000
+ commentsPage: verb(true, (commit, listOptions = {}) => list(`${projectPath(commit.repo)}/repository/commits/${encodeURIComponent(commit.sha)}/comments`, listOptions, (comment) => toCommitComment(commit, comment))),
2001
+ createComment: verb(true, async (commit, body, options) => {
2002
+ const { data } = await fetcher.json(`${projectPath(commit.repo)}/repository/commits/${encodeURIComponent(commit.sha)}/comments`, {
2003
+ method: "POST",
2004
+ json: { note: body },
2005
+ signal: options?.signal
2006
+ });
2007
+ return toCommitComment(commit, data);
2008
+ })
2009
+ },
2010
+ releases: {
2011
+ listPage: verb(true, releasesPage),
2012
+ 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)),
2013
+ getByTag: verb(true, async (repo, tag, options) => toRelease(repo, (await fetcher.json(`${projectPath(repo)}/releases/${encodeURIComponent(tag)}`, { signal: options?.signal })).data)),
2014
+ latest: verb(true, async (repo, options) => {
2015
+ const [newest] = (await releasesPage(repo, {
2016
+ perPage: 1,
2017
+ signal: options?.signal
2018
+ })).items;
2019
+ if (!newest || newest.publishedAt) return newest;
2020
+ return (await releasesPage(repo, {
2021
+ perPage: 20,
2022
+ signal: options?.signal
2023
+ })).items.find((release) => release.publishedAt);
2024
+ }),
2025
+ create: verb(true, async (repo, input, options) => {
2026
+ requirePublishedRelease(input);
2027
+ const { data } = await fetcher.json(`${projectPath(repo)}/releases`, {
2028
+ method: "POST",
2029
+ json: {
2030
+ tag_name: input.tag,
2031
+ ref: input.target,
2032
+ name: input.name,
2033
+ description: input.body
2034
+ },
2035
+ signal: options?.signal
2036
+ });
2037
+ return toRelease(repo, data);
2038
+ }),
2039
+ update: verb(true, async (ref, update, options) => {
2040
+ requirePublishedRelease(update);
2041
+ const tag = ref.tag ?? ref.id;
2042
+ if (update.tag !== void 0 && update.tag !== tag) throw new UnsupportedOperationError("GitLab keys a release by its tag, so the tag cannot change", context);
2043
+ if (update.target !== void 0) throw new UnsupportedOperationError("GitLab cannot change the commit a release points to", context);
2044
+ const { data } = await fetcher.json(`${projectPath(ref.repo)}/releases/${encodeURIComponent(tag)}`, {
2045
+ method: "PUT",
2046
+ json: {
2047
+ name: update.name,
2048
+ description: update.body
2049
+ },
2050
+ signal: options?.signal
2051
+ });
2052
+ return toRelease(ref.repo, data);
2053
+ })
2054
+ },
2055
+ search: {
2056
+ threadsPage: verb(true, searchThreadsPage),
2057
+ reposPage: verb(true, searchReposPage),
2058
+ commitsPage: verb(!anonymous && "experimental", searchCommitsPage),
2059
+ codePage: verb(!anonymous, searchCodePage)
2060
+ },
2061
+ checks: {
2062
+ list: verb(!anonymous, async (repo, sha, options) => ({ items: await Array.fromAsync(fetcher.items(`${projectPath(repo)}/repository/commits/${sha}/statuses`, {
2063
+ query: { per_page: 100 },
2064
+ signal: options?.signal
2065
+ }), (raw) => toStatusCheck(repo, raw)) })),
2066
+ report: verb(true, async (repo, sha, input, options) => toStatusCheck(repo, (await fetcher.json(`${projectPath(repo)}/statuses/${sha}`, {
2067
+ method: "POST",
2068
+ json: {
2069
+ state: STATUS_STATES[input.state],
2070
+ name: input.name,
2071
+ description: input.description,
2072
+ target_url: input.url
2073
+ },
2074
+ signal: options?.signal
2075
+ })).data)),
2076
+ rerun: verb(true, async (ref, options) => {
2077
+ if (ref.type !== "job" && ref.type !== "status") throw new UnsupportedOperationError(`GitLab cannot re-run a ${ref.type}`, context);
2078
+ await fetcher.raw(`${projectPath(ref.repo)}/jobs/${ref.id}/retry`, {
2079
+ method: "POST",
2080
+ signal: options?.signal
2081
+ });
2082
+ })
2083
+ },
2084
+ ci: {
2085
+ runsPage: verb(true, (repo, query = {}) => list(`${projectPath(repo)}/pipelines`, query, (raw) => toPipeline(repo, raw), { query: {
2086
+ ref: query.branch,
2087
+ status: PIPELINE_STATES[query.state ?? "unknown"]
2088
+ } })),
2089
+ getRun: verb(true, async (ref, options) => toPipeline(ref.repo, (await fetcher.json(`${projectPath(ref.repo)}/pipelines/${ref.id}`, { signal: options?.signal })).data)),
2090
+ jobsPage: verb(true, (ref, listOptions = {}) => list(`${projectPath(ref.repo)}/pipelines/${ref.id}/jobs`, listOptions, (raw) => toCiJob(ref, raw))),
2091
+ getJob: verb(!anonymous, async (ref, options) => {
2092
+ const { data } = await fetcher.json(`${projectPath(ref.repo)}/jobs/${encodeURIComponent(ref.id)}`, { signal: options?.signal });
2093
+ const run = ref.run ?? (data.pipeline && {
2094
+ forge: "gitlab",
2095
+ instance,
2096
+ repo: ref.repo,
2097
+ id: String(data.pipeline.id)
2098
+ });
2099
+ if (!run) throw new UnsupportedOperationError(`GitLab returned job ${ref.id} without its pipeline, and the ref names no run`, context);
2100
+ return toCiJob(run, data);
2101
+ }),
2102
+ log: verb(!anonymous, async (ref, options) => (await fetcher.stream(`${projectPath(ref.repo)}/jobs/${encodeURIComponent(ref.id)}/trace`, { signal: options?.signal })).body),
2103
+ rerunFailed: verb(true, async (ref, options) => {
2104
+ await fetcher.raw(`${projectPath(ref.repo)}/pipelines/${encodeURIComponent(ref.id)}/retry`, {
2105
+ method: "POST",
2106
+ signal: options?.signal
2107
+ });
2108
+ })
2109
+ },
2110
+ securityAlerts: {
2111
+ kinds: {
2112
+ dependency: !anonymous,
2113
+ code_scanning: !anonymous,
2114
+ secret: !anonymous
2115
+ },
2116
+ listPage: vulnerabilitiesPage
2117
+ },
2118
+ emulated: { getCommitComment: anonymous ? "unverified" : "emulated" },
2119
+ threads: {
2120
+ filesPage: verb(true, (thread, listOptions = {}) => list(`${threadPath(requireMerge(thread, "read for changed files"))}/diffs`, listOptions, toChangedFile)),
2121
+ commitsPage: verb(true, (thread, listOptions = {}) => list(`${threadPath(requireMerge(thread, "read for commits"))}/commits`, listOptions, (raw) => toCommit(thread.repo, raw))),
2122
+ reviewsPage: verb("emulated", async (thread, listOptions) => {
2123
+ const ref = requireThread(thread, context);
2124
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests have approvals", context);
2125
+ const { data, response } = await fetcher.json(`${threadPath(ref)}/approvals`, { signal: listOptions?.signal });
2126
+ return {
2127
+ items: toApprovalReviews(ref, data),
2128
+ ...rateLimitPart(response)
2129
+ };
2130
+ }),
2131
+ approve: verb(true, approve),
2132
+ createReview: verb("emulated", async (thread, input, options) => {
2133
+ if (input.comments?.length) throw new UnsupportedOperationError("GitLab reviews carry no inline comments yet", context);
2134
+ const ref = requireThread(thread, context);
2135
+ if (input.event === "comment" && input.body) {
2136
+ const { data } = await fetcher.json(`${threadPath(ref)}/discussions`, {
2137
+ method: "POST",
2138
+ json: { body: input.body },
2139
+ signal: options?.signal
2140
+ });
2141
+ const note = data.notes[0];
2142
+ return {
2143
+ ...syntheticReview(ref, `discussion:${data.id}`, "commented", {
2144
+ author: toActor(instance, note.author),
2145
+ stateRaw: "discussion",
2146
+ submittedAt: toDate(note.created_at),
2147
+ raw: data
2148
+ }),
2149
+ body: note.body,
2150
+ comments: [{
2151
+ ...toNoteComment(ref, note, data),
2152
+ raw: note
2153
+ }]
2154
+ };
2155
+ }
2156
+ if (input.event !== "approve") throw new UnsupportedOperationError("GitLab has approvals and discussions, not reviews; use `threads.approve()`, or `threads.createComment()` with a body", context);
2157
+ return approve(ref, input.body, options);
2158
+ }),
2159
+ replyToReviewComment: verb(true, async (thread, comment, body, options) => {
2160
+ const ref = requireMerge(thread, "reviewed");
2161
+ if (comment.thread === void 0) throw new UnsupportedOperationError("GitLab replies inside a discussion; pass a comment with its `thread` from `comments()`", context);
2162
+ const { data } = await fetcher.json(`${threadPath(ref)}/discussions/${encodeURIComponent(comment.thread.id)}/notes`, {
2163
+ method: "POST",
2164
+ json: { body },
2165
+ signal: options?.signal
2166
+ });
2167
+ return {
2168
+ ...toNoteComment(ref, data),
2169
+ thread: {
2170
+ id: comment.thread.id,
2171
+ resolved: Boolean(data.resolved)
2172
+ }
2173
+ };
2174
+ }),
2175
+ reviewThreads: verb(true, {
2176
+ resolveReviewThread: (thread, id, options) => setDiscussionResolved(thread, id, true, options),
2177
+ unresolveReviewThread: (thread, id, options) => setDiscussionResolved(thread, id, false, options)
2178
+ }),
2179
+ checks: perKind({ pull_request: true }, async (thread, options) => {
2180
+ const ref = requireThread(thread, context);
2181
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
2182
+ if (!data.head_pipeline) return { items: [] };
2183
+ const pipelineProject = data.head_pipeline.project_id;
2184
+ const own = pipelineProject === void 0 || pipelineProject === data.target_project_id;
2185
+ const project = own ? projectPath(ref.repo) : `/projects/${pipelineProject}`;
2186
+ const repo = own ? ref.repo : repoRefFromWebUrl(instance, data.head_pipeline.web_url, pipelineProject);
2187
+ const run = repo && {
2188
+ forge: "gitlab",
2189
+ instance,
2190
+ repo,
2191
+ id: String(data.head_pipeline.id)
2192
+ };
2193
+ return { items: await Array.fromAsync(fetcher.items(`${project}/pipelines/${data.head_pipeline.id}/jobs`, {
2194
+ query: { per_page: 100 },
2195
+ signal: options?.signal
2196
+ }), (job) => toJobCheck(repo ?? ref.repo, job, run)) };
2197
+ }),
2198
+ get: perKind({
2199
+ issue: true,
2200
+ pull_request: true
2201
+ }, get),
2202
+ getMany: verb(true, (refs, options) => getManyConcurrently(refs, get, options)),
2203
+ closingIssuesPage: verb(true, async (thread, listOptions = {}) => {
2204
+ const ref = requireThread(thread, context);
2205
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests close issues", context);
2206
+ return list(`${threadPath(ref)}/closes_issues`, listOptions, (raw) => referencedThread(raw, "issue"));
2207
+ }),
2208
+ closingPullRequestsPage: verb(true, async (thread, listOptions = {}) => {
2209
+ const ref = requireThread(thread, context);
2210
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("Only issues are closed by merge requests", context);
2211
+ return list(`${threadPath(ref)}/closed_by`, listOptions, (raw) => referencedThread(raw, "pull_request"));
2212
+ }),
2213
+ listPage: perKind(ISSUE_LIKE, listPage),
2214
+ eventsPage: verb(!anonymous, async (thread, listOptions = {}) => {
2215
+ const ref = requireThread(thread, context);
2216
+ return list(`${threadPath(ref)}/notes`, listOptions, (note) => toNoteEvent(ref, note), { query: {
2217
+ sort: "asc",
2218
+ order_by: "created_at"
2219
+ } });
2220
+ }),
2221
+ commentsPage: perKind({
2222
+ issue: !anonymous,
2223
+ pull_request: !anonymous
2224
+ }, async (thread, listOptions = {}) => {
2225
+ const ref = requireThread(thread, context);
2226
+ const page = await list(`${threadPath(requireIssueOrPull(ref, context, "list comments on"))}/discussions`, listOptions, (discussion) => discussion);
2227
+ return {
2228
+ ...page,
2229
+ items: page.items.flatMap((discussion) => discussion.notes.filter((note) => !note.system).map((note) => toNoteComment(ref, note, discussion)))
2230
+ };
2231
+ }),
2232
+ getComment: perKind({
2233
+ issue: !anonymous,
2234
+ pull_request: !anonymous
2235
+ }, async (ref, options) => {
2236
+ const thread = requireIssueOrPull(ref.thread, context, "read comments on");
2237
+ const { data } = await fetcher.json(`${threadPath(thread)}/notes/${ref.id}`, { signal: options?.signal });
2238
+ if (data.system) throw new NotFoundError(`Comment ${ref.id} not found`, 404, "", context);
2239
+ if (!data.resolvable) return toNoteComment(thread, data);
2240
+ for await (const discussion of fetcher.items(`${threadPath(thread)}/discussions`, {
2241
+ query: { per_page: 100 },
2242
+ signal: options?.signal
2243
+ })) {
2244
+ const note = discussion.notes.find((candidate) => String(candidate.id) === ref.id);
2245
+ if (note) return toNoteComment(thread, note, discussion);
2246
+ }
2247
+ return toNoteComment(thread, data);
2248
+ }),
2249
+ createComment: perKind({
2250
+ issue: true,
2251
+ pull_request: true
2252
+ }, async (thread, body, options) => {
2253
+ const ref = requireThread(thread, context);
2254
+ const { data } = await fetcher.json(`${threadPath(requireIssueOrPull(ref, context, "comment on"))}/notes`, {
2255
+ method: "POST",
2256
+ json: { body },
2257
+ signal: options?.signal
2258
+ });
2259
+ return toNoteComment(ref, data);
2260
+ }),
2261
+ updateComment: perKind({
2262
+ issue: true,
2263
+ pull_request: true
2264
+ }, async (ref, body, options) => {
2265
+ const thread = requireIssueOrPull(ref.thread, context, "edit comments on");
2266
+ const { data } = await fetcher.json(`${threadPath(thread)}/notes/${ref.id}`, {
2267
+ method: "PUT",
2268
+ json: { body },
2269
+ signal: options?.signal
2270
+ });
2271
+ return toNoteComment(thread, data);
2272
+ }),
2273
+ deleteComment: perKind({
2274
+ issue: true,
2275
+ pull_request: true
2276
+ }, async (ref, options) => {
2277
+ const thread = requireIssueOrPull(ref.thread, context, "delete comments on");
2278
+ await fetcher.raw(`${threadPath(thread)}/notes/${ref.id}`, {
2279
+ method: "DELETE",
2280
+ signal: options?.signal
2281
+ });
2282
+ }),
2283
+ create: perKind({
2284
+ issue: true,
2285
+ pull_request: true
2286
+ }, async (repo, input, options) => {
2287
+ if (input.kind === "discussion") throw new UnsupportedOperationError("GitLab has no discussion threads", context);
2288
+ const assignee_ids = input.assignees?.length ? await Promise.all(input.assignees.map(userId)) : void 0;
2289
+ const labels = input.labels?.join(",");
2290
+ if (input.kind === "issue") {
2291
+ const { data } = await fetcher.json(`${projectPath(repo)}/issues`, {
2292
+ method: "POST",
2293
+ json: {
2294
+ title: input.title,
2295
+ description: input.body,
2296
+ labels,
2297
+ assignee_ids
2298
+ },
2299
+ signal: options?.signal
2300
+ });
2301
+ return toThread({
2302
+ forge: FORGE,
2303
+ instance,
2304
+ repo,
2305
+ kind: "issue",
2306
+ number: String(data.iid)
2307
+ }, data);
2308
+ }
2309
+ if (!input.head || !input.base) throw new UnsupportedOperationError("Creating a merge request needs head and base branches", context);
2310
+ const { data } = await fetcher.json(`${projectPath(repo)}/merge_requests`, {
2311
+ method: "POST",
2312
+ json: {
2313
+ title: input.draft ? `Draft: ${input.title}` : input.title,
2314
+ description: input.body,
2315
+ source_branch: input.head,
2316
+ target_branch: input.base,
2317
+ labels,
2318
+ assignee_ids
2319
+ },
2320
+ signal: options?.signal
2321
+ });
2322
+ return toThread({
2323
+ forge: FORGE,
2324
+ instance,
2325
+ repo,
2326
+ kind: "pull_request",
2327
+ number: String(data.iid)
2328
+ }, data);
2329
+ }),
2330
+ update: perKind({
2331
+ issue: true,
2332
+ pull_request: true
2333
+ }, async (thread, input, options) => {
2334
+ const ref = requireIssueOrPull(thread, context, "update");
2335
+ const { data } = await fetcher.json(threadPath(ref), {
2336
+ method: "PUT",
2337
+ json: {
2338
+ title: input.title,
2339
+ description: input.body,
2340
+ state_event: input.state && STATE_EVENTS[input.state],
2341
+ labels: input.labels?.join(","),
2342
+ assignee_ids: input.assignees && await Promise.all(input.assignees.map(userId))
2343
+ },
2344
+ signal: options?.signal
2345
+ });
2346
+ return toThread(ref, data);
2347
+ }),
2348
+ addLabels: perKind({
2349
+ issue: true,
2350
+ pull_request: true
2351
+ }, async (thread, labels, options) => {
2352
+ const ref = requireIssueOrPull(thread, context, "label");
2353
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2354
+ method: "PUT",
2355
+ json: { add_labels: labels.join(",") },
2356
+ signal: options?.signal
2357
+ })).data).labels;
2358
+ }),
2359
+ removeLabels: perKind({
2360
+ issue: true,
2361
+ pull_request: true
2362
+ }, async (thread, labels, options) => {
2363
+ const ref = requireIssueOrPull(thread, context, "label");
2364
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2365
+ method: "PUT",
2366
+ json: { remove_labels: labels.join(",") },
2367
+ signal: options?.signal
2368
+ })).data).labels;
2369
+ }),
2370
+ setMilestone: perKind({
2371
+ issue: true,
2372
+ pull_request: true
2373
+ }, async (thread, milestone, options) => {
2374
+ const ref = requireIssueOrPull(thread, context, "set the milestone of");
2375
+ const { data } = await fetcher.json(threadPath(ref), {
2376
+ method: "PUT",
2377
+ json: { milestone_id: milestone === void 0 ? 0 : await milestoneId(milestone, (page) => milestonesPage(ref.repo, page, true), context, options) },
2378
+ signal: options?.signal
2379
+ });
2380
+ return toMilestone(data.milestone);
2381
+ }),
2382
+ reactionsPage: perKind(ISSUE_LIKE, async (target, listOptions = {}) => {
2383
+ const result = await fetcher.page(`${awardPath(target)}/award_emoji`, {
2384
+ query: { per_page: listOptions.perPage },
2385
+ cursor: listOptions.cursor,
2386
+ signal: listOptions.signal
2387
+ });
2388
+ return toPage(result, (raw) => {
2389
+ const reactor = toActor(instance, raw.user);
2390
+ return reactor && {
2391
+ content: reactionContent(REACTION_NAMES[raw.name] ?? raw.name),
2392
+ contentRaw: raw.name,
2393
+ actor: reactor,
2394
+ createdAt: toDate(raw.created_at),
2395
+ raw
2396
+ };
2397
+ });
2398
+ }),
2399
+ reactions: perKind({
2400
+ issue: true,
2401
+ pull_request: true
2402
+ }, {
2403
+ async react(target, reaction, options) {
2404
+ try {
2405
+ await fetcher.raw(`${awardPath(target)}/award_emoji`, {
2406
+ method: "POST",
2407
+ json: { name: AWARD_EMOJI[reaction] },
2408
+ signal: options?.signal
2409
+ });
2410
+ } catch (error) {
2411
+ if (!(error instanceof ForgeApiError && error.body.includes("has already been taken"))) throw error;
2412
+ }
2413
+ },
2414
+ async unreact(target, reaction, options) {
2415
+ const path = `${awardPath(target)}/award_emoji`;
2416
+ const { data } = await fetcher.json(path, {
2417
+ query: { per_page: 100 },
2418
+ signal: options?.signal
2419
+ });
2420
+ const login = await viewerLogin();
2421
+ const mine = data.find((award) => award.name === AWARD_EMOJI[reaction] && award.user?.username === login);
2422
+ if (mine) await fetcher.raw(`${path}/${mine.id}`, {
2423
+ method: "DELETE",
2424
+ signal: options?.signal
2425
+ });
2426
+ }
2427
+ }),
2428
+ transfer: verb(true, async (thread, repo, options) => {
2429
+ const ref = requireIssueOrPull(thread, context, "transfer");
2430
+ if (ref.kind !== "issue") throw new UnsupportedOperationError("GitLab moves issues only", context);
2431
+ const { data: target } = await fetcher.json(`/projects/${projectId(repo)}`, { signal: options?.signal });
2432
+ const { data } = await fetcher.json(`${threadPath(ref)}/move`, {
2433
+ method: "POST",
2434
+ json: { to_project_id: target.id },
2435
+ signal: options?.signal
2436
+ });
2437
+ return {
2438
+ forge: FORGE,
2439
+ instance,
2440
+ repo,
2441
+ kind: "issue",
2442
+ number: String(data.iid),
2443
+ externalId: data.id === void 0 ? void 0 : String(data.id)
2444
+ };
2445
+ }),
2446
+ markDuplicate: verb("emulated", async (thread, canonical, options) => {
2447
+ const ref = requireIssueOrPull(thread, context, "mark duplicate");
2448
+ const reference = canonical.repo.owner === ref.repo.owner && canonical.repo.name === ref.repo.name ? `#${canonical.number}` : `${canonical.repo.owner}/${canonical.repo.name}#${canonical.number}`;
2449
+ await fetcher.raw(`${threadPath(ref)}/notes`, {
2450
+ method: "POST",
2451
+ json: { body: `/duplicate ${reference}` },
2452
+ signal: options?.signal
2453
+ });
2454
+ }),
2455
+ setLabels: perKind({
2456
+ issue: true,
2457
+ pull_request: true
2458
+ }, async (thread, labels, options) => {
2459
+ const ref = requireIssueOrPull(thread, context, "label");
2460
+ return toThread(ref, (await fetcher.json(threadPath(ref), {
2461
+ method: "PUT",
2462
+ json: { labels: labels.join(",") },
2463
+ signal: options?.signal
2464
+ })).data).labels;
2465
+ }),
2466
+ setAssignees: perKind({
2467
+ issue: true,
2468
+ pull_request: true
2469
+ }, async (thread, assignees, options) => {
2470
+ const ref = requireIssueOrPull(thread, context, "assign");
2471
+ const { data } = await fetcher.json(threadPath(ref), {
2472
+ method: "PUT",
2473
+ json: { assignee_ids: await Promise.all(assignees.map(userId)) },
2474
+ signal: options?.signal
2475
+ });
2476
+ return (data.assignees ?? []).flatMap((user) => toActor(instance, user) ?? []);
2477
+ }),
2478
+ requestReview: perKind({ pull_request: true }, async (thread, reviewers, options) => {
2479
+ const ref = requireThread(thread, context);
2480
+ if (ref.kind !== "pull_request") throw new UnsupportedOperationError("Only merge requests have reviewers", context);
2481
+ const { data } = await fetcher.json(threadPath(ref), { signal: options?.signal });
2482
+ const ids = /* @__PURE__ */ new Set([...(data.reviewers ?? []).map((user) => user.id), ...await Promise.all(reviewers.map(userId))]);
2483
+ await fetcher.raw(threadPath(ref), {
2484
+ method: "PUT",
2485
+ json: { reviewer_ids: [...ids] },
2486
+ signal: options?.signal
2487
+ });
2488
+ }),
2489
+ close: perKind({
2490
+ issue: true,
2491
+ pull_request: true
2492
+ }, (ref, options) => setState(ref, "close", options)),
2493
+ reopen: perKind({
2494
+ issue: true,
2495
+ pull_request: true
2496
+ }, (ref, options) => setState(ref, "reopen", options)),
2497
+ locking: perKind({
2498
+ issue: true,
2499
+ pull_request: true
2500
+ }, {
2501
+ lock: (thread, options) => setLocked(thread, true, options),
2502
+ unlock: (thread, options) => setLocked(thread, false, options)
2503
+ }),
2504
+ merge: verb(true, merge),
2505
+ updateBranch: verb(true, updateBranch),
2506
+ subscriptions: perKind(ISSUE_LIKE, {
2507
+ subscription: async (thread, options) => {
2508
+ const ref = requireIssueOrPull(thread, context, "read the subscription of");
2509
+ return (await fetcher.json(threadPath(ref), { signal: options?.signal })).data.subscribed ? "subscribed" : "none";
2510
+ },
2511
+ subscribe: (thread, options) => setSubscribed(thread, true, options),
2512
+ unsubscribe: (thread, options) => setSubscribed(thread, false, options)
2513
+ })
2514
+ }
2515
+ };
2516
+ }
2517
+ });
2518
+ /** GitLab tokens carry coarse scopes; `api` covers writes and `read_api` reads. */
2519
+ function gitlabScopesFor(verb) {
2520
+ const [group = "", name = ""] = verb.split(".");
2521
+ if (group === "webhooks") return name === "verify" || name === "ingest" ? {} : {
2522
+ token: ["api"],
2523
+ note: "Maintainer on the project, or Owner on the group"
2524
+ };
2525
+ if (group === "orgs") return {
2526
+ token: ["read_api"],
2527
+ note: "A member of the group, for a private group"
2528
+ };
2529
+ return { token: [WRITE_VERBS.has(verb) ? "api" : "read_api"] };
2530
+ }
2531
+ //#endregion
2532
+ export { toRepoRef as a, gitlab, toLabel as i, approvalId as n, toState as o, toActor as r, toThreadKind as s, FORGE as t };