@gitkraken/core-gitlens 0.63.0 → 0.64.1

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/dist/git/watching/provider.d.ts +1 -1
  3. package/dist/git/watching/watchService.js +6 -1
  4. package/dist/git/watching/watchService.js.map +1 -1
  5. package/dist/git-cli/cliGitProvider.js +3 -3
  6. package/dist/git-cli/cliGitProvider.js.map +1 -1
  7. package/dist/git-cli/providers/config.js +2 -2
  8. package/dist/git-cli/providers/pausedOperations.js +2 -2
  9. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  10. package/dist/git-cli/providers/staging.js +1 -1
  11. package/dist/ipc/discovery.js +1 -1
  12. package/dist/plus/agents/providers/claudeCodeTranscript.js +6 -6
  13. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -1
  14. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -1
  15. package/dist/plus/integrations/extensionManager.d.ts +6 -0
  16. package/dist/plus/integrations/extensionManager.js +10 -0
  17. package/dist/plus/integrations/extensionManager.js.map +1 -0
  18. package/dist/plus/integrations/index.d.ts +5 -63
  19. package/dist/plus/integrations/index.js +4 -53
  20. package/dist/plus/integrations/index.js.map +1 -1
  21. package/dist/plus/integrations/integrationService.d.ts +14 -2
  22. package/dist/plus/integrations/integrationService.js +48 -12
  23. package/dist/plus/integrations/integrationService.js.map +1 -1
  24. package/dist/plus/integrations/manager.d.ts +10 -0
  25. package/dist/plus/integrations/managerContext.d.ts +69 -0
  26. package/dist/plus/integrations/managerContext.js +59 -0
  27. package/dist/plus/integrations/managerContext.js.map +1 -0
  28. package/dist/plus/integrations/models/gitlabMergeRequestWrites.d.ts +167 -0
  29. package/dist/plus/integrations/models/gitlabMergeRequestWrites.js +0 -0
  30. package/dist/plus/integrations/providers/azure/azure.js +1 -1
  31. package/dist/plus/integrations/providers/github.js +1 -1
  32. package/dist/plus/integrations/providers/gitlab/gitlab.d.ts +2 -2
  33. package/dist/plus/integrations/providers/gitlab/gitlab.js +3 -3
  34. package/dist/plus/integrations/providers/gitlab/gitlab.js.map +1 -1
  35. package/dist/plus/integrations/providers/gitlab/issueWrites.d.ts +4 -13
  36. package/dist/plus/integrations/providers/gitlab/issueWrites.js +33 -136
  37. package/dist/plus/integrations/providers/gitlab/issueWrites.js.map +1 -1
  38. package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.d.ts +30 -0
  39. package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.js +569 -0
  40. package/dist/plus/integrations/providers/gitlab/mergeRequestWrites.js.map +1 -0
  41. package/dist/plus/integrations/providers/gitlab/writeErrors.d.ts +12 -0
  42. package/dist/plus/integrations/providers/gitlab/writeErrors.js +101 -0
  43. package/dist/plus/integrations/providers/gitlab/writeErrors.js.map +1 -0
  44. package/dist/plus/integrations/providers/gitlab/writeTransport.d.ts +47 -0
  45. package/dist/plus/integrations/providers/gitlab/writeTransport.js +135 -0
  46. package/dist/plus/integrations/providers/gitlab/writeTransport.js.map +1 -0
  47. package/dist/plus/integrations/providers/gitlab.d.ts +6 -1
  48. package/dist/plus/integrations/providers/gitlab.js +9 -1
  49. package/dist/plus/integrations/providers/gitlab.js.map +1 -1
  50. package/dist/plus/integrations/reads/sweeps.js +1 -1
  51. package/dist/utils/env/node/exec.js +2 -2
  52. package/docs/integrations.md +77 -0
  53. package/package.json +1 -1
  54. package/dist/plus/integrations/providers/gitlab/issueWriteErrors.d.ts +0 -11
  55. package/dist/plus/integrations/providers/gitlab/issueWriteErrors.js +0 -73
  56. package/dist/plus/integrations/providers/gitlab/issueWriteErrors.js.map +0 -1
@@ -0,0 +1,569 @@
1
+ import { isGitLabDecimalId } from "../../models/gitlabIssueWrites.js";
2
+ import { isGitBranchName } from "../utils/writeInputs.js";
3
+ import { GitLabWriteError, gitLabWriteFailure, validateGitLabWriteFields } from "./writeErrors.js";
4
+ import { isGitLabProjectRef, isGitLabUrl, restId } from "./writeTransport.js";
5
+ import * as l10n from "@vscode/l10n";
6
+ //#region ../plus/integrations/src/providers/gitlab/mergeRequestWrites.ts
7
+ const mergeRequestGidPrefix = "gid://gitlab/MergeRequest/";
8
+ const ownerAccessLevel = 50;
9
+ const shaPattern = /^[\da-f]{40}(?:[\da-f]{24})?$/i;
10
+ const draftTitlePattern = /^\s*(?:\[draft\]|\(draft\)|draft:)/i;
11
+ const timestampPattern = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
12
+ const mergeStatusPattern = /^[a-z][a-z_]{0,63}$/;
13
+ const mergeMethods = [
14
+ "merge",
15
+ "rebase_merge",
16
+ "ff"
17
+ ];
18
+ const mergeExecutions = ["merge", "train"];
19
+ const states = [
20
+ "opened",
21
+ "closed",
22
+ "merged",
23
+ "locked"
24
+ ];
25
+ const mergeBlockers = /* @__PURE__ */ new Map([
26
+ ["conflict", "conflicts"],
27
+ ["ci_must_pass", "pipeline"],
28
+ ["ci_still_running", "pipeline"],
29
+ ["security_policy_pipeline_check", "pipeline"],
30
+ ["not_approved", "approvals"],
31
+ ["approvals_syncing", "approvals"],
32
+ ["requested_changes", "approvals"],
33
+ ["discussions_not_resolved", "discussions"],
34
+ ["draft_status", "draft"],
35
+ ["need_rebase", "rebase"],
36
+ ["status_checks_must_pass", "status-checks"],
37
+ ["unchecked", "checking"],
38
+ ["checking", "checking"],
39
+ ["preparing", "checking"]
40
+ ]);
41
+ const createFields = [{
42
+ id: "title",
43
+ required: true
44
+ }, {
45
+ id: "description",
46
+ required: false
47
+ }];
48
+ const editFields = [{
49
+ id: "title",
50
+ required: false
51
+ }, {
52
+ id: "description",
53
+ required: false
54
+ }];
55
+ const createPermissionsQuery = `query MergeRequestCreatePermissions($target: ID!, $source: ID!) {
56
+ target: project(fullPath: $target) { id userPermissions { createMergeRequestIn } }
57
+ source: project(fullPath: $source) { id userPermissions { createMergeRequestFrom } }
58
+ }`;
59
+ const mergeRequestPermissionsQuery = `query MergeRequestWritePermissions($path: ID!, $iid: String!) {
60
+ project(fullPath: $path) {
61
+ id
62
+ maxAccessLevel { integerValue }
63
+ mergeRequest(iid: $iid) {
64
+ id
65
+ autoMergeEnabled
66
+ availableAutoMergeStrategies
67
+ squashOnMerge
68
+ squashReadOnly
69
+ userPermissions { updateMergeRequest canMerge }
70
+ }
71
+ }
72
+ }`;
73
+ function isSha(value) {
74
+ return typeof value === "string" && shaPattern.test(value);
75
+ }
76
+ function sameSha(actual, expected) {
77
+ return actual?.toLowerCase() === expected.toLowerCase();
78
+ }
79
+ function isMergeMethod(value) {
80
+ return mergeMethods.includes(value);
81
+ }
82
+ function isTimestamp(value) {
83
+ return typeof value === "string" && timestampPattern.test(value) && !Number.isNaN(Date.parse(value));
84
+ }
85
+ function deleteFence(updatedAt) {
86
+ const match = updatedAt == null ? void 0 : timestampPattern.exec(updatedAt);
87
+ const fraction = match?.[2];
88
+ return match == null || fraction == null || fraction.length < 3 ? void 0 : `${match[1]}.${fraction.padEnd(6, "9")}${match[3]}`;
89
+ }
90
+ function mergeStatusOf(raw) {
91
+ const status = raw.detailed_merge_status;
92
+ return typeof status === "string" && mergeStatusPattern.test(status) ? status : void 0;
93
+ }
94
+ function isApprovedMerge(mergeRequest, input) {
95
+ return mergeRequest.sourceProjectId === input.expectedSourceProjectId && mergeRequest.sourceBranch === input.expectedSourceBranch && mergeRequest.targetBranch === input.expectedTargetBranch && sameSha(mergeRequest.sourceSha, input.expectedSourceSha);
96
+ }
97
+ function isApprovedTrainCar(car, project, input) {
98
+ const queued = car?.merge_request;
99
+ return restId(queued?.id) === input.expectedMergeRequestId && restId(queued?.iid) === input.iid && restId(queued?.project_id) === project.id && queued?.state === "opened" && car?.target_branch === input.expectedTargetBranch;
100
+ }
101
+ function mergeRequestReceipt(raw, project, iid, expectedId) {
102
+ const id = restId(raw?.id);
103
+ const actualIid = restId(raw?.iid);
104
+ const targetProjectId = restId(raw?.target_project_id);
105
+ const state = raw?.state;
106
+ if (id == null || actualIid == null || targetProjectId == null || !isGitLabUrl(raw.web_url) || typeof raw.title !== "string" || raw.description !== null && typeof raw.description !== "string" || !states.includes(state) || typeof raw.draft !== "boolean" || typeof raw.source_branch !== "string" || typeof raw.target_branch !== "string" || raw.sha != null && !isSha(raw.sha)) throw new GitLabWriteError("unknown");
107
+ if (targetProjectId !== project.id || restId(raw.project_id) !== project.id || iid != null && iid !== actualIid || expectedId != null && expectedId !== id) throw new GitLabWriteError("conflict");
108
+ const sourceProjectId = restId(raw.source_project_id);
109
+ return {
110
+ id,
111
+ iid: actualIid,
112
+ url: raw.web_url,
113
+ title: raw.title,
114
+ description: raw.description ?? "",
115
+ state,
116
+ draft: raw.draft,
117
+ targetProjectId,
118
+ ...sourceProjectId != null && { sourceProjectId },
119
+ sourceBranch: raw.source_branch,
120
+ targetBranch: raw.target_branch,
121
+ ...raw.sha != null && { sourceSha: raw.sha },
122
+ ...isTimestamp(raw.updated_at) && { updatedAt: raw.updated_at }
123
+ };
124
+ }
125
+ function allowed(value) {
126
+ return value ? { allowed: true } : {
127
+ allowed: false,
128
+ reason: "forbidden"
129
+ };
130
+ }
131
+ function transition(permission, available) {
132
+ return permission.allowed && !available ? {
133
+ allowed: false,
134
+ reason: "transition-unavailable"
135
+ } : permission;
136
+ }
137
+ function unavailableMerge(reason, mergeStatus, blocker) {
138
+ return {
139
+ kind: "unavailable",
140
+ reason,
141
+ ...blocker != null && { blocker },
142
+ ...mergeStatus != null && { mergeStatus }
143
+ };
144
+ }
145
+ function blockedMerge(mergeStatus, fallback) {
146
+ return unavailableMerge("policy-blocked", mergeStatus, mergeBlockers.get(mergeStatus ?? "") ?? fallback);
147
+ }
148
+ function mergeFailure({ kind: _kind, ...refusal }, dispatched) {
149
+ return {
150
+ ok: false,
151
+ ...!dispatched && { mutationDispatched: false },
152
+ ...refusal
153
+ };
154
+ }
155
+ function isValidMerge(input) {
156
+ return typeof input.squash === "boolean" && mergeExecutions.includes(input.expectedExecution) && isMergeMethod(input.expectedMergeMethod) && typeof input.expectedRemovesSourceBranch === "boolean" && isGitLabDecimalId(input.expectedSourceProjectId) && isGitBranchName(input.expectedSourceBranch) && isGitBranchName(input.expectedTargetBranch) && isSha(input.expectedSourceSha) && isSha(input.expectedTargetSha);
157
+ }
158
+ function validateFields(action, title, description) {
159
+ return validateGitLabWriteFields(action, title, description, l10n.t("GitLab quick actions are unavailable in merge request descriptions."));
160
+ }
161
+ function draftTitleRefusal() {
162
+ return gitLabWriteFailure("invalid-input", { title: l10n.t("A draft marker in the title would change the draft status.") });
163
+ }
164
+ function movedProject(input, project) {
165
+ return input.expectedProjectPath !== void 0 && input.expectedProjectPath.toLowerCase() !== project.fullPath.toLowerCase() ? gitLabWriteFailure("conflict") : void 0;
166
+ }
167
+ var GitLabMergeRequestWriter = class {
168
+ transport;
169
+ constructor(transport) {
170
+ this.transport = transport;
171
+ }
172
+ async getCreateOptions(options) {
173
+ const { context, sourceProject, defaultBranch, capability } = await this.readCreateTarget(options.project, options.sourceProject);
174
+ return {
175
+ ...context,
176
+ ok: true,
177
+ sourceProject,
178
+ ...defaultBranch != null && { defaultBranch },
179
+ fields: capability.allowed ? createFields : [],
180
+ draft: true,
181
+ createCapability: capability
182
+ };
183
+ }
184
+ async getMergeRequestOptions(options) {
185
+ const { context, mergeRequest, capabilities } = await this.readMergeRequest(options);
186
+ return {
187
+ ...context,
188
+ ok: true,
189
+ mergeRequest,
190
+ fields: capabilities.edit.allowed ? editFields : [],
191
+ capabilities
192
+ };
193
+ }
194
+ async resolveTarget(options) {
195
+ const { intent } = options;
196
+ if (intent !== void 0 && intent !== "merge" && intent !== "delete") return gitLabWriteFailure("invalid-input");
197
+ const { context, mergeRequest, capabilities } = await this.readMergeRequest(options);
198
+ const target = {
199
+ ...context,
200
+ ok: true,
201
+ mergeRequest
202
+ };
203
+ if (intent === "delete") return capabilities.delete.allowed ? target : gitLabWriteFailure(capabilities.delete.reason);
204
+ if (intent === "merge") {
205
+ const { merge } = capabilities;
206
+ return merge.kind === "unavailable" ? mergeFailure(merge, false) : {
207
+ ...target,
208
+ merge
209
+ };
210
+ }
211
+ return target;
212
+ }
213
+ async write(input) {
214
+ if (!isGitLabDecimalId(input.projectId) || !isGitLabDecimalId(input.expectedAccountId) || input.expectedProjectPath !== void 0 && typeof input.expectedProjectPath !== "string") return gitLabWriteFailure("invalid-input");
215
+ if (input.action === "create") return this.create(input);
216
+ const { action } = input;
217
+ if (action !== "edit" && action !== "close" && action !== "reopen" && action !== "merge") return gitLabWriteFailure("invalid-input");
218
+ if (!isGitLabDecimalId(input.expectedMergeRequestId)) return gitLabWriteFailure("invalid-input");
219
+ return this.writeExisting(input);
220
+ }
221
+ async delete(input) {
222
+ if (!isGitLabDecimalId(input.projectId) || !isGitLabDecimalId(input.expectedAccountId) || !isGitLabDecimalId(input.expectedMergeRequestId) || input.expectedProjectPath !== void 0 && typeof input.expectedProjectPath !== "string" || input.expectedState !== void 0 && !states.includes(input.expectedState)) return gitLabWriteFailure("invalid-input");
223
+ const { context, mergeRequest, capabilities } = await this.readMergeRequest({
224
+ ...input,
225
+ project: input.projectId
226
+ });
227
+ const moved = movedProject(input, context.project);
228
+ if (moved != null) return moved;
229
+ if (input.expectedState !== void 0 && input.expectedState !== mergeRequest.state) return gitLabWriteFailure("conflict");
230
+ if (!capabilities.delete.allowed) return gitLabWriteFailure(capabilities.delete.reason);
231
+ const unmodifiedSince = deleteFence(mergeRequest.updatedAt);
232
+ if (unmodifiedSince == null) return gitLabWriteFailure("unknown");
233
+ return this.transport.mutate("DELETE", this.mergeRequestPath(context.project, mergeRequest), void 0, 204, () => ({
234
+ ...context,
235
+ ok: true,
236
+ status: "deleted",
237
+ mergeRequest
238
+ }), void 0, { "If-Unmodified-Since": unmodifiedSince });
239
+ }
240
+ async create(input) {
241
+ const { title, description, sourceBranch, targetBranch, sourceProjectId, draft } = input;
242
+ const invalid = validateFields("create", title, description);
243
+ if (invalid != null) return invalid;
244
+ if (!isGitBranchName(sourceBranch) || !isGitBranchName(targetBranch) || sourceProjectId !== void 0 && !isGitLabDecimalId(sourceProjectId) || draft !== void 0 && typeof draft !== "boolean") return gitLabWriteFailure("invalid-input");
245
+ const marked = draftTitlePattern.test(title);
246
+ if (marked && draft !== true) return draftTitleRefusal();
247
+ const { context, sourceProject, capability } = await this.readCreateTarget(input.projectId, sourceProjectId);
248
+ const { project } = context;
249
+ const moved = movedProject(input, project);
250
+ if (moved != null) return moved;
251
+ if (!capability.allowed) return gitLabWriteFailure(capability.reason);
252
+ if (sourceProject.id === project.id && sourceBranch === targetBranch) return gitLabWriteFailure("invalid-input");
253
+ if (await this.readBranchTip(sourceProject, sourceBranch) == null) return gitLabWriteFailure("not-found", { sourceBranch: l10n.t("Branch '{0}' not found", sourceBranch) });
254
+ if (await this.readBranchTip(project, targetBranch) == null) return gitLabWriteFailure("not-found", { targetBranch: l10n.t("Branch '{0}' not found", targetBranch) });
255
+ const existing = await this.findOpenMergeRequest(project, sourceProject, sourceBranch, targetBranch);
256
+ if (existing != null) return {
257
+ ...gitLabWriteFailure("conflict"),
258
+ mergeRequest: existing
259
+ };
260
+ return this.transport.mutate("POST", `/api/v4/projects/${sourceProject.id}/merge_requests`, {
261
+ source_branch: sourceBranch,
262
+ target_branch: targetBranch,
263
+ target_project_id: Number(project.id),
264
+ title: draft === true && !marked ? `Draft: ${title}` : title,
265
+ description
266
+ }, 201, async (response) => {
267
+ const created = mergeRequestReceipt(await response.json(), project);
268
+ return created.state === "opened" && created.sourceProjectId === sourceProject.id && created.sourceBranch === sourceBranch && created.targetBranch === targetBranch ? {
269
+ ...context,
270
+ ok: true,
271
+ status: "created",
272
+ mergeRequest: created
273
+ } : {
274
+ ok: false,
275
+ reason: "unknown",
276
+ applied: "maybe"
277
+ };
278
+ });
279
+ }
280
+ async writeExisting(input) {
281
+ const { action } = input;
282
+ if (action === "edit") {
283
+ const invalid = validateFields(action, input.title, input.description);
284
+ if (invalid != null) return invalid;
285
+ } else if (action === "merge" && !isValidMerge(input)) return gitLabWriteFailure("invalid-input");
286
+ const read = await this.readMergeRequest({
287
+ ...input,
288
+ project: input.projectId
289
+ });
290
+ const { context, mergeRequest, capabilities, lockVersion } = read;
291
+ const moved = movedProject(input, context.project);
292
+ if (moved != null) return moved;
293
+ if (action === "merge") return this.merge(input, read);
294
+ const capability = capabilities[action];
295
+ if (!capability.allowed) return gitLabWriteFailure(capability.reason);
296
+ let fields = { state_event: action };
297
+ if (action === "edit") {
298
+ const { title, description } = input;
299
+ const marked = title !== void 0 && draftTitlePattern.test(title);
300
+ if (marked && !mergeRequest.draft) return draftTitleRefusal();
301
+ fields = {
302
+ title: title !== void 0 && mergeRequest.draft && !marked ? `Draft: ${title}` : title,
303
+ description,
304
+ ...lockVersion != null && { lock_version: lockVersion }
305
+ };
306
+ }
307
+ const { project } = context;
308
+ return this.transport.mutate("PUT", this.mergeRequestPath(project, mergeRequest), fields, 200, async (response) => {
309
+ const updated = mergeRequestReceipt(await response.json(), project, mergeRequest.iid, mergeRequest.id);
310
+ if (action === "edit") return {
311
+ ...context,
312
+ ok: true,
313
+ status: "updated",
314
+ mergeRequest: updated
315
+ };
316
+ const state = action === "close" ? "closed" : "opened";
317
+ return updated.state === state ? {
318
+ ...context,
319
+ ok: true,
320
+ status: action === "close" ? "closed" : "reopened",
321
+ mergeRequest: updated
322
+ } : {
323
+ ok: false,
324
+ reason: "unknown",
325
+ applied: "maybe"
326
+ };
327
+ });
328
+ }
329
+ merge(input, { context, mergeRequest, capabilities }) {
330
+ const { merge } = capabilities;
331
+ if (merge.kind === "unavailable") return mergeFailure(merge, false);
332
+ if (mergeRequest.sourceProjectId !== input.expectedSourceProjectId || mergeRequest.sourceBranch !== input.expectedSourceBranch || !sameSha(mergeRequest.sourceSha, input.expectedSourceSha)) return {
333
+ ok: false,
334
+ reason: "source-changed",
335
+ mutationDispatched: false
336
+ };
337
+ if (mergeRequest.targetBranch !== input.expectedTargetBranch || !sameSha(mergeRequest.targetSha, input.expectedTargetSha)) return {
338
+ ok: false,
339
+ reason: "target-changed",
340
+ mutationDispatched: false
341
+ };
342
+ if (merge.execution !== input.expectedExecution || merge.method !== input.expectedMergeMethod || merge.removesSourceBranch !== input.expectedRemovesSourceBranch || merge.squash === (input.squash ? "unavailable" : "required")) return gitLabWriteFailure("conflict");
343
+ const { project } = context;
344
+ const body = {
345
+ sha: mergeRequest.sourceSha,
346
+ ...input.squash && { squash: true }
347
+ };
348
+ const refusal = (response) => this.toMergeRefusal(response, merge.execution, context, input);
349
+ if (merge.execution === "train") {
350
+ const trainPath = `/api/v4/projects/${project.id}/merge_trains/merge_requests/${mergeRequest.iid}`;
351
+ return this.transport.mutate("POST", trainPath, {
352
+ ...body,
353
+ auto_merge: false
354
+ }, 201, async (response) => {
355
+ const cars = await response.json();
356
+ return isApprovedTrainCar((Array.isArray(cars) ? cars : []).find((c) => restId(c?.merge_request?.id) === mergeRequest.id) ?? await this.transport.read(trainPath), project, input) ? {
357
+ ...context,
358
+ ok: true,
359
+ status: "queued",
360
+ mergeRequest
361
+ } : {
362
+ ok: false,
363
+ reason: "unknown",
364
+ applied: "maybe"
365
+ };
366
+ }, refusal);
367
+ }
368
+ return this.transport.mutate("PUT", `${this.mergeRequestPath(project, mergeRequest)}/merge`, body, 200, async (response) => {
369
+ const merged = mergeRequestReceipt(await response.json(), project, mergeRequest.iid, mergeRequest.id);
370
+ return merged.state === "merged" && isApprovedMerge(merged, input) ? {
371
+ ...context,
372
+ ok: true,
373
+ status: "merged",
374
+ mergeRequest: merged
375
+ } : {
376
+ ok: false,
377
+ reason: "unknown",
378
+ applied: "maybe"
379
+ };
380
+ }, refusal);
381
+ }
382
+ async toMergeRefusal(response, execution, context, input) {
383
+ const { status } = response;
384
+ if (status === 409) return {
385
+ ok: false,
386
+ reason: execution === "train" ? "conflict" : "source-changed"
387
+ };
388
+ if (status === 401) return /\binvalid_token\b/i.test(response.headers.get("www-authenticate") ?? "") ? void 0 : {
389
+ ok: false,
390
+ reason: "forbidden"
391
+ };
392
+ const refused = status === (execution === "train" ? 400 : 405);
393
+ if (!refused && (execution === "train" || status !== 422)) return void 0;
394
+ let current;
395
+ let mergeStatus;
396
+ try {
397
+ const raw = await this.transport.read(this.mergeRequestPath(context.project, input));
398
+ current = mergeRequestReceipt(raw, context.project, input.iid, input.expectedMergeRequestId);
399
+ mergeStatus = mergeStatusOf(raw);
400
+ } catch {
401
+ current = void 0;
402
+ }
403
+ if (!refused) {
404
+ if (current == null || !isApprovedMerge(current, input)) return {
405
+ ok: false,
406
+ reason: "unknown",
407
+ applied: "maybe"
408
+ };
409
+ if (current.state === "merged") return {
410
+ ...context,
411
+ ok: true,
412
+ status: "merged",
413
+ mergeRequest: current
414
+ };
415
+ if (current.state !== "opened") return {
416
+ ok: false,
417
+ reason: "unknown",
418
+ applied: "maybe"
419
+ };
420
+ }
421
+ return mergeFailure(blockedMerge(mergeStatus, "other"), true);
422
+ }
423
+ async readCreateTarget(project, sourceProject) {
424
+ if (!isGitLabProjectRef(project) || sourceProject !== void 0 && !isGitLabProjectRef(sourceProject)) throw new GitLabWriteError("invalid-input");
425
+ const account = await this.transport.readAccount();
426
+ const target = await this.transport.readProject(project);
427
+ const source = sourceProject === void 0 ? target : await this.transport.readProject(sourceProject);
428
+ let capability = this.getWriteRefusal(account, target.raw);
429
+ if (capability == null) {
430
+ const data = await this.transport.readGraphQL(createPermissionsQuery, {
431
+ target: target.project.fullPath,
432
+ source: source.project.fullPath
433
+ }, {
434
+ target: target.project,
435
+ source: source.project
436
+ });
437
+ const into = data.target?.userPermissions?.createMergeRequestIn;
438
+ const from = data.source?.userPermissions?.createMergeRequestFrom;
439
+ if (typeof into !== "boolean" || typeof from !== "boolean") throw new GitLabWriteError("unknown");
440
+ capability = allowed(into && from);
441
+ }
442
+ return {
443
+ context: this.transport.context(account, target.project),
444
+ sourceProject: source.project,
445
+ defaultBranch: target.raw.default_branch || void 0,
446
+ capability
447
+ };
448
+ }
449
+ async readMergeRequest(options) {
450
+ const { project, iid, expectedMergeRequestId } = options;
451
+ if (!isGitLabProjectRef(project) || !isGitLabDecimalId(iid) || expectedMergeRequestId !== void 0 && !isGitLabDecimalId(expectedMergeRequestId)) throw new GitLabWriteError("invalid-input");
452
+ const account = await this.transport.readAccount();
453
+ const target = await this.transport.readProject(project);
454
+ const context = this.transport.context(account, target.project);
455
+ const raw = await this.transport.read(this.mergeRequestPath(target.project, { iid }));
456
+ let mergeRequest = mergeRequestReceipt(raw, target.project, iid, expectedMergeRequestId);
457
+ if (mergeRequest.state === "opened") {
458
+ const targetSha = await this.readBranchTip(target.project, mergeRequest.targetBranch);
459
+ if (targetSha != null) mergeRequest = {
460
+ ...mergeRequest,
461
+ targetSha
462
+ };
463
+ }
464
+ const lockVersion = raw.lock_version;
465
+ return {
466
+ context,
467
+ mergeRequest,
468
+ capabilities: await this.getCapabilities(account, target, raw, mergeRequest),
469
+ lockVersion: typeof lockVersion === "number" && Number.isSafeInteger(lockVersion) && lockVersion >= 0 ? lockVersion : void 0
470
+ };
471
+ }
472
+ getWriteRefusal(account, project) {
473
+ if (!account.canWrite) return {
474
+ allowed: false,
475
+ reason: "insufficient-scope"
476
+ };
477
+ if (project.archived || project.marked_for_deletion_on || project.merge_requests_enabled === false || project.merge_requests_access_level === "disabled") return {
478
+ allowed: false,
479
+ reason: "provider-policy"
480
+ };
481
+ }
482
+ async getCapabilities(account, target, raw, mergeRequest) {
483
+ const mergeStatus = mergeStatusOf(raw);
484
+ const unavailable = this.getWriteRefusal(account, target.raw);
485
+ if (unavailable != null) return {
486
+ edit: unavailable,
487
+ close: unavailable,
488
+ reopen: unavailable,
489
+ delete: unavailable,
490
+ merge: unavailableMerge(unavailable.reason, mergeStatus)
491
+ };
492
+ const { project } = await this.transport.readGraphQL(mergeRequestPermissionsQuery, {
493
+ path: target.project.fullPath,
494
+ iid: mergeRequest.iid
495
+ }, { project: target.project });
496
+ const permissions = project?.mergeRequest;
497
+ if (permissions?.id !== `${mergeRequestGidPrefix}${mergeRequest.id}`) throw new GitLabWriteError("conflict");
498
+ const { updateMergeRequest, canMerge } = permissions.userPermissions ?? {};
499
+ const { autoMergeEnabled, availableAutoMergeStrategies: strategies, squashOnMerge, squashReadOnly } = permissions;
500
+ const accessLevel = project?.maxAccessLevel?.integerValue;
501
+ if (typeof updateMergeRequest !== "boolean" || typeof canMerge !== "boolean" || typeof autoMergeEnabled !== "boolean" || typeof squashOnMerge !== "boolean" || typeof squashReadOnly !== "boolean" || typeof accessLevel !== "number" || strategies != null && !Array.isArray(strategies)) throw new GitLabWriteError("unknown");
502
+ const { state } = mergeRequest;
503
+ const update = allowed(updateMergeRequest);
504
+ return {
505
+ edit: transition(update, state === "opened" || state === "closed"),
506
+ close: transition(update, state === "opened"),
507
+ reopen: transition(update, state === "closed"),
508
+ delete: allowed(accessLevel >= ownerAccessLevel),
509
+ merge: this.getMergeCapability(target.raw, raw, mergeRequest, {
510
+ canMerge,
511
+ autoMergeEnabled,
512
+ strategies: strategies ?? [],
513
+ squash: squashOnMerge ? "required" : squashReadOnly ? "unavailable" : "optional"
514
+ })
515
+ };
516
+ }
517
+ getMergeCapability(project, raw, mergeRequest, policy) {
518
+ const mergeStatus = mergeStatusOf(raw);
519
+ if (mergeRequest.state !== "opened") return unavailableMerge("transition-unavailable", mergeStatus);
520
+ if (!policy.canMerge) return unavailableMerge("forbidden", mergeStatus);
521
+ const method = project.merge_method;
522
+ if (!isMergeMethod(method)) return unavailableMerge("unsupported", mergeStatus);
523
+ if (policy.autoMergeEnabled) return unavailableMerge("policy-blocked", mergeStatus, "auto-merge");
524
+ if (mergeRequest.sourceSha == null) return unavailableMerge("policy-blocked", mergeStatus, "checking");
525
+ if (mergeRequest.targetSha == null) return blockedMerge(mergeStatus, "other");
526
+ const hasTrain = project.merge_trains_enabled === true || policy.strategies.includes("merge_train") || policy.strategies.includes("add_to_merge_train_when_checks_pass");
527
+ if (hasTrain) {
528
+ if (!policy.strategies.includes("merge_train")) return blockedMerge(mergeStatus, "merge-train");
529
+ } else if (mergeStatus !== "mergeable") return blockedMerge(mergeStatus, "other");
530
+ return {
531
+ kind: "available",
532
+ execution: hasTrain ? "train" : "merge",
533
+ method,
534
+ squash: policy.squash,
535
+ removesSourceBranch: raw.should_remove_source_branch === true || raw.force_remove_source_branch === true
536
+ };
537
+ }
538
+ async findOpenMergeRequest(project, sourceProject, sourceBranch, targetBranch) {
539
+ const query = new URLSearchParams({
540
+ state: "opened",
541
+ source_branch: sourceBranch,
542
+ target_branch: targetBranch,
543
+ per_page: "100"
544
+ });
545
+ const found = await this.transport.read(`/api/v4/projects/${project.id}/merge_requests?${query.toString()}`);
546
+ if (!Array.isArray(found)) throw new GitLabWriteError("unknown");
547
+ const existing = found.find((raw) => restId(raw?.source_project_id) === sourceProject.id && raw.source_branch === sourceBranch && raw.target_branch === targetBranch && raw.state === "opened");
548
+ return existing && mergeRequestReceipt(existing, project);
549
+ }
550
+ async readBranchTip(project, branch) {
551
+ let raw;
552
+ try {
553
+ raw = await this.transport.read(`/api/v4/projects/${project.id}/repository/branches/${encodeURIComponent(branch)}`);
554
+ } catch (ex) {
555
+ if (ex instanceof GitLabWriteError && ex.reason === "not-found") return void 0;
556
+ throw ex;
557
+ }
558
+ const sha = raw?.commit?.id;
559
+ if (raw?.name !== branch || !isSha(sha)) throw new GitLabWriteError("unknown");
560
+ return sha;
561
+ }
562
+ mergeRequestPath(project, mergeRequest) {
563
+ return `/api/v4/projects/${project.id}/merge_requests/${mergeRequest.iid}`;
564
+ }
565
+ };
566
+ //#endregion
567
+ export { GitLabMergeRequestWriter };
568
+
569
+ //# sourceMappingURL=mergeRequestWrites.js.map