@leitwerk-dev/gitlab 0.2.1 → 0.3.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.
- package/README.md +27 -5
- package/dist/chunk-TQIZKDAM.js +1160 -0
- package/dist/chunk-TQIZKDAM.js.map +1 -0
- package/dist/client.d.ts +80 -15
- package/dist/client.d.ts.map +1 -1
- package/dist/delivery-tools.d.ts +4 -0
- package/dist/delivery-tools.d.ts.map +1 -0
- package/dist/external.d.ts +58 -6
- package/dist/external.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -45
- package/dist/index.js.map +1 -1
- package/dist/issue-watcher.d.ts +40 -0
- package/dist/issue-watcher.d.ts.map +1 -0
- package/dist/preflight.d.ts +10 -0
- package/dist/preflight.d.ts.map +1 -0
- package/dist/setup.d.ts.map +1 -1
- package/dist/testing.d.ts +17 -2
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +129 -1
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +9 -2
- package/dist/tools.d.ts.map +1 -1
- package/package.json +7 -6
- package/src/client.ts +169 -22
- package/src/delivery-tools.ts +226 -0
- package/src/external.ts +161 -9
- package/src/index.ts +3 -0
- package/src/issue-watcher.ts +145 -0
- package/src/preflight.ts +70 -0
- package/src/setup.ts +2 -0
- package/src/testing.ts +140 -1
- package/src/tools.ts +32 -9
- package/dist/chunk-64FNBSKH.js +0 -605
- package/dist/chunk-64FNBSKH.js.map +0 -1
package/src/tools.ts
CHANGED
|
@@ -20,29 +20,48 @@ async function existingRemote<T>(read: () => Promise<T>): Promise<T | null> {
|
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
/** @public */
|
|
23
|
-
export function
|
|
23
|
+
export function resolveGitLabRepositoryBinding(
|
|
24
24
|
ctx: Pick<IntegrationToolExecutionContext, "project" | "process">,
|
|
25
|
+
/** @public */
|
|
25
26
|
): {
|
|
26
27
|
/** @public */
|
|
27
28
|
profile: string;
|
|
28
29
|
/** @public */
|
|
29
30
|
projectId: number;
|
|
30
|
-
/** @public */
|
|
31
|
-
iid: number;
|
|
32
31
|
} {
|
|
33
32
|
if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
|
|
34
33
|
throw new Error("An authorized GitLab process project is required");
|
|
35
34
|
const binding = ctx.project.metadata?.gitlab as
|
|
36
|
-
| { profile?: unknown; projectId?: unknown
|
|
35
|
+
| { profile?: unknown; projectId?: unknown }
|
|
37
36
|
| undefined;
|
|
38
37
|
if (
|
|
39
38
|
!binding ||
|
|
40
39
|
typeof binding.profile !== "string" ||
|
|
40
|
+
!binding.profile.trim() ||
|
|
41
41
|
typeof binding.projectId !== "number" ||
|
|
42
|
-
|
|
42
|
+
!Number.isSafeInteger(binding.projectId) ||
|
|
43
|
+
binding.projectId <= 0
|
|
43
44
|
)
|
|
44
45
|
throw new Error("Invalid GitLab project binding");
|
|
45
|
-
return { profile: binding.profile, projectId: binding.projectId
|
|
46
|
+
return { profile: binding.profile, projectId: binding.projectId };
|
|
47
|
+
}
|
|
48
|
+
/** @public */
|
|
49
|
+
export function resolveGitLabBinding(
|
|
50
|
+
ctx: Pick<IntegrationToolExecutionContext, "project" | "process">,
|
|
51
|
+
/** @public */
|
|
52
|
+
): {
|
|
53
|
+
/** @public */
|
|
54
|
+
profile: string;
|
|
55
|
+
/** @public */
|
|
56
|
+
projectId: number;
|
|
57
|
+
/** @public */
|
|
58
|
+
iid: number;
|
|
59
|
+
} {
|
|
60
|
+
const repository = resolveGitLabRepositoryBinding(ctx);
|
|
61
|
+
const iid = (ctx.project?.metadata?.gitlab as { iid?: unknown })?.iid;
|
|
62
|
+
if (typeof iid !== "number" || !Number.isSafeInteger(iid) || iid <= 0)
|
|
63
|
+
throw new Error("Invalid GitLab project binding: a merge request is required");
|
|
64
|
+
return { ...repository, iid };
|
|
46
65
|
}
|
|
47
66
|
/** @internal */
|
|
48
67
|
export async function ensureGitLabComment(input: {
|
|
@@ -64,6 +83,7 @@ export async function ensureGitLabComment(input: {
|
|
|
64
83
|
discussionId?: string;
|
|
65
84
|
/** @internal */
|
|
66
85
|
signal?: AbortSignal;
|
|
86
|
+
/** @public */
|
|
67
87
|
}): Promise<{
|
|
68
88
|
/** @internal */
|
|
69
89
|
marker: string;
|
|
@@ -102,9 +122,9 @@ export async function ensureGitLabSeenReaction(input: {
|
|
|
102
122
|
writes: ExternalWrites;
|
|
103
123
|
/** @public */
|
|
104
124
|
instanceId: string;
|
|
105
|
-
/** @
|
|
125
|
+
/** @internal */
|
|
106
126
|
projectId: number;
|
|
107
|
-
/** @
|
|
127
|
+
/** @internal */
|
|
108
128
|
iid: number;
|
|
109
129
|
/** @public */
|
|
110
130
|
noteId: number;
|
|
@@ -167,12 +187,15 @@ export function registerGitLabTools(api: ServerExtensionAPI, integration: GitLab
|
|
|
167
187
|
[...required],
|
|
168
188
|
),
|
|
169
189
|
async execute(ctx, args) {
|
|
190
|
+
if (name === "gitlab_get_identity")
|
|
191
|
+
return integration
|
|
192
|
+
.client(resolveGitLabRepositoryBinding(ctx).profile)
|
|
193
|
+
.resolveGitIdentity(ctx.signal);
|
|
170
194
|
const b = resolveGitLabBinding(ctx);
|
|
171
195
|
const client = integration.client(b.profile);
|
|
172
196
|
if (name === "gitlab_observe_merge_request")
|
|
173
197
|
return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
174
198
|
if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
|
|
175
|
-
if (name === "gitlab_get_identity") return client.resolveGitIdentity(ctx.signal);
|
|
176
199
|
if (name === "gitlab_comment" || name === "gitlab_reply")
|
|
177
200
|
return ensureGitLabComment({
|
|
178
201
|
client,
|
package/dist/chunk-64FNBSKH.js
DELETED
|
@@ -1,605 +0,0 @@
|
|
|
1
|
-
// src/client.ts
|
|
2
|
-
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
3
|
-
import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
|
|
4
|
-
var GitLabError = class extends Error {
|
|
5
|
-
/** @internal */
|
|
6
|
-
constructor(status, retryable) {
|
|
7
|
-
super(
|
|
8
|
-
`GitLab request failed (${status || "network unavailable"})${retryable ? "; retryable" : "; check profile and project access"}`
|
|
9
|
-
);
|
|
10
|
-
this.status = status;
|
|
11
|
-
this.retryable = retryable;
|
|
12
|
-
}
|
|
13
|
-
status;
|
|
14
|
-
retryable;
|
|
15
|
-
};
|
|
16
|
-
function parseGitLabProfiles(raw) {
|
|
17
|
-
const profiles = /* @__PURE__ */ new Map();
|
|
18
|
-
for (const [name, value] of Object.entries(
|
|
19
|
-
asUnknownRecord(asUnknownRecord(raw)?.profiles) ?? {}
|
|
20
|
-
)) {
|
|
21
|
-
const item = asUnknownRecord(value) ?? {};
|
|
22
|
-
const baseUrl = typeof item.base_url === "string" ? item.base_url.replace(/\/+$/, "") : "";
|
|
23
|
-
const url = repositoryHttpsUrl(`${baseUrl}/` === "/" ? "" : `${baseUrl}/repository`);
|
|
24
|
-
if (url.origin !== baseUrl)
|
|
25
|
-
throw new Error(`GitLab profile '${name}' requires an HTTPS origin base_url`);
|
|
26
|
-
const configuredToken = typeof item.token === "string" ? item.token : "";
|
|
27
|
-
const token = configuredToken.startsWith("env:") ? process.env[configuredToken.slice(4)] ?? "" : configuredToken;
|
|
28
|
-
if (!token || /[\r\n\0]/.test(token))
|
|
29
|
-
throw new Error(`GitLab profile '${name}' requires a token`);
|
|
30
|
-
const identity = asUnknownRecord(item.git_identity);
|
|
31
|
-
if (identity && [identity.name, identity.email].some(
|
|
32
|
-
(v) => typeof v !== "string" || !v.trim() || /[\r\n<>]/.test(v)
|
|
33
|
-
))
|
|
34
|
-
throw new Error(`GitLab profile '${name}' requires a valid git_identity name and email`);
|
|
35
|
-
profiles.set(name, {
|
|
36
|
-
baseUrl,
|
|
37
|
-
token,
|
|
38
|
-
...identity ? { gitIdentity: { name: String(identity.name), email: String(identity.email) } } : {}
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
return profiles;
|
|
42
|
-
}
|
|
43
|
-
var projectPath = (id) => `/projects/${encodeURIComponent(id)}`;
|
|
44
|
-
var mrPath = (id, iid) => `${projectPath(id)}/merge_requests/${iid}`;
|
|
45
|
-
var GitLabClient = class {
|
|
46
|
-
/** @public */
|
|
47
|
-
baseUrl;
|
|
48
|
-
#profile;
|
|
49
|
-
#fetch;
|
|
50
|
-
#sleep;
|
|
51
|
-
/** @internal */
|
|
52
|
-
constructor(profile, options = {}) {
|
|
53
|
-
if (repositoryHttpsUrl(`${profile.baseUrl}/repository`).origin !== profile.baseUrl)
|
|
54
|
-
throw new Error("GitLab requires an HTTPS origin baseUrl");
|
|
55
|
-
if (!profile.token || /[\r\n\0]/.test(profile.token))
|
|
56
|
-
throw new Error("GitLab requires a valid token");
|
|
57
|
-
this.#profile = profile;
|
|
58
|
-
this.baseUrl = profile.baseUrl;
|
|
59
|
-
this.#fetch = options.fetch ?? fetch;
|
|
60
|
-
this.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
61
|
-
}
|
|
62
|
-
async response(path, signal, body) {
|
|
63
|
-
for (let attempt = 0; ; attempt++) {
|
|
64
|
-
let response;
|
|
65
|
-
try {
|
|
66
|
-
response = await this.#fetch(`${this.baseUrl}/api/v4${path}`, {
|
|
67
|
-
method: body === void 0 ? "GET" : "POST",
|
|
68
|
-
redirect: "error",
|
|
69
|
-
headers: {
|
|
70
|
-
"PRIVATE-TOKEN": this.#profile.token,
|
|
71
|
-
Accept: "application/json",
|
|
72
|
-
...body === void 0 ? {} : { "Content-Type": "application/json" }
|
|
73
|
-
},
|
|
74
|
-
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4),
|
|
75
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
76
|
-
});
|
|
77
|
-
} catch {
|
|
78
|
-
if (signal?.aborted) throw new GitLabError(0, true);
|
|
79
|
-
if (body !== void 0 || attempt >= 2) throw new GitLabError(0, true);
|
|
80
|
-
await this.#sleep(1e3 * 2 ** attempt);
|
|
81
|
-
continue;
|
|
82
|
-
}
|
|
83
|
-
if (response.ok) return response;
|
|
84
|
-
const retryable = response.status === 429 || response.status >= 500 || response.status === 408;
|
|
85
|
-
await response.body?.cancel();
|
|
86
|
-
if (!retryable || body !== void 0 || attempt >= 2)
|
|
87
|
-
throw new GitLabError(response.status, retryable);
|
|
88
|
-
const seconds = Number(response.headers.get("retry-after"));
|
|
89
|
-
await this.#sleep(Math.min(3e4, seconds > 0 ? seconds * 1e3 : 1e3 * 2 ** attempt));
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
async request(path, signal, body) {
|
|
93
|
-
return this.json(await this.response(path, signal, body));
|
|
94
|
-
}
|
|
95
|
-
async json(response) {
|
|
96
|
-
try {
|
|
97
|
-
return await response.json();
|
|
98
|
-
} catch {
|
|
99
|
-
throw new GitLabError(502, true);
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
async pages(path, signal) {
|
|
103
|
-
const rows = [];
|
|
104
|
-
let page = 1;
|
|
105
|
-
for (let n = 0; n < 1e4; n++) {
|
|
106
|
-
const response = await this.response(
|
|
107
|
-
`${path}${path.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
|
|
108
|
-
signal
|
|
109
|
-
);
|
|
110
|
-
const batch = await this.json(response);
|
|
111
|
-
if (!Array.isArray(batch)) throw new Error("Invalid GitLab list response");
|
|
112
|
-
rows.push(...batch);
|
|
113
|
-
const next = response.headers.get("x-next-page");
|
|
114
|
-
if (next === "" || next === null && batch.length < 100) return rows;
|
|
115
|
-
const nextPage = next === null ? page + 1 : Number(next);
|
|
116
|
-
if (!Number.isInteger(nextPage) || nextPage <= page)
|
|
117
|
-
throw new Error("Invalid GitLab pagination");
|
|
118
|
-
page = nextPage;
|
|
119
|
-
}
|
|
120
|
-
throw new Error("GitLab pagination limit exceeded; discovery incomplete");
|
|
121
|
-
}
|
|
122
|
-
/** @public */
|
|
123
|
-
getProject(id, signal) {
|
|
124
|
-
return this.request(projectPath(id), signal);
|
|
125
|
-
}
|
|
126
|
-
/** @internal */
|
|
127
|
-
listProjects(signal) {
|
|
128
|
-
return this.pages("/projects?archived=false", signal);
|
|
129
|
-
}
|
|
130
|
-
/** @internal */
|
|
131
|
-
getGroup(id, signal) {
|
|
132
|
-
return this.request(`/groups/${encodeURIComponent(id)}`, signal);
|
|
133
|
-
}
|
|
134
|
-
/** @internal */
|
|
135
|
-
listGroupProjects(id, signal) {
|
|
136
|
-
return this.pages(
|
|
137
|
-
`/groups/${encodeURIComponent(id)}/projects?include_subgroups=true&with_shared=false&archived=false`,
|
|
138
|
-
signal
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
/** @public */
|
|
142
|
-
listMergeRequests(id, label, signal) {
|
|
143
|
-
return this.pages(
|
|
144
|
-
`${projectPath(id)}/merge_requests?state=opened&labels=${encodeURIComponent(label)}`,
|
|
145
|
-
signal
|
|
146
|
-
);
|
|
147
|
-
}
|
|
148
|
-
/** @internal */
|
|
149
|
-
getMergeRequest(id, iid, signal) {
|
|
150
|
-
return this.request(mrPath(id, iid), signal);
|
|
151
|
-
}
|
|
152
|
-
/** @public */
|
|
153
|
-
getChanges(id, iid, signal) {
|
|
154
|
-
return this.pages(`${mrPath(id, iid)}/diffs`, signal);
|
|
155
|
-
}
|
|
156
|
-
/** @public */
|
|
157
|
-
getBranch(id, branch, signal) {
|
|
158
|
-
return this.request(
|
|
159
|
-
`${projectPath(id)}/repository/branches/${encodeURIComponent(branch)}`,
|
|
160
|
-
signal
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
/** @internal */
|
|
164
|
-
getCommit(id, sha, signal) {
|
|
165
|
-
return this.request(`${projectPath(id)}/repository/commits/${encodeURIComponent(sha)}`, signal);
|
|
166
|
-
}
|
|
167
|
-
/** @internal */
|
|
168
|
-
listMergeRequestPipelines(id, iid, signal) {
|
|
169
|
-
return this.pages(`${mrPath(id, iid)}/pipelines`, signal);
|
|
170
|
-
}
|
|
171
|
-
/** @internal */
|
|
172
|
-
listBranchPipelines(id, branch, sha, signal) {
|
|
173
|
-
return this.pages(
|
|
174
|
-
`${projectPath(id)}/pipelines?ref=${encodeURIComponent(branch)}&sha=${encodeURIComponent(sha)}&source=push`,
|
|
175
|
-
signal
|
|
176
|
-
);
|
|
177
|
-
}
|
|
178
|
-
/** @internal */
|
|
179
|
-
getPipeline(id, pipeline, signal) {
|
|
180
|
-
return this.request(`${projectPath(id)}/pipelines/${pipeline}`, signal);
|
|
181
|
-
}
|
|
182
|
-
/** @public */
|
|
183
|
-
listFailedJobs(id, pipeline, signal) {
|
|
184
|
-
return this.pages(
|
|
185
|
-
`${projectPath(id)}/pipelines/${pipeline}/jobs?scope[]=failed&include_retried=false`,
|
|
186
|
-
signal
|
|
187
|
-
);
|
|
188
|
-
}
|
|
189
|
-
/** @internal */
|
|
190
|
-
listNotes(id, iid, signal) {
|
|
191
|
-
return this.pages(`${mrPath(id, iid)}/notes`, signal);
|
|
192
|
-
}
|
|
193
|
-
/** @internal */
|
|
194
|
-
getDiscussion(id, iid, discussionId, signal) {
|
|
195
|
-
return this.request(
|
|
196
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}`,
|
|
197
|
-
signal
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
/** @internal */
|
|
201
|
-
replyToDiscussion(id, iid, discussionId, body, signal) {
|
|
202
|
-
return this.request(
|
|
203
|
-
`${mrPath(id, iid)}/discussions/${encodeURIComponent(discussionId)}/notes`,
|
|
204
|
-
signal,
|
|
205
|
-
{ body }
|
|
206
|
-
);
|
|
207
|
-
}
|
|
208
|
-
/** @internal */
|
|
209
|
-
listNoteReactions(id, iid, noteId, signal) {
|
|
210
|
-
return this.pages(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal);
|
|
211
|
-
}
|
|
212
|
-
/** @internal */
|
|
213
|
-
addNoteReaction(id, iid, noteId, name, signal) {
|
|
214
|
-
return this.request(`${mrPath(id, iid)}/notes/${noteId}/award_emoji`, signal, { name });
|
|
215
|
-
}
|
|
216
|
-
/** @public */
|
|
217
|
-
async listMergeRequestFeedback(id, iid, signal) {
|
|
218
|
-
const [discussions, identity] = await Promise.all([
|
|
219
|
-
this.pages(`${mrPath(id, iid)}/discussions`, signal),
|
|
220
|
-
this.resolveGitIdentity(signal)
|
|
221
|
-
]);
|
|
222
|
-
const feedback = [];
|
|
223
|
-
for (const discussion of discussions) {
|
|
224
|
-
for (const note of discussion.notes) {
|
|
225
|
-
if (note.system || note.resolved || note.author.bot || note.author.username === identity.username || !note.body.trim() || !Number.isFinite(Date.parse(note.created_at)))
|
|
226
|
-
continue;
|
|
227
|
-
const position = note.position ?? discussion.notes[0]?.position;
|
|
228
|
-
feedback.push({
|
|
229
|
-
id: note.id,
|
|
230
|
-
discussionId: discussion.id,
|
|
231
|
-
body: note.body,
|
|
232
|
-
author: note.author.username,
|
|
233
|
-
createdAt: note.created_at,
|
|
234
|
-
...position ? {
|
|
235
|
-
path: position.new_path ?? position.old_path,
|
|
236
|
-
line: position.new_line ?? position.old_line
|
|
237
|
-
} : {}
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
return feedback.sort((a, b) => a.id - b.id);
|
|
242
|
-
}
|
|
243
|
-
/** @internal */
|
|
244
|
-
addNote(id, iid, body, signal) {
|
|
245
|
-
return this.request(`${mrPath(id, iid)}/notes`, signal, { body });
|
|
246
|
-
}
|
|
247
|
-
/** @public */
|
|
248
|
-
async resolveGitIdentity(signal) {
|
|
249
|
-
const user = await this.request("/user", signal);
|
|
250
|
-
const name = this.#profile.gitIdentity?.name ?? user.name;
|
|
251
|
-
const email = this.#profile.gitIdentity?.email ?? user.commit_email ?? user.email;
|
|
252
|
-
if (!user.username || !name?.trim() || !email?.includes("@") || /[\r\n<>]/.test(name + email))
|
|
253
|
-
throw new Error(
|
|
254
|
-
"GitLab bot Git identity is unavailable; configure git_identity on the profile"
|
|
255
|
-
);
|
|
256
|
-
return { name, email, username: user.username };
|
|
257
|
-
}
|
|
258
|
-
/** @public */
|
|
259
|
-
async getJobTrace(id, job, maxBytes = 65536, signal) {
|
|
260
|
-
const limit = Math.min(262144, Math.max(1, Math.floor(maxBytes) || 65536));
|
|
261
|
-
const response = await this.response(`${projectPath(id)}/jobs/${job}/trace`, signal);
|
|
262
|
-
const reader = response.body?.getReader();
|
|
263
|
-
if (!reader) return { text: "", truncated: false };
|
|
264
|
-
const chunks = [];
|
|
265
|
-
let size = 0;
|
|
266
|
-
let truncated = false;
|
|
267
|
-
try {
|
|
268
|
-
while (true) {
|
|
269
|
-
const item = await reader.read();
|
|
270
|
-
if (item.done) break;
|
|
271
|
-
const take = Math.min(item.value.length, limit - size);
|
|
272
|
-
chunks.push(item.value.slice(0, take));
|
|
273
|
-
size += take;
|
|
274
|
-
if (size >= limit) {
|
|
275
|
-
truncated = true;
|
|
276
|
-
break;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
} finally {
|
|
280
|
-
await reader.cancel();
|
|
281
|
-
}
|
|
282
|
-
return { text: Buffer.concat(chunks).toString("utf8"), truncated };
|
|
283
|
-
}
|
|
284
|
-
};
|
|
285
|
-
async function observeMergeRequest(client, projectId, iid, signal) {
|
|
286
|
-
const mr = await client.getMergeRequest(projectId, iid, signal);
|
|
287
|
-
if (mr.state !== "opened") return { mr, pipeline: null };
|
|
288
|
-
const targetHead = (await client.getBranch(mr.target_project_id, mr.target_branch, signal)).commit.id;
|
|
289
|
-
const associated = (await client.listMergeRequestPipelines(projectId, iid, signal)).sort(
|
|
290
|
-
(a, b) => b.id - a.id
|
|
291
|
-
);
|
|
292
|
-
for (const candidate of associated) {
|
|
293
|
-
const id = candidate.project_id ?? projectId;
|
|
294
|
-
let matches = candidate.sha === mr.sha;
|
|
295
|
-
if (!matches && (candidate.ref === `refs/merge-requests/${iid}/merge` || candidate.sha === mr.merge_commit_sha)) {
|
|
296
|
-
const commit = await client.getCommit(id, candidate.sha, signal);
|
|
297
|
-
matches = commit.parent_ids.includes(mr.sha);
|
|
298
|
-
}
|
|
299
|
-
if (matches)
|
|
300
|
-
return { mr, targetHead, pipeline: await client.getPipeline(id, candidate.id, signal) };
|
|
301
|
-
}
|
|
302
|
-
const candidates = await client.listBranchPipelines(
|
|
303
|
-
mr.source_project_id,
|
|
304
|
-
mr.source_branch,
|
|
305
|
-
mr.sha,
|
|
306
|
-
signal
|
|
307
|
-
);
|
|
308
|
-
const latest = candidates.filter((p) => p.sha === mr.sha && p.ref === mr.source_branch && p.source === "push").sort((a, b) => b.id - a.id)[0];
|
|
309
|
-
return {
|
|
310
|
-
mr,
|
|
311
|
-
targetHead,
|
|
312
|
-
pipeline: latest ? await client.getPipeline(mr.source_project_id, latest.id, signal) : null
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// src/capability.ts
|
|
317
|
-
import {
|
|
318
|
-
createCapabilityToken
|
|
319
|
-
} from "@leitwerk-dev/process-sdk";
|
|
320
|
-
var gitlabIntegration = createCapabilityToken(
|
|
321
|
-
"@leitwerk-dev/gitlab.integration"
|
|
322
|
-
);
|
|
323
|
-
function gitlabRepositoryCredentials(profile, projects) {
|
|
324
|
-
return projects.map((project) => ({
|
|
325
|
-
projectKey: project.key,
|
|
326
|
-
kind: "git_https",
|
|
327
|
-
credentialRef: `gitlab:${profile}`
|
|
328
|
-
}));
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
// src/external.ts
|
|
332
|
-
import {
|
|
333
|
-
createExternalSourcePollReporter
|
|
334
|
-
} from "@leitwerk-dev/process-sdk";
|
|
335
|
-
import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
336
|
-
var GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
|
|
337
|
-
function pendingGitLabFeedback(items, afterId, since) {
|
|
338
|
-
const start = since ? Date.parse(since) : 0;
|
|
339
|
-
return items.filter((item) => item.id > afterId && Date.parse(item.createdAt) >= start);
|
|
340
|
-
}
|
|
341
|
-
function gitLabFeedbackReadyAt(items, quietPeriodMs) {
|
|
342
|
-
return items.length ? Math.max(...items.map((item) => Date.parse(item.createdAt))) + quietPeriodMs : null;
|
|
343
|
-
}
|
|
344
|
-
var observationKey = ({ mr, pipeline, targetHead }) => JSON.stringify([
|
|
345
|
-
mr.state,
|
|
346
|
-
mr.sha,
|
|
347
|
-
[...mr.labels].sort(),
|
|
348
|
-
pipeline?.project_id,
|
|
349
|
-
pipeline?.id,
|
|
350
|
-
pipeline?.status,
|
|
351
|
-
mr.source_project_id,
|
|
352
|
-
mr.source_branch,
|
|
353
|
-
mr.target_project_id,
|
|
354
|
-
mr.target_branch,
|
|
355
|
-
targetHead,
|
|
356
|
-
mr.has_conflicts,
|
|
357
|
-
mr.merge_status,
|
|
358
|
-
mr.detailed_merge_status
|
|
359
|
-
]);
|
|
360
|
-
var gitlabExternal = {
|
|
361
|
-
/** @public */
|
|
362
|
-
mergeRequest(resolve) {
|
|
363
|
-
return {
|
|
364
|
-
kind: GITLAB_MR_KIND,
|
|
365
|
-
label: "GitLab merge request",
|
|
366
|
-
description: "Observe MR state, source/target heads, mergeability and revision-correlated CI",
|
|
367
|
-
config: {},
|
|
368
|
-
inputMode: "none",
|
|
369
|
-
resolve
|
|
370
|
-
};
|
|
371
|
-
}
|
|
372
|
-
};
|
|
373
|
-
function createGitLabProvider(deps, integration, options = {}) {
|
|
374
|
-
const schedule = /* @__PURE__ */ new Map();
|
|
375
|
-
const now = options.now ?? Date.now;
|
|
376
|
-
return deps.polling.create({
|
|
377
|
-
id: "gitlab",
|
|
378
|
-
pollInterval: () => "5s",
|
|
379
|
-
isEnabled: () => true,
|
|
380
|
-
defaultIntervalMs: 5e3,
|
|
381
|
-
async pollOnce() {
|
|
382
|
-
const result = emptyPollResult();
|
|
383
|
-
const report = createExternalSourcePollReporter(deps.externalSources, result);
|
|
384
|
-
await report.poll(GITLAB_MR_KIND, async (armed) => {
|
|
385
|
-
const c = armed.resolved;
|
|
386
|
-
if (!c || typeof c.profile !== "string" || !Number.isInteger(c.projectId) || !Number.isInteger(c.iid))
|
|
387
|
-
throw new Error("Invalid GitLab external source");
|
|
388
|
-
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
389
|
-
const previous = schedule.get(key);
|
|
390
|
-
if (previous && previous.at > now()) return;
|
|
391
|
-
try {
|
|
392
|
-
const observation = await observeMergeRequest(
|
|
393
|
-
integration.client(c.profile),
|
|
394
|
-
c.projectId,
|
|
395
|
-
c.iid
|
|
396
|
-
);
|
|
397
|
-
const observedKey = observationKey(observation);
|
|
398
|
-
const feedback = c.feedback && observation.mr.state === "opened" ? pendingGitLabFeedback(
|
|
399
|
-
await integration.client(c.profile).listMergeRequestFeedback(c.projectId, c.iid),
|
|
400
|
-
c.feedback.afterId,
|
|
401
|
-
c.feedback.since
|
|
402
|
-
) : [];
|
|
403
|
-
const feedbackReadyAt = gitLabFeedbackReadyAt(
|
|
404
|
-
feedback,
|
|
405
|
-
c.feedback?.quietPeriodMs ?? 12e4
|
|
406
|
-
);
|
|
407
|
-
const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
|
|
408
|
-
await report.observe(armed, {
|
|
409
|
-
observation: {
|
|
410
|
-
summary: `${observation.mr.state} \xB7 ${observation.pipeline?.status ?? "no current pipeline"}`,
|
|
411
|
-
observedAt: new Date(now()).toISOString(),
|
|
412
|
-
subject: observation.mr.web_url,
|
|
413
|
-
revision: observation.mr.sha
|
|
414
|
-
}
|
|
415
|
-
});
|
|
416
|
-
if (observedKey !== c.afterKey || feedbackReady || c.wakeAt !== void 0 && c.wakeAt <= now())
|
|
417
|
-
await report.fire(
|
|
418
|
-
armed,
|
|
419
|
-
{ ...observation },
|
|
420
|
-
`${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`
|
|
421
|
-
);
|
|
422
|
-
schedule.set(key, {
|
|
423
|
-
at: now() + parseDurationMs(c.pollInterval ?? "30s", 3e4),
|
|
424
|
-
failures: 0
|
|
425
|
-
});
|
|
426
|
-
} catch (error) {
|
|
427
|
-
const failures = (previous?.failures ?? 0) + 1;
|
|
428
|
-
schedule.set(key, {
|
|
429
|
-
at: now() + Math.min(3e5, 3e4 * 2 ** Math.min(failures - 1, 4)),
|
|
430
|
-
failures
|
|
431
|
-
});
|
|
432
|
-
await report.observe(armed, {
|
|
433
|
-
refreshError: error instanceof Error ? error.message : "GitLab observation unavailable"
|
|
434
|
-
});
|
|
435
|
-
throw error;
|
|
436
|
-
}
|
|
437
|
-
});
|
|
438
|
-
return result;
|
|
439
|
-
}
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
// src/tools.ts
|
|
444
|
-
import { createHash } from "crypto";
|
|
445
|
-
import {
|
|
446
|
-
numberArg,
|
|
447
|
-
projectParameters,
|
|
448
|
-
stringArg
|
|
449
|
-
} from "@leitwerk-dev/process-sdk";
|
|
450
|
-
async function existingRemote(read) {
|
|
451
|
-
try {
|
|
452
|
-
return await read();
|
|
453
|
-
} catch (error) {
|
|
454
|
-
if (error instanceof GitLabError && error.status === 404) return null;
|
|
455
|
-
throw error;
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
function resolveGitLabBinding(ctx) {
|
|
459
|
-
if (!ctx.project || ctx.project.instanceId !== ctx.process.id)
|
|
460
|
-
throw new Error("An authorized GitLab process project is required");
|
|
461
|
-
const binding = ctx.project.metadata?.gitlab;
|
|
462
|
-
if (!binding || typeof binding.profile !== "string" || typeof binding.projectId !== "number" || typeof binding.iid !== "number")
|
|
463
|
-
throw new Error("Invalid GitLab project binding");
|
|
464
|
-
return { profile: binding.profile, projectId: binding.projectId, iid: binding.iid };
|
|
465
|
-
}
|
|
466
|
-
async function ensureGitLabComment(input) {
|
|
467
|
-
const { client, writes, instanceId, projectId, iid, writeKey, signal } = input;
|
|
468
|
-
const identity = [client.baseUrl, projectId, iid, instanceId, writeKey];
|
|
469
|
-
if (input.discussionId) identity.push(input.discussionId);
|
|
470
|
-
const digest = createHash("sha256").update(JSON.stringify(identity)).digest("hex");
|
|
471
|
-
const marker = `<!-- leitwerk:gitlab:${digest} -->`;
|
|
472
|
-
const find = async () => {
|
|
473
|
-
const notes = input.discussionId ? (await client.getDiscussion(projectId, iid, input.discussionId, signal)).notes : await client.listNotes(projectId, iid, signal);
|
|
474
|
-
return notes.find((note) => note.body.includes(marker));
|
|
475
|
-
};
|
|
476
|
-
await writes.ensure(
|
|
477
|
-
{ writeType: "gitlab.comment", dedupKey: digest },
|
|
478
|
-
{
|
|
479
|
-
reconcile: () => existingRemote(async () => await find() ?? null),
|
|
480
|
-
execute: () => {
|
|
481
|
-
const body = `${input.body}
|
|
482
|
-
|
|
483
|
-
${marker}`;
|
|
484
|
-
return input.discussionId ? client.replyToDiscussion(projectId, iid, input.discussionId, body, signal) : client.addNote(projectId, iid, body, signal);
|
|
485
|
-
},
|
|
486
|
-
toMetadata: (note) => ({ projectId, iid, noteId: note.id, marker })
|
|
487
|
-
}
|
|
488
|
-
);
|
|
489
|
-
return { marker };
|
|
490
|
-
}
|
|
491
|
-
async function ensureGitLabSeenReaction(input) {
|
|
492
|
-
const { client, writes, instanceId, projectId, iid, noteId, signal } = input;
|
|
493
|
-
const digest = createHash("sha256").update(JSON.stringify([client.baseUrl, projectId, iid, instanceId, "eyes", noteId])).digest("hex");
|
|
494
|
-
await writes.ensure(
|
|
495
|
-
{ writeType: "gitlab.reaction", dedupKey: digest },
|
|
496
|
-
{
|
|
497
|
-
reconcile: () => existingRemote(async () => {
|
|
498
|
-
const identity = await client.resolveGitIdentity(signal);
|
|
499
|
-
return (await client.listNoteReactions(projectId, iid, noteId, signal)).find(
|
|
500
|
-
(reaction) => reaction.name === "eyes" && reaction.user.username === identity.username
|
|
501
|
-
) ?? null;
|
|
502
|
-
}),
|
|
503
|
-
execute: () => client.addNoteReaction(projectId, iid, noteId, "eyes", signal),
|
|
504
|
-
toMetadata: (reaction) => ({ projectId, iid, noteId, reactionId: reaction.id, name: "eyes" })
|
|
505
|
-
}
|
|
506
|
-
);
|
|
507
|
-
}
|
|
508
|
-
function registerGitLabTools(api, integration) {
|
|
509
|
-
for (const [name, description, required] of [
|
|
510
|
-
["gitlab_observe_merge_request", "Read the current MR source revision and its latest CI", []],
|
|
511
|
-
["gitlab_get_changes", "Read the MR changes", []],
|
|
512
|
-
["gitlab_get_identity", "Resolve the authenticated GitLab bot Git identity", []],
|
|
513
|
-
["gitlab_list_failed_jobs", "Read failed jobs from an MR-associated pipeline", ["pipelineId"]],
|
|
514
|
-
[
|
|
515
|
-
"gitlab_get_job_trace",
|
|
516
|
-
"Read a bounded trace from a failed MR pipeline job",
|
|
517
|
-
["pipelineId", "jobId"]
|
|
518
|
-
],
|
|
519
|
-
["gitlab_comment", "Post a retry-safe MR comment", ["body", "writeKey"]],
|
|
520
|
-
[
|
|
521
|
-
"gitlab_reply",
|
|
522
|
-
"Post a retry-safe reply in an MR discussion",
|
|
523
|
-
["body", "writeKey", "discussionId"]
|
|
524
|
-
]
|
|
525
|
-
]) {
|
|
526
|
-
api.tool({
|
|
527
|
-
name,
|
|
528
|
-
description,
|
|
529
|
-
parameters: projectParameters(
|
|
530
|
-
{
|
|
531
|
-
pipelineId: { type: "integer" },
|
|
532
|
-
jobId: { type: "integer" },
|
|
533
|
-
maxBytes: { type: "integer" },
|
|
534
|
-
body: { type: "string" },
|
|
535
|
-
writeKey: { type: "string" },
|
|
536
|
-
discussionId: { type: "string" }
|
|
537
|
-
},
|
|
538
|
-
[...required]
|
|
539
|
-
),
|
|
540
|
-
async execute(ctx, args) {
|
|
541
|
-
const b = resolveGitLabBinding(ctx);
|
|
542
|
-
const client = integration.client(b.profile);
|
|
543
|
-
if (name === "gitlab_observe_merge_request")
|
|
544
|
-
return observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
545
|
-
if (name === "gitlab_get_changes") return client.getChanges(b.projectId, b.iid, ctx.signal);
|
|
546
|
-
if (name === "gitlab_get_identity") return client.resolveGitIdentity(ctx.signal);
|
|
547
|
-
if (name === "gitlab_comment" || name === "gitlab_reply")
|
|
548
|
-
return ensureGitLabComment({
|
|
549
|
-
client,
|
|
550
|
-
writes: ctx.externalWrites,
|
|
551
|
-
instanceId: ctx.process.id,
|
|
552
|
-
projectId: b.projectId,
|
|
553
|
-
iid: b.iid,
|
|
554
|
-
writeKey: stringArg(args, "writeKey"),
|
|
555
|
-
body: stringArg(args, "body"),
|
|
556
|
-
...name === "gitlab_reply" ? { discussionId: stringArg(args, "discussionId") } : {},
|
|
557
|
-
signal: ctx.signal
|
|
558
|
-
});
|
|
559
|
-
const observation = await observeMergeRequest(client, b.projectId, b.iid, ctx.signal);
|
|
560
|
-
if (!observation.pipeline || observation.pipeline.id !== numberArg(args, "pipelineId"))
|
|
561
|
-
throw new Error("Pipeline is not current for the authorized MR");
|
|
562
|
-
const jobs = await client.listFailedJobs(
|
|
563
|
-
observation.pipeline.project_id,
|
|
564
|
-
observation.pipeline.id,
|
|
565
|
-
ctx.signal
|
|
566
|
-
);
|
|
567
|
-
if (name === "gitlab_list_failed_jobs") return jobs;
|
|
568
|
-
const job = jobs.find((job2) => job2.id === numberArg(args, "jobId"));
|
|
569
|
-
if (!job) throw new Error("Job is not a failed job of the authorized MR pipeline");
|
|
570
|
-
return client.getJobTrace(
|
|
571
|
-
observation.pipeline.project_id,
|
|
572
|
-
job.id,
|
|
573
|
-
typeof args.maxBytes === "number" ? args.maxBytes : void 0,
|
|
574
|
-
ctx.signal
|
|
575
|
-
);
|
|
576
|
-
}
|
|
577
|
-
});
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
// src/setup.ts
|
|
582
|
-
import { coreHostCapabilities } from "@leitwerk-dev/process-sdk";
|
|
583
|
-
function setupGitLabIntegration(api, integration, options = {}) {
|
|
584
|
-
api.provide(gitlabIntegration, integration);
|
|
585
|
-
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
586
|
-
if (!deps || Array.isArray(deps)) return;
|
|
587
|
-
registerGitLabTools(api, integration);
|
|
588
|
-
return createGitLabProvider(deps, integration, options);
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
export {
|
|
592
|
-
parseGitLabProfiles,
|
|
593
|
-
GitLabClient,
|
|
594
|
-
observeMergeRequest,
|
|
595
|
-
gitlabIntegration,
|
|
596
|
-
gitlabRepositoryCredentials,
|
|
597
|
-
pendingGitLabFeedback,
|
|
598
|
-
gitLabFeedbackReadyAt,
|
|
599
|
-
observationKey,
|
|
600
|
-
gitlabExternal,
|
|
601
|
-
resolveGitLabBinding,
|
|
602
|
-
ensureGitLabSeenReaction,
|
|
603
|
-
setupGitLabIntegration
|
|
604
|
-
};
|
|
605
|
-
//# sourceMappingURL=chunk-64FNBSKH.js.map
|