@leitwerk-dev/gitlab 0.3.1 → 0.4.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.
Files changed (56) hide show
  1. package/README.md +154 -1
  2. package/dist/capability.d.ts +3 -0
  3. package/dist/capability.d.ts.map +1 -1
  4. package/dist/chunk-YPCOVBQS.js +2343 -0
  5. package/dist/chunk-YPCOVBQS.js.map +1 -0
  6. package/dist/client.d.ts +99 -2
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/external.d.ts +23 -1
  9. package/dist/external.d.ts.map +1 -1
  10. package/dist/index.d.ts +8 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +512 -10
  13. package/dist/index.js.map +1 -1
  14. package/dist/issue-watcher.d.ts +2 -0
  15. package/dist/issue-watcher.d.ts.map +1 -1
  16. package/dist/launch.d.ts +40 -0
  17. package/dist/launch.d.ts.map +1 -0
  18. package/dist/maintenance-labels.d.ts +30 -0
  19. package/dist/maintenance-labels.d.ts.map +1 -0
  20. package/dist/maintenance.d.ts +132 -0
  21. package/dist/maintenance.d.ts.map +1 -0
  22. package/dist/publication-maintenance.d.ts +7 -0
  23. package/dist/publication-maintenance.d.ts.map +1 -0
  24. package/dist/publication.d.ts +37 -0
  25. package/dist/publication.d.ts.map +1 -0
  26. package/dist/repository-catalog.d.ts +16 -0
  27. package/dist/repository-catalog.d.ts.map +1 -0
  28. package/dist/setup.d.ts +8 -2
  29. package/dist/setup.d.ts.map +1 -1
  30. package/dist/testing.d.ts +10 -1
  31. package/dist/testing.d.ts.map +1 -1
  32. package/dist/testing.js +125 -5
  33. package/dist/testing.js.map +1 -1
  34. package/dist/ticket-creation.d.ts +5 -0
  35. package/dist/ticket-creation.d.ts.map +1 -0
  36. package/dist/tools.d.ts +100 -3
  37. package/dist/tools.d.ts.map +1 -1
  38. package/package.json +7 -7
  39. package/src/capability.ts +3 -0
  40. package/src/client.ts +275 -6
  41. package/src/delivery-tools.ts +4 -4
  42. package/src/external.ts +90 -19
  43. package/src/index.ts +58 -10
  44. package/src/issue-watcher.ts +10 -1
  45. package/src/launch.ts +63 -0
  46. package/src/maintenance-labels.ts +129 -0
  47. package/src/maintenance.ts +759 -0
  48. package/src/publication-maintenance.ts +288 -0
  49. package/src/publication.ts +234 -0
  50. package/src/repository-catalog.ts +94 -0
  51. package/src/setup.ts +115 -6
  52. package/src/testing.ts +143 -4
  53. package/src/ticket-creation.ts +145 -0
  54. package/src/tools.ts +382 -23
  55. package/dist/chunk-TQIZKDAM.js +0 -1160
  56. package/dist/chunk-TQIZKDAM.js.map +0 -1
package/src/setup.ts CHANGED
@@ -1,7 +1,18 @@
1
- import { coreHostCapabilities, type ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
1
+ import {
2
+ coreHostCapabilities,
3
+ type IntegrationToolExecutionContext,
4
+ repositorySettingsIdentity,
5
+ type ServerExtensionAPI,
6
+ scopedSettingsCapability,
7
+ type TicketCreationConfig,
8
+ } from "@leitwerk-dev/process-sdk";
9
+ import type { PollResult } from "@leitwerk-dev/watcher-utils";
2
10
  import { type GitLabIntegration, gitlabIntegration } from "./capability.js";
3
11
  import { registerGitLabDeliveryTools } from "./delivery-tools.js";
4
12
  import { createGitLabProvider } from "./external.js";
13
+ import { createGitLabMaintenance } from "./maintenance.js";
14
+ import { createGitLabRepositoryCatalog } from "./repository-catalog.js";
15
+ import { registerGitLabTicketCreation } from "./ticket-creation.js";
5
16
  import { registerGitLabTools } from "./tools.js";
6
17
 
7
18
  /** Register shared tools and polling with an explicit integration. @public */
@@ -11,12 +22,110 @@ export function setupGitLabIntegration(
11
22
  options: {
12
23
  /** @public */
13
24
  now?: () => number;
25
+ /** @internal */
26
+ ticketCreation?: TicketCreationConfig;
14
27
  } = {},
15
- ) {
16
- api.provide(gitlabIntegration, integration);
28
+ ):
29
+ | {
30
+ /** @public */
31
+ poll(): Promise<PollResult>;
32
+ /** @internal */
33
+ maintenance: ReturnType<typeof createGitLabMaintenance>;
34
+ }
35
+ | undefined {
36
+ const catalog = integration.repositoryCatalog ?? createGitLabRepositoryCatalog(integration);
37
+ api.provide(gitlabIntegration, {
38
+ profiles: () => integration.profiles(),
39
+ client: (profile) => integration.client(profile),
40
+ repositoryCatalog: catalog,
41
+ });
42
+ const settings = api.get(scopedSettingsCapability);
43
+ if (settings && !Array.isArray(settings))
44
+ settings.registerDiscovery("repository", async () => {
45
+ const subjects = [];
46
+ for (const profile of integration.profiles()) {
47
+ const client = integration.client(profile);
48
+ for (const project of await catalog.refresh(profile))
49
+ subjects.push({
50
+ scopeType: "repository",
51
+ identity: repositorySettingsIdentity(client.baseUrl, project.id),
52
+ label: project.path_with_namespace,
53
+ aliases: [
54
+ project.http_url_to_repo,
55
+ ...(project.ssh_url_to_repo ? [project.ssh_url_to_repo] : []),
56
+ ],
57
+ });
58
+ }
59
+ return subjects;
60
+ });
17
61
  const deps = api.get(coreHostCapabilities.serverSetup);
18
62
  if (!deps || Array.isArray(deps)) return;
19
- registerGitLabTools(api, integration);
20
- registerGitLabDeliveryTools(api, integration, deps.projects);
21
- return createGitLabProvider(deps, integration, options);
63
+ const maintenance = createGitLabMaintenance(api, deps, integration, options.now);
64
+ const assertOwnership = async (ctx: IntegrationToolExecutionContext) => {
65
+ if (maintenance.ownsProcess(ctx.process.processId))
66
+ await maintenance.assertOwnership(ctx.process.id, ctx.project?.key ?? "repo", ctx.signal);
67
+ };
68
+ const guardedWrites = new Set([
69
+ "gitlab_ensure_merge_request",
70
+ "gitlab_comment",
71
+ "gitlab_reply",
72
+ "gitlab_inline_comment",
73
+ "gitlab_resolve_discussion",
74
+ "gitlab_acknowledge_feedback",
75
+ ]);
76
+ const guardedApi: ServerExtensionAPI = {
77
+ ...api,
78
+ tool(definition) {
79
+ api.tool({
80
+ ...definition,
81
+ async execute(ctx, args) {
82
+ const guarded =
83
+ maintenance.ownsProcess(ctx.process.processId) && guardedWrites.has(definition.name);
84
+ if (guarded || definition.name === "gitlab_update_comment") await assertOwnership(ctx);
85
+ const result = await definition.execute(
86
+ guarded
87
+ ? {
88
+ ...ctx,
89
+ externalWrites: {
90
+ ...ctx.externalWrites,
91
+ ensure: (identity, operation) =>
92
+ ctx.externalWrites.ensure(identity, {
93
+ ...operation,
94
+ execute: async () => {
95
+ await assertOwnership(ctx);
96
+ return operation.execute();
97
+ },
98
+ }),
99
+ },
100
+ }
101
+ : ctx,
102
+ args,
103
+ );
104
+ if (definition.name === "gitlab_ensure_merge_request") await assertOwnership(ctx);
105
+ return result;
106
+ },
107
+ });
108
+ },
109
+ };
110
+ registerGitLabTools(guardedApi, integration, assertOwnership);
111
+ registerGitLabTicketCreation(
112
+ api,
113
+ integration,
114
+ options.ticketCreation ?? { enabled: false, defaultLabels: [] },
115
+ );
116
+ registerGitLabDeliveryTools(guardedApi, integration, deps.projects);
117
+ api.tool({
118
+ name: "gitlab_assert_maintenance",
119
+ description: "Recheck MR maintenance ownership before Git publication",
120
+ parameters: {
121
+ type: "object",
122
+ properties: { projectKey: { type: "string" } },
123
+ required: ["projectKey"],
124
+ },
125
+ async execute(ctx) {
126
+ await assertOwnership(ctx);
127
+ return { ok: true };
128
+ },
129
+ });
130
+ return { ...createGitLabProvider(deps, integration, options), /** @internal */ maintenance };
22
131
  }
package/src/testing.ts CHANGED
@@ -6,14 +6,17 @@ import type {
6
6
  GitLabDiff,
7
7
  GitLabFeedback,
8
8
  GitLabIssue,
9
+ GitLabLabelEvent,
9
10
  GitLabMergeRequest,
10
11
  GitLabNote,
11
12
  GitLabNoteReaction,
12
13
  GitLabPipeline,
13
14
  GitLabProject,
14
15
  } from "./client.js";
16
+ import { GitLabError } from "./client.js";
15
17
 
16
18
  export { GITLAB_MR_KIND } from "./external.js";
19
+ export { createGitLabMaintenance } from "./maintenance.js";
17
20
  export { setupGitLabIntegration } from "./setup.js";
18
21
 
19
22
  /** @public */
@@ -25,6 +28,8 @@ interface LocalState {
25
28
  /** @public */
26
29
  labels?: Record<string, string[]>;
27
30
  /** @internal */
31
+ labelEvents?: Record<string, GitLabLabelEvent[]>;
32
+ /** @internal */
28
33
  projects: GitLabProject[];
29
34
  /** @internal */
30
35
  mrs: GitLabMergeRequest[];
@@ -38,6 +43,8 @@ interface LocalState {
38
43
  feedback?: Record<string, GitLabFeedback[]>;
39
44
  /** @public */
40
45
  discussionNotes?: Record<string, GitLabNote[]>;
46
+ /** @internal */
47
+ discussionResolved?: Record<string, boolean>;
41
48
  /** @public */
42
49
  reactions?: Record<string, GitLabNoteReaction[]>;
43
50
  }
@@ -50,11 +57,15 @@ export class LocalGitLabAdapter {
50
57
  loseNextCommentResponse = false;
51
58
  /** @public */
52
59
  loseNextMergeRequestResponse = false;
60
+ /** @internal */
61
+ loseNextIssueResponse = false;
53
62
  /** @public */
54
63
  loseNextReplyResponse = false;
55
64
  /** @public */
56
65
  loseNextReactionResponse = false;
57
66
  /** @public */
67
+ loseNextLabelResponse = false;
68
+ /** @public */
58
69
  constructor(
59
70
  /** @internal */
60
71
  readonly root: string,
@@ -104,6 +115,7 @@ export class LocalGitLabAdapter {
104
115
  id: this.state.projects.length + 1,
105
116
  path_with_namespace: name,
106
117
  http_url_to_repo: bare,
118
+ ssh_url_to_repo: bare,
107
119
  web_url: `${this.baseUrl}/${name}`,
108
120
  default_branch: "main",
109
121
  };
@@ -211,7 +223,7 @@ export class LocalGitLabAdapter {
211
223
  client(): GitLabClientLike {
212
224
  const mr = (id: number, iid: number) => {
213
225
  const m = this.state.mrs.find((m) => m.project_id === id && m.iid === iid);
214
- if (!m) throw new Error("Unknown test MR");
226
+ if (!m) throw new GitLabError(404, false);
215
227
  return m;
216
228
  };
217
229
  const commit = (id: number, ref: string) => ({
@@ -221,10 +233,26 @@ export class LocalGitLabAdapter {
221
233
  });
222
234
  return {
223
235
  baseUrl: this.baseUrl,
224
- listIssues: async (id) =>
236
+ listIssues: async (id, _signal, state = "opened") =>
225
237
  structuredClone(
226
- (this.state.issues ?? []).filter((i) => i.project_id === id && i.state === "opened"),
238
+ (this.state.issues ?? []).filter(
239
+ (i) => i.project_id === id && (state === "all" || i.state === "opened"),
240
+ ),
227
241
  ),
242
+ createIssue: async (id, input) => {
243
+ const issue = this.createIssue(
244
+ id,
245
+ input.title,
246
+ input.labels ? input.labels.split(",") : [],
247
+ );
248
+ issue.description = input.description;
249
+ this.save();
250
+ if (this.loseNextIssueResponse) {
251
+ this.loseNextIssueResponse = false;
252
+ throw new Error("Response lost after issue write");
253
+ }
254
+ return structuredClone(issue);
255
+ },
228
256
  getIssue: async (id, iid) => {
229
257
  const issue = (this.state.issues ?? []).find((i) => i.project_id === id && i.iid === iid);
230
258
  if (!issue) throw new Error("Unknown local GitLab issue");
@@ -288,7 +316,32 @@ export class LocalGitLabAdapter {
288
316
  },
289
317
 
290
318
  getProject: async (id) => structuredClone(this.project(id)),
319
+ listRepositoryTree: async (id, ref, directory = "") =>
320
+ this.git(id, ["ls-tree", ref, ...(directory ? [`${directory}/`] : [])])
321
+ .split("\n")
322
+ .filter(Boolean)
323
+ .map((line) => {
324
+ const [details, filePath] = line.split("\t");
325
+ const [, type, objectId] = details.split(" ");
326
+ return { path: filePath, type, id: objectId };
327
+ }),
328
+ getRepositoryFile: async (id, ref, filePath) => ({
329
+ file_path: filePath,
330
+ content: Buffer.from(this.git(id, ["show", `${ref}:${filePath}`])).toString("base64"),
331
+ encoding: "base64",
332
+ last_commit_id: this.git(id, ["log", "-1", "--format=%H", ref, "--", filePath]),
333
+ }),
291
334
  listProjects: async () => structuredClone(this.state.projects),
335
+ searchProjects: async (search) =>
336
+ structuredClone(
337
+ this.state.projects
338
+ .filter(
339
+ (project) =>
340
+ !project.archived &&
341
+ project.path_with_namespace.toLowerCase().includes(search.trim().toLowerCase()),
342
+ )
343
+ .slice(0, 100),
344
+ ),
292
345
  getGroup: async (id) => ({ id: 1, full_path: String(id) }),
293
346
  listGroupProjects: async (group) =>
294
347
  structuredClone(
@@ -297,7 +350,7 @@ export class LocalGitLabAdapter {
297
350
  getMergeRequest: async (id, iid) => ({
298
351
  ...structuredClone(mr(id, iid)),
299
352
  has_conflicts: this.conflicts(mr(id, iid)),
300
- sha: commit(mr(id, iid).source_project_id, mr(id, iid).source_branch).id,
353
+ sha: this.git(mr(id, iid).source_project_id, ["rev-parse", mr(id, iid).source_branch]),
301
354
  }),
302
355
  listMergeRequests: async (id, label) =>
303
356
  structuredClone(
@@ -305,6 +358,40 @@ export class LocalGitLabAdapter {
305
358
  (m) => m.project_id === id && m.state === "opened" && m.labels.includes(label),
306
359
  ),
307
360
  ),
361
+ listMergeRequestLabelEvents: async (id, iid) => {
362
+ mr(id, iid);
363
+ return structuredClone(this.state.labelEvents?.[`${id}:${iid}`] ?? []);
364
+ },
365
+ updateMergeRequestLabels: async (id, iid, patch) => {
366
+ const request = mr(id, iid);
367
+ this.state.labelEvents ??= {};
368
+ this.state.labelEvents[`${id}:${iid}`] ??= [];
369
+ const events = this.state.labelEvents[`${id}:${iid}`];
370
+ for (const [action, labels] of [
371
+ ["add", patch.add_labels],
372
+ ["remove", patch.remove_labels],
373
+ ] as const) {
374
+ for (const name of labels?.split(",").filter(Boolean) ?? []) {
375
+ if (request.labels.includes(name) === (action === "add")) continue;
376
+ request.labels =
377
+ action === "add"
378
+ ? [...request.labels, name]
379
+ : request.labels.filter((label) => label !== name);
380
+ events.push({
381
+ id: Math.max(0, ...events.map((event) => event.id)) + 1,
382
+ action,
383
+ label: { name },
384
+ created_at: new Date().toISOString(),
385
+ });
386
+ }
387
+ }
388
+ this.save();
389
+ if (this.loseNextLabelResponse) {
390
+ this.loseNextLabelResponse = false;
391
+ throw new Error("Response lost after label write");
392
+ }
393
+ return structuredClone(request);
394
+ },
308
395
  getBranch: async (id, branch) => ({
309
396
  name: branch,
310
397
  can_push: true,
@@ -312,6 +399,7 @@ export class LocalGitLabAdapter {
312
399
  commit: commit(id, branch),
313
400
  }),
314
401
  getCommit: async (id, ref) => commit(id, ref),
402
+ getMergeBase: async (id, refs) => commit(id, this.git(id, ["merge-base", ...refs])),
315
403
  getChanges: async (id, iid) => structuredClone(this.state.diffs[`${id}:${iid}`] ?? []),
316
404
  listMergeRequestPipelines: async (id, iid) =>
317
405
  structuredClone(
@@ -357,10 +445,38 @@ export class LocalGitLabAdapter {
357
445
  notes: (this.state.discussionNotes?.[`${id}:${iid}:${discussionId}`] ?? []).map((note) => ({
358
446
  ...structuredClone(note),
359
447
  system: false,
448
+ resolved: this.state.discussionResolved?.[`${id}:${iid}:${discussionId}`] === true,
360
449
  created_at: new Date().toISOString(),
361
450
  author: { username: "bot" },
362
451
  })),
363
452
  }),
453
+ listDiscussions: async (id, iid) =>
454
+ Object.entries(this.state.discussionNotes ?? {})
455
+ .filter(([key]) => key.startsWith(`${id}:${iid}:`))
456
+ .map(([key, notes]) => ({
457
+ id: key.slice(`${id}:${iid}:`.length),
458
+ notes: notes.map((note) => ({
459
+ ...structuredClone(note),
460
+ system: false,
461
+ created_at: new Date().toISOString(),
462
+ author: { username: "bot" },
463
+ })),
464
+ })),
465
+ addDiscussion: async (id, iid, body, position) => {
466
+ this.state.discussionNotes ??= {};
467
+ const discussionId = `discussion-${Object.keys(this.state.discussionNotes).length + 1}`;
468
+ const note = {
469
+ id: 1,
470
+ body,
471
+ system: false,
472
+ created_at: new Date().toISOString(),
473
+ author: { username: "bot" },
474
+ position,
475
+ };
476
+ this.state.discussionNotes[`${id}:${iid}:${discussionId}`] = [note];
477
+ this.save();
478
+ return { id: discussionId, notes: [note] };
479
+ },
364
480
  replyToDiscussion: async (id, iid, discussionId, body) => {
365
481
  const key = `${id}:${iid}:${discussionId}`;
366
482
  this.state.discussionNotes ??= {};
@@ -368,6 +484,22 @@ export class LocalGitLabAdapter {
368
484
  const notes = this.state.discussionNotes[key];
369
485
  return this.append(notes, { id: notes.length + 1, body }, "Reply");
370
486
  },
487
+ resolveDiscussion: async (id, iid, discussionId) => {
488
+ const key = `${id}:${iid}:${discussionId}`;
489
+ this.state.discussionResolved ??= {};
490
+ this.state.discussionResolved[key] = true;
491
+ this.save();
492
+ return {
493
+ id: discussionId,
494
+ notes: (this.state.discussionNotes?.[key] ?? []).map((note) => ({
495
+ ...structuredClone(note),
496
+ system: false,
497
+ resolved: true,
498
+ created_at: new Date().toISOString(),
499
+ author: { username: "bot" },
500
+ })),
501
+ };
502
+ },
371
503
  listNoteReactions: async (id, iid, noteId) =>
372
504
  structuredClone(this.state.reactions?.[`${id}:${iid}:${noteId}`] ?? []),
373
505
  addNoteReaction: async (id, iid, noteId, name) => {
@@ -388,6 +520,13 @@ export class LocalGitLabAdapter {
388
520
  const notes = this.state.notes[key];
389
521
  return this.append(notes, { id: notes.length + 1, body }, "Comment");
390
522
  },
523
+ updateNote: async (id, iid, noteId, body) => {
524
+ const note = (this.state.notes[`${id}:${iid}`] ?? []).find((item) => item.id === noteId);
525
+ if (!note) throw new Error("Unknown test note");
526
+ note.body = body;
527
+ this.save();
528
+ return structuredClone(note);
529
+ },
391
530
  };
392
531
  }
393
532
  }
@@ -0,0 +1,145 @@
1
+ import {
2
+ listTicketDestinations,
3
+ markdownTicketCreationDefinition,
4
+ numberArg,
5
+ objectArg,
6
+ parseTicketDestinationId,
7
+ type ServerExtensionAPI,
8
+ stringArg,
9
+ type TicketCreationConfig,
10
+ type TicketCreationDestinationProvider,
11
+ type TicketCreationDestinationSnapshot,
12
+ ticketDestinationId,
13
+ ticketLabelNames,
14
+ } from "@leitwerk-dev/process-sdk";
15
+ import type { GitLabIntegration } from "./capability.js";
16
+ import type { GitLabProject } from "./client.js";
17
+
18
+ function available(project: GitLabProject): boolean {
19
+ return (
20
+ !project.archived &&
21
+ project.issues_enabled !== false &&
22
+ project.issues_access_level !== "disabled"
23
+ );
24
+ }
25
+
26
+ function destinationData(snapshot: TicketCreationDestinationSnapshot) {
27
+ const data = objectArg(snapshot.data);
28
+ return {
29
+ profile: stringArg(data, "profile"),
30
+ baseUrl: stringArg(data, "baseUrl"),
31
+ projectId: numberArg(data, "projectId"),
32
+ path: stringArg(data, "path"),
33
+ defaultLabels: ticketLabelNames(data.defaultLabels),
34
+ };
35
+ }
36
+
37
+ /** @internal */
38
+ export function registerGitLabTicketCreation(
39
+ api: ServerExtensionAPI,
40
+ integration: GitLabIntegration,
41
+ config: TicketCreationConfig,
42
+ ): void {
43
+ if (!config.enabled) return;
44
+ const summary = (profile: string, project: GitLabProject) => ({
45
+ id: ticketDestinationId(profile, project.id),
46
+ displayName: project.path_with_namespace,
47
+ group: `${profile} · ${new URL(integration.client(profile).baseUrl).hostname}`,
48
+ description: config.defaultLabels.length
49
+ ? `Default labels: ${config.defaultLabels.join(", ")}`
50
+ : "No default labels",
51
+ });
52
+ const destinations: TicketCreationDestinationProvider = {
53
+ list() {
54
+ return listTicketDestinations("GitLab", integration.profiles(), async (profile) =>
55
+ (await integration.client(profile).listProjects())
56
+ .filter(available)
57
+ .map((project) => summary(profile, project)),
58
+ );
59
+ },
60
+ async resolve({ destinationId }) {
61
+ const { profile, resourceId } = parseTicketDestinationId(destinationId);
62
+ const client = integration.client(profile);
63
+ const project = await client.getProject(Number(resourceId));
64
+ if (!available(project)) throw new Error("The selected GitLab project cannot accept issues");
65
+ const labels = await client.listLabels(project.id);
66
+ return {
67
+ summary: summary(profile, project),
68
+ data: {
69
+ profile,
70
+ baseUrl: client.baseUrl,
71
+ projectId: project.id,
72
+ path: project.path_with_namespace,
73
+ defaultLabels: config.defaultLabels,
74
+ },
75
+ agentContext: `Create an issue in ${project.path_with_namespace}. Existing optional labels: ${labels.map((label) => label.name).join(", ") || "none"}.`,
76
+ };
77
+ },
78
+ async validate(snapshot) {
79
+ const data = destinationData(snapshot);
80
+ const client = integration.client(data.profile);
81
+ if (client.baseUrl !== data.baseUrl) throw new Error("GitLab profile installation changed");
82
+ const project = await client.getProject(data.projectId);
83
+ if (!available(project) || project.path_with_namespace !== data.path)
84
+ throw new Error("The selected GitLab project changed; choose the destination again");
85
+ },
86
+ };
87
+ api.tool<Record<string, unknown>>({
88
+ name: "gitlab_create_issue",
89
+ description: "Create one issue in the selected GitLab project",
90
+ ...markdownTicketCreationDefinition("GitLab", destinations, "description"),
91
+ async execute(ctx, args) {
92
+ if (!ctx.ticketDestination) throw new Error("A GitLab ticket destination is required");
93
+ await destinations.validate(ctx.ticketDestination);
94
+ const target = destinationData(ctx.ticketDestination);
95
+ const client = integration.client(target.profile);
96
+ const title = stringArg(args, "title");
97
+ const description = stringArg(args, "description");
98
+ const requestedLabels = ticketLabelNames(args.labels);
99
+ const names = [...new Set([...target.defaultLabels, ...requestedLabels])];
100
+ if (names.some((name) => name.includes(",")))
101
+ throw new Error("GitLab label names cannot contain commas");
102
+ const labels = await client.listLabels(target.projectId, ctx.signal);
103
+ const unknown = requestedLabels.filter(
104
+ (name) =>
105
+ !target.defaultLabels.includes(name) && !labels.some((label) => label.name === name),
106
+ );
107
+ if (unknown.length) throw new Error(`Unknown GitLab labels: ${unknown.join(", ")}`);
108
+ for (const name of target.defaultLabels) {
109
+ await ctx.externalWrites.ensure(
110
+ { writeType: "gitlab.ensure_label", dedupKey: `${ctx.idempotencyKey}:label:${name}` },
111
+ {
112
+ reconcile: async () =>
113
+ (await client.listLabels(target.projectId, ctx.signal)).find(
114
+ (label) => label.name === name,
115
+ ) ?? null,
116
+ execute: () => client.createLabel(target.projectId, name, ctx.signal),
117
+ toMetadata: (label) => ({ name: label.name }),
118
+ },
119
+ );
120
+ }
121
+ const marker = `<!-- leitwerk-ticket-write:${ctx.idempotencyKey} -->`;
122
+ const issue = await ctx.externalWrites.ensure(
123
+ { writeType: "gitlab.create_issue", dedupKey: ctx.idempotencyKey },
124
+ {
125
+ reconcile: async () =>
126
+ (await client.listIssues(target.projectId, ctx.signal, "all")).find((issue) =>
127
+ issue.description?.includes(marker),
128
+ ) ?? null,
129
+ execute: () =>
130
+ client.createIssue(
131
+ target.projectId,
132
+ { title, description: `${description}\n\n${marker}`, labels: names.join(",") },
133
+ ctx.signal,
134
+ ),
135
+ toMetadata: (issue) => ({
136
+ projectId: issue.project_id,
137
+ iid: issue.iid,
138
+ url: issue.web_url,
139
+ }),
140
+ },
141
+ );
142
+ return { externalId: `${target.path}#${issue.iid}`, url: issue.web_url, result: issue };
143
+ },
144
+ });
145
+ }