@open-cr-agent/vcs-gitlab 0.7.0 → 0.10.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.
package/dist/adapter.js CHANGED
@@ -1,6 +1,7 @@
1
- import { errorMessage, OcraError } from "@open-cr-agent/core";
1
+ import { errorMessage, OcraError, } from "@open-cr-agent/core";
2
2
  import { gitlabSuggestion, PlatformReview, } from "@open-cr-agent/vcs-platform";
3
3
  import { DEVELOPER, GitLabApiError, } from "./client.js";
4
+ import { gitlabDiscussion } from "./discussion.js";
4
5
  // A GitLab merge request as ocra's review conversation (vcs-platform).
5
6
  export class GitLabAdapter extends PlatformReview {
6
7
  constructor(options) {
@@ -132,6 +133,15 @@ class GitLabPlatform {
132
133
  resolveThread(id) {
133
134
  return this.options.api.resolveDiscussion(this.options.iid, id);
134
135
  }
136
+ discussion(ref) {
137
+ return gitlabDiscussion(this.options.api, this.options.iid, ref);
138
+ }
139
+ async reply(discussion, body) {
140
+ if (discussion.replyTo === undefined)
141
+ await this.options.api.createNote(this.options.iid, body);
142
+ else
143
+ await this.options.api.replyToDiscussion(this.options.iid, discussion.replyTo, body);
144
+ }
135
145
  remember(note) {
136
146
  this.ids.set(note.author.username, note.author.id);
137
147
  if (note.resolved_by)
package/dist/client.d.ts CHANGED
@@ -33,6 +33,10 @@ declare const noteSchema: z.ZodObject<{
33
33
  id: z.ZodNumber;
34
34
  username: z.ZodString;
35
35
  }, z.core.$strip>>>;
36
+ position: z.ZodOptional<z.ZodNullable<z.ZodObject<{
37
+ new_path: z.ZodString;
38
+ new_line: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
39
+ }, z.core.$strip>>>;
36
40
  }, z.core.$strip>;
37
41
  export type Note = z.infer<typeof noteSchema>;
38
42
  declare const discussionSchema: z.ZodObject<{
@@ -53,6 +57,10 @@ declare const discussionSchema: z.ZodObject<{
53
57
  id: z.ZodNumber;
54
58
  username: z.ZodString;
55
59
  }, z.core.$strip>>>;
60
+ position: z.ZodOptional<z.ZodNullable<z.ZodObject<{
61
+ new_path: z.ZodString;
62
+ new_line: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
63
+ }, z.core.$strip>>>;
56
64
  }, z.core.$strip>>;
57
65
  }, z.core.$strip>;
58
66
  export type Discussion = z.infer<typeof discussionSchema>;
@@ -75,6 +83,7 @@ export interface GitLabApiOptions {
75
83
  baseUrl?: string;
76
84
  fetch?: typeof fetch;
77
85
  sleep?: (ms: number) => Promise<void>;
86
+ signal?: AbortSignal;
78
87
  }
79
88
  export declare const DEVELOPER = 30;
80
89
  export declare class GitLabApi {
@@ -94,12 +103,13 @@ export declare class GitLabApi {
94
103
  createNote(iid: number, body: string): Promise<void>;
95
104
  updateNote(iid: number, noteId: number, body: string): Promise<void>;
96
105
  createDiscussion(iid: number, body: string, position: Position): Promise<void>;
106
+ replyToDiscussion(iid: number, discussionId: string, body: string): Promise<void>;
97
107
  resolveDiscussion(iid: number, discussionId: string): Promise<void>;
98
108
  accessLevel(userId: number): Promise<number>;
99
109
  findUser(username: string): Promise<number | undefined>;
100
110
  noteEditors(iid: number): Promise<Map<number, string | undefined>>;
101
111
  private pages;
102
112
  private graphql;
103
- private request;
113
+ request(method: string, path: string, body?: unknown): Promise<unknown>;
104
114
  }
105
115
  export {};
package/dist/client.js CHANGED
@@ -25,6 +25,12 @@ const noteSchema = z.object({
25
25
  resolvable: z.boolean().optional(),
26
26
  resolved: z.boolean().optional(),
27
27
  resolved_by: user.nullable().optional(),
28
+ // On a line of the diff: the file and the new side's line, unset on a
29
+ // removed line.
30
+ position: z
31
+ .object({ new_path: z.string(), new_line: z.number().nullable().optional() })
32
+ .nullable()
33
+ .optional(),
28
34
  });
29
35
  const discussionSchema = z.object({
30
36
  id: z.string(),
@@ -84,6 +90,7 @@ export class GitLabApi {
84
90
  headers: { Accept: "application/json", Authorization: `Bearer ${options.token}` },
85
91
  fetch: options.fetch ?? fetch,
86
92
  sleep: options.sleep,
93
+ signal: options.signal,
87
94
  timeoutMs: () => REQUEST_TIMEOUT_MS,
88
95
  toError: (status, message) => new GitLabApiError(status, message),
89
96
  };
@@ -122,6 +129,9 @@ export class GitLabApi {
122
129
  async createDiscussion(iid, body, position) {
123
130
  await this.request("POST", `/merge_requests/${iid}/discussions`, { body, position });
124
131
  }
132
+ async replyToDiscussion(iid, discussionId, body) {
133
+ await this.request("POST", `/merge_requests/${iid}/discussions/${encodeURIComponent(discussionId)}/notes`, { body });
134
+ }
125
135
  async resolveDiscussion(iid, discussionId) {
126
136
  await this.request("PUT", `/merge_requests/${iid}/discussions/${encodeURIComponent(discussionId)}?resolved=true`);
127
137
  }
@@ -0,0 +1,4 @@
1
+ import { type MentionRef } from "@open-cr-agent/core";
2
+ import type { PlatformDiscussion } from "@open-cr-agent/vcs-platform";
3
+ import type { GitLabApi } from "./client.js";
4
+ export declare function gitlabDiscussion(api: GitLabApi, iid: number, ref: MentionRef): Promise<PlatformDiscussion | undefined>;
@@ -0,0 +1,51 @@
1
+ import { OcraError } from "@open-cr-agent/core";
2
+ // A note on the merge request and the discussion it is in. Every note is in
3
+ // one on GitLab, a comment on the merge request as a whole too, so a reply
4
+ // always goes to its discussion; such a comment is read, as on GitHub,
5
+ // among the merge request's other comments.
6
+ export async function gitlabDiscussion(api, iid, ref) {
7
+ const id = Number(ref.id);
8
+ if (!Number.isSafeInteger(id) || id <= 0)
9
+ return undefined;
10
+ const discussions = await api.listDiscussions(iid);
11
+ const discussion = discussions.find((d) => d.notes.some((n) => n.id === id));
12
+ const conversation = discussion?.individual_note
13
+ ? discussions.filter((d) => d.individual_note || d === discussion)
14
+ : discussion
15
+ ? [discussion]
16
+ : [];
17
+ const notes = conversation
18
+ .flatMap((d) => d.notes)
19
+ .filter((n) => !n.system)
20
+ .sort((a, b) => a.id - b.id);
21
+ const note = notes.find((n) => n.id === id);
22
+ if (!discussion || !note)
23
+ return undefined;
24
+ const editors = await api.noteEditors(iid);
25
+ if (!editors.has(id)) {
26
+ throw new OcraError("VCS_API_FAILED", `GitLab did not say who last edited note ${id}`);
27
+ }
28
+ const editor = editors.get(id);
29
+ const said = (n) => ({ author: n.author.username, body: n.body });
30
+ const at = notes.indexOf(note);
31
+ const position = discussion.individual_note ? undefined : notes[0]?.position;
32
+ return {
33
+ comment: {
34
+ id: String(id),
35
+ author: note.author.username,
36
+ body: note.body,
37
+ ...(editor ? { editor } : {}),
38
+ },
39
+ earlier: notes.slice(0, at).map(said),
40
+ later: notes.slice(at + 1).map(said),
41
+ ...(position
42
+ ? {
43
+ on: {
44
+ path: position.new_path,
45
+ ...(position.new_line ? { line: position.new_line } : {}),
46
+ },
47
+ }
48
+ : {}),
49
+ replyTo: discussion.id,
50
+ };
51
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { GitLabApiError } from "./client.js";
2
2
  export { gitlabPlugin } from "./plugin.js";
3
+ export { proposeOnGitLab } from "./propose.js";
3
4
  export { type GitLabSettings, resolveGitLabTarget } from "./target.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { GitLabApiError } from "./client.js";
2
2
  export { gitlabPlugin } from "./plugin.js";
3
+ export { proposeOnGitLab } from "./propose.js";
3
4
  export { resolveGitLabTarget } from "./target.js";
package/dist/plugin.js CHANGED
@@ -1,4 +1,4 @@
1
- import { changeRequestSchema, codeSourceSchema, commitIdSchema, fetchSchema, historySchema, } from "@open-cr-agent/vcs-platform";
1
+ import { changeRequestSchema, codeSourceSchema, commitIdSchema, fetchSchema, historySchema, signalSchema, } from "@open-cr-agent/vcs-platform";
2
2
  import { z } from "zod";
3
3
  import { GitLabAdapter } from "./adapter.js";
4
4
  import { GitLabApi } from "./client.js";
@@ -9,6 +9,7 @@ const optionsSchema = z.object({
9
9
  token: z.string().min(1),
10
10
  apiUrl: z.string().url().optional(),
11
11
  fetch: fetchSchema.optional(),
12
+ signal: signalSchema.optional(),
12
13
  code: codeSourceSchema,
13
14
  snapshot: changeRequestSchema.extend({ mergeBaseSha: commitIdSchema }).optional(),
14
15
  history: historySchema.optional(),
@@ -22,6 +23,7 @@ export const gitlabPlugin = {
22
23
  token: options.token,
23
24
  ...(options.apiUrl ? { baseUrl: options.apiUrl } : {}),
24
25
  ...(options.fetch ? { fetch: options.fetch } : {}),
26
+ ...(options.signal ? { signal: options.signal } : {}),
25
27
  });
26
28
  return new GitLabAdapter({
27
29
  iid: options.iid,
@@ -0,0 +1,2 @@
1
+ import type { FileProposal, ProposedChange, ProposeOptions } from "@open-cr-agent/vcs-platform";
2
+ export declare function proposeOnGitLab(options: ProposeOptions, proposal: FileProposal): Promise<ProposedChange>;
@@ -0,0 +1,123 @@
1
+ import { setTimeout as wait } from "node:timers/promises";
2
+ import { z } from "zod";
3
+ import { GitLabApiError } from "./client.js";
4
+ import { gitlabApi } from "./target.js";
5
+ const projectSchema = z.object({ default_branch: z.string().min(1) });
6
+ const treeSchema = z.array(z.object({ path: z.string(), type: z.string() }));
7
+ const mergeRequestSchema = z.object({
8
+ iid: z.number(),
9
+ web_url: z.string(),
10
+ state: z.string().optional(),
11
+ merge_status: z.string().optional(),
12
+ head_pipeline: z.object({ id: z.number() }).nullish(),
13
+ merge_when_pipeline_succeeds: z.boolean().optional(),
14
+ });
15
+ const MAX_TREE_PAGES = 10;
16
+ // GitLab makes a new merge request's pipeline and checks its mergeability
17
+ // after answering; these are the waits, in all about 15 seconds, for both.
18
+ const SETTLE_WAITS_MS = [1000, 2000, 3000, 4000, 5000];
19
+ const UNSETTLED = new Set(["unchecked", "checking", "preparing", "cannot_be_merged_recheck"]);
20
+ // One commit on a new branch from the default branch, made through the
21
+ // commits API, so nothing is pushed from the checkout; then a merge request.
22
+ // The token needs the api scope and the Developer role.
23
+ export async function proposeOnGitLab(options, proposal) {
24
+ const warnings = [];
25
+ const { api } = await gitlabApi({ ...options, warn: (message) => warnings.push(message) }, options.repository, "--propose");
26
+ const base = projectSchema.parse(await api.request("GET", "")).default_branch;
27
+ const existing = await existingPaths(api, base, proposal.files.map((f) => f.path));
28
+ await api.request("POST", "/repository/commits", {
29
+ branch: proposal.branch,
30
+ start_branch: base,
31
+ commit_message: proposal.commitMessage,
32
+ actions: proposal.files.map((f) => ({
33
+ action: existing.has(f.path) ? "update" : "create",
34
+ file_path: f.path,
35
+ content: f.content,
36
+ })),
37
+ });
38
+ const created = mergeRequestSchema.parse(await api.request("POST", "/merge_requests", {
39
+ source_branch: proposal.branch,
40
+ target_branch: base,
41
+ title: proposal.title,
42
+ description: proposal.body,
43
+ remove_source_branch: true,
44
+ }));
45
+ const webUrl = created.web_url;
46
+ if (!proposal.autoMerge)
47
+ return { webUrl, merge: "off", warnings };
48
+ const merge = await mergeWhenGreen(api, created.iid, options);
49
+ return { webUrl, merge: merge.merge, warnings: [...warnings, ...merge.warnings] };
50
+ }
51
+ // The paths among `paths` the default branch holds, from one listing of
52
+ // each directory rather than one request per file.
53
+ async function existingPaths(api, ref, paths) {
54
+ const found = new Set();
55
+ const dirs = new Set(paths.map((p) => p.slice(0, Math.max(p.lastIndexOf("/"), 0))));
56
+ for (const dir of dirs) {
57
+ for (let page = 1; page <= MAX_TREE_PAGES; page += 1) {
58
+ const query = `ref=${encodeURIComponent(ref)}&path=${encodeURIComponent(dir)}&per_page=100&page=${page}`;
59
+ let entries;
60
+ try {
61
+ entries = treeSchema.parse(await api.request("GET", `/repository/tree?${query}`));
62
+ }
63
+ catch (error) {
64
+ // A directory the branch does not have yet.
65
+ if (error instanceof GitLabApiError && error.status === 404)
66
+ break;
67
+ throw error;
68
+ }
69
+ for (const entry of entries)
70
+ if (entry.type === "blob")
71
+ found.add(entry.path);
72
+ if (entries.length < 100)
73
+ break;
74
+ }
75
+ }
76
+ return found;
77
+ }
78
+ // Merged when its pipeline succeeds. GitLab merges at once a merge request
79
+ // with no running pipeline, so the request waits for the pipeline a new
80
+ // branch starts; with none after the waits, nothing is required of it.
81
+ async function mergeWhenGreen(api, iid, options) {
82
+ const sleep = options.sleep ?? ((ms) => wait(ms, undefined, { signal: options.signal }));
83
+ let mergeRequest = await settled(api, iid, sleep);
84
+ for (let attempt = 0;; attempt += 1) {
85
+ try {
86
+ const answer = mergeRequestSchema.parse(await api.request("PUT", `/merge_requests/${iid}/merge`, {
87
+ merge_when_pipeline_succeeds: true,
88
+ should_remove_source_branch: true,
89
+ }));
90
+ if (answer.state === "merged")
91
+ return { merge: "merged", warnings: [] };
92
+ if (answer.merge_when_pipeline_succeeds)
93
+ return { merge: "enabled", warnings: [] };
94
+ return unavailable("GitLab neither merged it nor set it to merge when its pipeline succeeds");
95
+ }
96
+ catch (error) {
97
+ if (!(error instanceof GitLabApiError))
98
+ throw error;
99
+ const retry = [405, 422].includes(error.status) && attempt < SETTLE_WAITS_MS.length;
100
+ if (!retry || !UNSETTLED.has(mergeRequest.merge_status ?? "")) {
101
+ return unavailable(error.message);
102
+ }
103
+ await sleep(SETTLE_WAITS_MS[attempt] ?? 0);
104
+ mergeRequest = await get(api, iid);
105
+ }
106
+ }
107
+ }
108
+ async function settled(api, iid, sleep) {
109
+ let mergeRequest = await get(api, iid);
110
+ for (const ms of SETTLE_WAITS_MS) {
111
+ if (mergeRequest.head_pipeline && !UNSETTLED.has(mergeRequest.merge_status ?? ""))
112
+ break;
113
+ await sleep(ms);
114
+ mergeRequest = await get(api, iid);
115
+ }
116
+ return mergeRequest;
117
+ }
118
+ async function get(api, iid) {
119
+ return mergeRequestSchema.parse(await api.request("GET", `/merge_requests/${iid}`));
120
+ }
121
+ function unavailable(reason) {
122
+ return { merge: "unavailable", warnings: [`the merge request is left open: ${reason}`] };
123
+ }
package/dist/target.d.ts CHANGED
@@ -1,3 +1,12 @@
1
1
  import type { PlatformTarget, ResolveTargetOptions } from "@open-cr-agent/vcs-platform";
2
+ import { GitLabApi } from "./client.js";
2
3
  export type GitLabSettings = Record<string, never>;
3
4
  export declare function resolveGitLabTarget(options: ResolveTargetOptions): Promise<PlatformTarget<GitLabSettings>>;
5
+ type ApiOptions = Pick<ResolveTargetOptions, "env" | "origin" | "fetch" | "signal" | "warn">;
6
+ export declare function gitlabApi(options: ApiOptions, named: string | undefined, what: string): Promise<{
7
+ api: GitLabApi;
8
+ project: string;
9
+ token: string;
10
+ apiUrl: string;
11
+ }>;
12
+ export {};
package/dist/target.js CHANGED
@@ -7,20 +7,10 @@ const GITLAB_API = "https://gitlab.com/api/v4";
7
7
  // CI_JOB_TOKEN may not. The project is --project, else CI_PROJECT_ID, else
8
8
  // origin's.
9
9
  export async function resolveGitLabTarget(options) {
10
- const { env, ref } = options;
11
- const token = env.GITLAB_TOKEN;
12
- if (!token) {
13
- throw new OcraError("CONFIG_CREDENTIALS_MISSING", "--mr needs a GitLab token in GITLAB_TOKEN with the api scope and the Developer role: a project access token, or on GitLab.com Free a personal access token of a dedicated account (CI_JOB_TOKEN cannot post comments)");
14
- }
15
- const origin = await options.origin();
16
- const project = ref.repository ?? env.CI_PROJECT_ID ?? gitlabProject(origin);
17
- const apiUrl = gitlabApi(env.CI_API_V4_URL, remoteHost(origin), options.warn);
10
+ const { ref } = options;
11
+ const { api, project, token, apiUrl } = await gitlabApi(options, ref.repository, "--mr");
18
12
  const fetchImpl = options.fetch;
19
- const api = new GitLabApi(project, {
20
- token,
21
- baseUrl: apiUrl,
22
- ...(fetchImpl ? { fetch: fetchImpl } : {}),
23
- });
13
+ const signal = options.signal ? { signal: options.signal } : {};
24
14
  const iid = ref.number;
25
15
  const merge = await api.getMergeRequest(iid);
26
16
  const snapshot = mergeRequestOf(merge);
@@ -39,14 +29,34 @@ export async function resolveGitLabTarget(options) {
39
29
  snapshot,
40
30
  history: local.history,
41
31
  ...(fetchImpl ? { fetch: fetchImpl } : {}),
32
+ ...signal,
42
33
  }),
43
34
  };
44
35
  }
36
+ // The API client for the project named, else CI_PROJECT_ID's, else origin's.
37
+ // `what` is the flag that needs it, for the error without a token.
38
+ export async function gitlabApi(options, named, what) {
39
+ const { env } = options;
40
+ const token = env.GITLAB_TOKEN;
41
+ if (!token) {
42
+ throw new OcraError("CONFIG_CREDENTIALS_MISSING", `${what} needs a GitLab token in GITLAB_TOKEN with the api scope and the Developer role: a project access token, or on GitLab.com Free a personal access token of a dedicated account (CI_JOB_TOKEN cannot post comments)`);
43
+ }
44
+ const origin = await options.origin();
45
+ const project = named ?? env.CI_PROJECT_ID ?? gitlabProject(origin);
46
+ const apiUrl = gitlabApiUrl(env.CI_API_V4_URL, remoteHost(origin), options.warn);
47
+ const api = new GitLabApi(project, {
48
+ token,
49
+ baseUrl: apiUrl,
50
+ ...(options.fetch ? { fetch: options.fetch } : {}),
51
+ ...(options.signal ? { signal: options.signal } : {}),
52
+ });
53
+ return { api, project, token, apiUrl };
54
+ }
45
55
  // Where GITLAB_TOKEN goes: to CI_API_V4_URL, which GitLab CI sets, or else
46
56
  // to gitlab.com, but only when origin is there too or is no remote host. A
47
57
  // token for a self-managed instance must not travel to gitlab.com because
48
58
  // the address was left out.
49
- function gitlabApi(configured, origin, warn) {
59
+ function gitlabApiUrl(configured, origin, warn) {
50
60
  if (configured) {
51
61
  const api = remoteHost(configured);
52
62
  if (api && origin && site(api) !== site(origin)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-cr-agent/vcs-gitlab",
3
- "version": "0.7.0",
3
+ "version": "0.10.0",
4
4
  "description": "GitLab merge request adapter for Open-CR-Agent",
5
5
  "keywords": [
6
6
  "code-review",
@@ -33,9 +33,9 @@
33
33
  "!dist/**/*.map"
34
34
  ],
35
35
  "dependencies": {
36
- "@open-cr-agent/core": "0.7.0",
37
- "@open-cr-agent/vcs-platform": "0.7.0",
38
- "zod": "^4.6.5"
36
+ "@open-cr-agent/core": "0.10.0",
37
+ "@open-cr-agent/vcs-platform": "0.10.0",
38
+ "zod": "^4.6.6"
39
39
  },
40
40
  "publishConfig": {
41
41
  "access": "public"