plugin-git-manager 1.2.26 → 1.2.28

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 (108) hide show
  1. package/README.md +133 -108
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +3 -3
  5. package/client.js +1 -1
  6. package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
  7. package/dist/client/900.a48beac7e2ebee7d.js +10 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
  10. package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
  11. package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
  12. package/dist/client-v2/900.e6155002a9c97e7f.js +10 -0
  13. package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
  14. package/dist/client-v2/index.js +1 -1
  15. package/dist/externalVersion.js +9 -8
  16. package/dist/locale/en-US.json +307 -297
  17. package/dist/locale/vi-VN.json +295 -292
  18. package/dist/locale/zh-CN.json +61 -51
  19. package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
  20. package/dist/node_modules/simple-git/package.json +1 -1
  21. package/dist/node_modules/zod/index.cjs +1 -1
  22. package/dist/node_modules/zod/package.json +1 -1
  23. package/dist/server/actions/git-actions.js +90 -36
  24. package/dist/server/actions/gitlab-api.js +4 -2
  25. package/dist/server/actions/poller.js +5 -2
  26. package/dist/server/actions/review.js +20 -10
  27. package/dist/server/plugin.js +6 -4
  28. package/dist/server/poller.js +46 -45
  29. package/dist/server/request-method-policy.js +75 -0
  30. package/dist/server/services/registry-content-service.js +23 -10
  31. package/dist/server/utils/get-repo-account.js +3 -2
  32. package/dist/server/utils/url-security.js +24 -0
  33. package/package.json +61 -43
  34. package/server.d.ts +2 -2
  35. package/server.js +1 -1
  36. package/src/client/__tests__/RunReviewButton.test.tsx +73 -0
  37. package/src/client/ai-context.tsx +114 -114
  38. package/src/client/components/AIEmployeeSelect.tsx +63 -63
  39. package/src/client/components/CommitHistory.tsx +374 -374
  40. package/src/client/components/FileExplorer.tsx +386 -386
  41. package/src/client/components/GitAccounts.tsx +179 -179
  42. package/src/client/components/GitManagerSettings.tsx +160 -160
  43. package/src/client/components/GitOperations.tsx +220 -220
  44. package/src/client/components/LLMModelSelect.tsx +63 -63
  45. package/src/client/components/LLMServiceSelect.tsx +58 -58
  46. package/src/client/components/MarkdownView.tsx +80 -80
  47. package/src/client/components/MergeRequests.tsx +790 -790
  48. package/src/client/components/PollingStatus.tsx +225 -225
  49. package/src/client/components/RepositoryConfig.tsx +335 -335
  50. package/src/client/components/RepositoryPermissions.tsx +123 -123
  51. package/src/client/components/ReviewFlows.tsx +303 -303
  52. package/src/client/components/ReviewHistory.tsx +566 -566
  53. package/src/client/components/RunReviewButton.tsx +63 -55
  54. package/src/client/context/GitManagerContext.tsx +92 -92
  55. package/src/client/index.tsx +91 -82
  56. package/src/client/locale.ts +9 -9
  57. package/src/client/promptTemplates.ts +31 -31
  58. package/src/client-v2/ai-context.tsx +99 -0
  59. package/src/client-v2/components/SubtreeSplits.tsx +547 -547
  60. package/src/client-v2/index.tsx +1 -1
  61. package/src/client-v2/locale.ts +8 -8
  62. package/src/client-v2/plugin.tsx +67 -39
  63. package/src/index.ts +2 -2
  64. package/src/locale/en-US.json +307 -297
  65. package/src/locale/vi-VN.json +295 -292
  66. package/src/locale/zh-CN.json +61 -51
  67. package/src/server/__tests__/git-actions.test.ts +24 -24
  68. package/src/server/__tests__/git-security.test.ts +170 -0
  69. package/src/server/__tests__/plugin-url-security.test.ts +17 -17
  70. package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
  71. package/src/server/__tests__/poller.test.ts +37 -37
  72. package/src/server/__tests__/repository-access.test.ts +752 -752
  73. package/src/server/__tests__/review.test.ts +137 -137
  74. package/src/server/__tests__/role-permissions.test.ts +147 -147
  75. package/src/server/__tests__/smoke.test.ts +139 -17
  76. package/src/server/__tests__/subtree.test.ts +85 -85
  77. package/src/server/actions/git-actions.ts +540 -480
  78. package/src/server/actions/gitlab-api.ts +422 -411
  79. package/src/server/actions/poller.ts +39 -27
  80. package/src/server/actions/review.ts +1388 -1369
  81. package/src/server/actions/role-permissions.ts +321 -321
  82. package/src/server/actions/subtree.ts +508 -508
  83. package/src/server/ai-tools.ts +319 -319
  84. package/src/server/collections/gitAccounts.ts +56 -56
  85. package/src/server/collections/gitCodeReviews.ts +199 -199
  86. package/src/server/collections/gitRepositories.ts +87 -87
  87. package/src/server/collections/gitReviewFlows.ts +108 -108
  88. package/src/server/collections/gitSubtreeConfigs.ts +38 -38
  89. package/src/server/collections/gitSubtreeRuns.ts +30 -30
  90. package/src/server/index.ts +2 -2
  91. package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
  92. package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
  93. package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
  94. package/src/server/plugin.ts +372 -361
  95. package/src/server/poller.ts +351 -352
  96. package/src/server/repository-access.ts +773 -773
  97. package/src/server/request-method-policy.ts +55 -0
  98. package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
  99. package/src/server/services/registry-content-service.ts +33 -11
  100. package/src/server/utils/__tests__/redact.test.ts +56 -56
  101. package/src/server/utils/__tests__/url-security.test.ts +85 -85
  102. package/src/server/utils/get-repo-account.ts +51 -41
  103. package/src/server/utils/gitlab-url.ts +38 -38
  104. package/src/server/utils/redact.ts +87 -87
  105. package/src/server/utils/url-security.ts +128 -95
  106. package/dist/client/900.acf7d1fa22f95e71.js +0 -10
  107. package/dist/client-v2/434.7a27051db18526c0.js +0 -10
  108. package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
@@ -1,411 +1,422 @@
1
- import { Context } from '@nocobase/actions';
2
- import { getEffectiveActionParams } from '../repository-access';
3
- import { parseGitLabProject } from '../utils/gitlab-url';
4
- import { getRepoAccount } from '../utils/get-repo-account';
5
-
6
- async function gitlabFetch(apiBase: string, endpoint: string, pat: string, params?: Record<string, any>) {
7
- const url = new URL(`${apiBase}${endpoint}`);
8
- if (params) {
9
- Object.entries(params).forEach(([key, value]) => {
10
- if (value !== undefined && value !== null && value !== '') {
11
- url.searchParams.set(key, String(value));
12
- }
13
- });
14
- }
15
-
16
- const response = await fetch(url.toString(), {
17
- headers: {
18
- 'PRIVATE-TOKEN': pat,
19
- Accept: 'application/json',
20
- },
21
- });
22
-
23
- if (!response.ok) {
24
- const body = await response.text().catch(() => '');
25
- throw new Error(`GitLab API error ${response.status}: ${body}`);
26
- }
27
-
28
- // Extract pagination info from response headers
29
- const totalPages = response.headers.get('x-total-pages');
30
- const total = response.headers.get('x-total');
31
-
32
- const data = await response.json();
33
- return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
34
- }
35
-
36
- async function getRepoApiContext(ctx: Context) {
37
- // Fix for POST requests where data might be in ctx.request.body
38
- const params = getEffectiveActionParams(ctx);
39
- const { repositoryId } = params;
40
-
41
- const repo = await ctx.db.getRepository('gitRepositories').findOne({
42
- filterByTk: repositoryId,
43
- });
44
- if (!repo) {
45
- ctx.throw(404, 'Repository not found');
46
- }
47
-
48
- const account = await getRepoAccount(ctx.db, repo);
49
- const pat = account?.pat || '';
50
- const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
51
- const isGitHub = account?.provider === 'github' || repoUrl.includes('github.com');
52
- const { apiBase, encodedProject, projectPath } = parseGitLabProject(repoUrl);
53
- return { repo, pat, apiBase, encodedProject, projectPath, isGitHub };
54
- }
55
-
56
- async function githubFetch(endpoint: string, pat: string, params?: Record<string, any>) {
57
- const url = new URL(`https://api.github.com${endpoint}`);
58
- if (params) {
59
- Object.entries(params).forEach(([key, value]) => {
60
- if (value !== undefined && value !== null && value !== '') {
61
- url.searchParams.set(key, String(value));
62
- }
63
- });
64
- }
65
-
66
- const headers: any = {
67
- Accept: 'application/vnd.github.v3+json',
68
- };
69
- if (pat) {
70
- headers['Authorization'] = `Bearer ${pat}`;
71
- }
72
-
73
- const response = await fetch(url.toString(), { headers });
74
-
75
- if (!response.ok) {
76
- const body = await response.text().catch(() => '');
77
- throw new Error(`GitHub API error ${response.status}: ${body}`);
78
- }
79
-
80
- const linkHeader = response.headers.get('link');
81
- let totalPages = null;
82
- if (linkHeader) {
83
- const lastLink = linkHeader.split(',').find((s) => s.includes('rel="last"'));
84
- if (lastLink) {
85
- const match = lastLink.match(/page=(\d+)/);
86
- if (match) totalPages = parseInt(match[1], 10);
87
- }
88
- }
89
-
90
- const data = await response.json();
91
- return { data, totalPages, total: null };
92
- }
93
-
94
- export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
95
- const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
96
- // Merge params from query and body
97
- const params = getEffectiveActionParams(ctx);
98
- const { state = 'opened', search, page = 1, perPage = 20, orderBy = 'updated_at', sort = 'desc' } = params;
99
-
100
- let result;
101
- let items;
102
-
103
- if (isGitHub) {
104
- // Map GitLab state to GitHub state. `merged` requires fetching `closed`
105
- // and filtering client-side, since GitHub has no dedicated state.
106
- const ghState = state === 'opened' ? 'open' : state === 'closed' ? 'closed' : state === 'merged' ? 'closed' : 'all';
107
- result = await githubFetch(`/repos/${projectPath}/pulls`, pat, {
108
- state: ghState,
109
- page,
110
- per_page: Math.min(parseInt(String(perPage), 10) || 20, 100),
111
- sort: orderBy === 'updated_at' ? 'updated' : 'created',
112
- direction: sort,
113
- });
114
-
115
- let pullRequests = result.data || [];
116
- // If state is merged, filter the closed ones that are merged.
117
- // Pagination metadata from GitHub still reflects the unfiltered `closed`
118
- // total — null it out to avoid misleading the UI.
119
- let mergedFilterApplied = false;
120
- if (state === 'merged') {
121
- pullRequests = pullRequests.filter((pr: any) => pr.merged_at);
122
- mergedFilterApplied = true;
123
- }
124
- if (mergedFilterApplied) {
125
- result.totalPages = null;
126
- result.total = null;
127
- }
128
-
129
- items = pullRequests.map((pr: any) => ({
130
- id: pr.id,
131
- iid: pr.number,
132
- title: pr.title,
133
- description: pr.body,
134
- state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
135
- sourceBranch: pr.head?.ref,
136
- targetBranch: pr.base?.ref,
137
- author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
138
- assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
139
- reviewers: (pr.requested_reviewers || []).map((r: any) => ({
140
- name: r.login,
141
- username: r.login,
142
- avatarUrl: r.avatar_url,
143
- })),
144
- labels: (pr.labels || []).map((l: any) => l.name),
145
- draft: pr.draft || false,
146
- mergedBy: null, // Not returned by the PR list endpoint
147
- mergedAt: pr.merged_at,
148
- createdAt: pr.created_at,
149
- updatedAt: pr.updated_at,
150
- userNotesCount: typeof pr.comments === 'number' ? pr.comments : 0,
151
- upvotes: 0,
152
- downvotes: 0,
153
- webUrl: pr.html_url,
154
- // GitHub's PR list does not include mergeability info — surface as
155
- // `null` (unknown) so the UI doesn't render a misleading "no conflicts".
156
- hasConflicts: null,
157
- changesCount: typeof pr.changed_files === 'number' ? pr.changed_files : null,
158
- }));
159
- } else {
160
- if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
161
- result = await gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests`, pat, {
162
- state,
163
- search,
164
- page,
165
- per_page: Math.min(parseInt(String(perPage), 10) || 20, 100),
166
- order_by: orderBy,
167
- sort,
168
- });
169
-
170
- items = (result.data || []).map((mr: any) => ({
171
- id: mr.id,
172
- iid: mr.iid,
173
- title: mr.title,
174
- description: mr.description,
175
- state: mr.state,
176
- sourceBranch: mr.source_branch,
177
- targetBranch: mr.target_branch,
178
- author: mr.author
179
- ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
180
- : null,
181
- assignees: (mr.assignees || []).map((a: any) => ({
182
- name: a.name,
183
- username: a.username,
184
- avatarUrl: a.avatar_url,
185
- })),
186
- reviewers: (mr.reviewers || []).map((r: any) => ({
187
- name: r.name,
188
- username: r.username,
189
- avatarUrl: r.avatar_url,
190
- })),
191
- labels: mr.labels || [],
192
- draft: mr.draft || mr.work_in_progress || false,
193
- mergedBy: mr.merged_by ? { name: mr.merged_by.name, username: mr.merged_by.username } : null,
194
- mergedAt: mr.merged_at,
195
- createdAt: mr.created_at,
196
- updatedAt: mr.updated_at,
197
- userNotesCount: mr.user_notes_count || 0,
198
- upvotes: mr.upvotes || 0,
199
- downvotes: mr.downvotes || 0,
200
- webUrl: mr.web_url,
201
- hasConflicts: mr.has_conflicts || false,
202
- changesCount: mr.changes_count,
203
- }));
204
- }
205
-
206
- ctx.body = {
207
- success: true,
208
- data: items,
209
- pagination: {
210
- page: parseInt(String(page), 10),
211
- perPage: parseInt(String(perPage), 10),
212
- total: result.total,
213
- totalPages: result.totalPages,
214
- },
215
- };
216
- await next();
217
- }
218
-
219
- export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>) {
220
- const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
221
- const params = getEffectiveActionParams(ctx);
222
- const { mrIid } = params;
223
-
224
- if (!mrIid) {
225
- ctx.throw(400, 'mrIid is required');
226
- }
227
-
228
- let data;
229
- if (isGitHub) {
230
- const [prResult, filesResult] = await Promise.all([
231
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
232
- githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat).catch(() => ({ data: [] })),
233
- ]);
234
-
235
- const pr = prResult.data;
236
- const changes = (filesResult.data || []).map((c: any) => ({
237
- oldPath: c.previous_filename || c.filename,
238
- newPath: c.filename,
239
- newFile: c.status === 'added',
240
- renamedFile: c.status === 'renamed',
241
- deletedFile: c.status === 'removed',
242
- diff: c.patch,
243
- }));
244
-
245
- data = {
246
- id: pr.id,
247
- iid: pr.number,
248
- title: pr.title,
249
- description: pr.body,
250
- state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
251
- sourceBranch: pr.head?.ref,
252
- targetBranch: pr.base?.ref,
253
- author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
254
- assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
255
- reviewers: (pr.requested_reviewers || []).map((r: any) => ({
256
- name: r.login,
257
- username: r.login,
258
- avatarUrl: r.avatar_url,
259
- })),
260
- labels: (pr.labels || []).map((l: any) => l.name),
261
- draft: pr.draft || false,
262
- createdAt: pr.created_at,
263
- updatedAt: pr.updated_at,
264
- mergedBy: pr.merged_by ? { name: pr.merged_by.login, username: pr.merged_by.login } : null,
265
- mergedAt: pr.merged_at,
266
- closedBy: null, // Not always readily available on GitHub without extra call
267
- closedAt: pr.closed_at,
268
- webUrl: pr.html_url,
269
- // `mergeable_state === 'unknown'` when GitHub is still computing — surface
270
- // `null` instead of `false` so the UI can distinguish "no conflicts" from
271
- // "not yet known".
272
- hasConflicts:
273
- pr.mergeable_state === 'dirty'
274
- ? true
275
- : pr.mergeable_state === 'unknown' || pr.mergeable === null
276
- ? null
277
- : false,
278
- diffStats: {
279
- additions: typeof pr.additions === 'number' ? pr.additions : null,
280
- deletions: typeof pr.deletions === 'number' ? pr.deletions : null,
281
- changedFiles: typeof pr.changed_files === 'number' ? pr.changed_files : null,
282
- },
283
- changes,
284
- };
285
- } else {
286
- if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
287
- const [mrResult, changesResult] = await Promise.all([
288
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
289
- gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat).catch(() => ({
290
- data: {},
291
- })),
292
- ]);
293
-
294
- const mr = mrResult.data;
295
- const changes = (changesResult.data?.changes || []).map((c: any) => ({
296
- oldPath: c.old_path,
297
- newPath: c.new_path,
298
- newFile: c.new_file,
299
- renamedFile: c.renamed_file,
300
- deletedFile: c.deleted_file,
301
- diff: c.diff,
302
- }));
303
-
304
- data = {
305
- id: mr.id,
306
- iid: mr.iid,
307
- title: mr.title,
308
- description: mr.description,
309
- state: mr.state,
310
- sourceBranch: mr.source_branch,
311
- targetBranch: mr.target_branch,
312
- author: mr.author
313
- ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
314
- : null,
315
- assignees: (mr.assignees || []).map((a: any) => ({
316
- name: a.name,
317
- username: a.username,
318
- avatarUrl: a.avatar_url,
319
- })),
320
- reviewers: (mr.reviewers || []).map((r: any) => ({
321
- name: r.name,
322
- username: r.username,
323
- avatarUrl: r.avatar_url,
324
- })),
325
- labels: mr.labels || [],
326
- draft: mr.draft || mr.work_in_progress || false,
327
- createdAt: mr.created_at,
328
- updatedAt: mr.updated_at,
329
- mergedBy: mr.merged_by ? { name: mr.merged_by.name, username: mr.merged_by.username } : null,
330
- mergedAt: mr.merged_at,
331
- closedBy: mr.closed_by ? { name: mr.closed_by.name, username: mr.closed_by.username } : null,
332
- closedAt: mr.closed_at,
333
- webUrl: mr.web_url,
334
- hasConflicts: mr.has_conflicts || false,
335
- diffStats: {
336
- additions: mr.changes_count ? parseInt(mr.changes_count, 10) : null,
337
- },
338
- changes,
339
- };
340
- }
341
-
342
- ctx.body = {
343
- success: true,
344
- data,
345
- };
346
- await next();
347
- }
348
-
349
- export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
350
- const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
351
- const params = getEffectiveActionParams(ctx);
352
- const { mrIid, page = 1, perPage = 50 } = params;
353
-
354
- if (!mrIid) {
355
- ctx.throw(400, 'mrIid is required');
356
- }
357
-
358
- let notes = [];
359
- const pagination = {
360
- page: parseInt(String(page), 10),
361
- perPage: parseInt(String(perPage), 10),
362
- total: null,
363
- totalPages: null as any,
364
- };
365
-
366
- if (isGitHub) {
367
- const result = await githubFetch(`/repos/${projectPath}/issues/${mrIid}/comments`, pat, {
368
- page,
369
- per_page: Math.min(parseInt(String(perPage), 10) || 50, 100),
370
- });
371
-
372
- notes = (result.data || []).map((n: any) => ({
373
- id: n.id,
374
- body: n.body,
375
- author: n.user ? { name: n.user.login, username: n.user.login, avatarUrl: n.user.avatar_url } : null,
376
- createdAt: n.created_at,
377
- updatedAt: n.updated_at,
378
- resolvable: false,
379
- resolved: false,
380
- }));
381
- pagination.totalPages = result.totalPages;
382
- } else {
383
- if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
384
- const result = await gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/notes`, pat, {
385
- page,
386
- per_page: Math.min(parseInt(String(perPage), 10) || 50, 100),
387
- sort: 'asc',
388
- });
389
-
390
- notes = (result.data || [])
391
- .filter((n: any) => !n.system) // exclude system notes like "assigned to", "changed milestone"
392
- .map((n: any) => ({
393
- id: n.id,
394
- body: n.body,
395
- author: n.author ? { name: n.author.name, username: n.author.username, avatarUrl: n.author.avatar_url } : null,
396
- createdAt: n.created_at,
397
- updatedAt: n.updated_at,
398
- resolvable: n.resolvable || false,
399
- resolved: n.resolved || false,
400
- }));
401
- pagination.total = result.total;
402
- pagination.totalPages = result.totalPages;
403
- }
404
-
405
- ctx.body = {
406
- success: true,
407
- data: notes,
408
- pagination,
409
- };
410
- await next();
411
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { Context } from '@nocobase/actions';
11
+ import { getEffectiveActionParams } from '../repository-access';
12
+ import { parseGitLabProject } from '../utils/gitlab-url';
13
+ import { getRepoAccount } from '../utils/get-repo-account';
14
+
15
+ async function gitlabFetch(apiBase: string, endpoint: string, pat: string, params?: Record<string, any>) {
16
+ const url = new URL(`${apiBase}${endpoint}`);
17
+ if (params) {
18
+ Object.entries(params).forEach(([key, value]) => {
19
+ if (value !== undefined && value !== null && value !== '') {
20
+ url.searchParams.set(key, String(value));
21
+ }
22
+ });
23
+ }
24
+
25
+ const response = await fetch(url.toString(), {
26
+ redirect: 'error',
27
+ headers: {
28
+ 'PRIVATE-TOKEN': pat,
29
+ Accept: 'application/json',
30
+ },
31
+ });
32
+
33
+ if (!response.ok) {
34
+ const body = await response.text().catch(() => '');
35
+ throw new Error(`GitLab API error ${response.status}: ${body}`);
36
+ }
37
+
38
+ // Extract pagination info from response headers
39
+ const totalPages = response.headers.get('x-total-pages');
40
+ const total = response.headers.get('x-total');
41
+
42
+ const data = await response.json();
43
+ return { data, totalPages: totalPages ? parseInt(totalPages, 10) : null, total: total ? parseInt(total, 10) : null };
44
+ }
45
+
46
+ async function getRepoApiContext(ctx: Context) {
47
+ // Fix for POST requests where data might be in ctx.request.body
48
+ const params = getEffectiveActionParams(ctx);
49
+ const { repositoryId } = params;
50
+ if (typeof repositoryId !== 'string' && typeof repositoryId !== 'number') ctx.throw(400, 'repositoryId is required');
51
+
52
+ const repo = await ctx.db.getRepository('gitRepositories').findOne({
53
+ filterByTk: repositoryId,
54
+ });
55
+ if (!repo) {
56
+ ctx.throw(404, 'Repository not found');
57
+ }
58
+
59
+ const account = await getRepoAccount(ctx.db, repo);
60
+ const pat = account?.pat || '';
61
+ const repoUrl = ((repo.get('repoUrl') as string) || '').trim();
62
+ const isGitHub = account?.provider === 'github' || new URL(repoUrl).hostname === 'github.com';
63
+ const { apiBase, encodedProject, projectPath } = parseGitLabProject(repoUrl);
64
+ return { repo, pat, apiBase, encodedProject, projectPath, isGitHub };
65
+ }
66
+
67
+ async function githubFetch(endpoint: string, pat: string, params?: Record<string, any>) {
68
+ const url = new URL(`https://api.github.com${endpoint}`);
69
+ if (params) {
70
+ Object.entries(params).forEach(([key, value]) => {
71
+ if (value !== undefined && value !== null && value !== '') {
72
+ url.searchParams.set(key, String(value));
73
+ }
74
+ });
75
+ }
76
+
77
+ const headers: any = {
78
+ Accept: 'application/vnd.github.v3+json',
79
+ };
80
+ if (pat) {
81
+ headers['Authorization'] = `Bearer ${pat}`;
82
+ }
83
+
84
+ const response = await fetch(url.toString(), { headers, redirect: 'error' });
85
+
86
+ if (!response.ok) {
87
+ const body = await response.text().catch(() => '');
88
+ throw new Error(`GitHub API error ${response.status}: ${body}`);
89
+ }
90
+
91
+ const linkHeader = response.headers.get('link');
92
+ let totalPages = null;
93
+ if (linkHeader) {
94
+ const lastLink = linkHeader.split(',').find((s) => s.includes('rel="last"'));
95
+ if (lastLink) {
96
+ const match = lastLink.match(/page=(\d+)/);
97
+ if (match) totalPages = parseInt(match[1], 10);
98
+ }
99
+ }
100
+
101
+ const data = await response.json();
102
+ return { data, totalPages, total: null };
103
+ }
104
+
105
+ export async function mergeRequests(ctx: Context, next: () => Promise<void>) {
106
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
107
+ // Merge params from query and body
108
+ const params = getEffectiveActionParams(ctx);
109
+ const { state = 'opened', search, page = 1, perPage = 20, orderBy = 'updated_at', sort = 'desc' } = params;
110
+
111
+ let result;
112
+ let items;
113
+
114
+ if (isGitHub) {
115
+ // Map GitLab state to GitHub state. `merged` requires fetching `closed`
116
+ // and filtering client-side, since GitHub has no dedicated state.
117
+ const ghState = state === 'opened' ? 'open' : state === 'closed' ? 'closed' : state === 'merged' ? 'closed' : 'all';
118
+ result = await githubFetch(`/repos/${projectPath}/pulls`, pat, {
119
+ state: ghState,
120
+ page,
121
+ per_page: Math.min(parseInt(String(perPage), 10) || 20, 100),
122
+ sort: orderBy === 'updated_at' ? 'updated' : 'created',
123
+ direction: sort,
124
+ });
125
+
126
+ let pullRequests = result.data || [];
127
+ // If state is merged, filter the closed ones that are merged.
128
+ // Pagination metadata from GitHub still reflects the unfiltered `closed`
129
+ // total — null it out to avoid misleading the UI.
130
+ let mergedFilterApplied = false;
131
+ if (state === 'merged') {
132
+ pullRequests = pullRequests.filter((pr: any) => pr.merged_at);
133
+ mergedFilterApplied = true;
134
+ }
135
+ if (mergedFilterApplied) {
136
+ result.totalPages = null;
137
+ result.total = null;
138
+ }
139
+
140
+ items = pullRequests.map((pr: any) => ({
141
+ id: pr.id,
142
+ iid: pr.number,
143
+ title: pr.title,
144
+ description: pr.body,
145
+ state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
146
+ sourceBranch: pr.head?.ref,
147
+ targetBranch: pr.base?.ref,
148
+ author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
149
+ assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
150
+ reviewers: (pr.requested_reviewers || []).map((r: any) => ({
151
+ name: r.login,
152
+ username: r.login,
153
+ avatarUrl: r.avatar_url,
154
+ })),
155
+ labels: (pr.labels || []).map((l: any) => l.name),
156
+ draft: pr.draft || false,
157
+ mergedBy: null, // Not returned by the PR list endpoint
158
+ mergedAt: pr.merged_at,
159
+ createdAt: pr.created_at,
160
+ updatedAt: pr.updated_at,
161
+ userNotesCount: typeof pr.comments === 'number' ? pr.comments : 0,
162
+ upvotes: 0,
163
+ downvotes: 0,
164
+ webUrl: pr.html_url,
165
+ // GitHub's PR list does not include mergeability info — surface as
166
+ // `null` (unknown) so the UI doesn't render a misleading "no conflicts".
167
+ hasConflicts: null,
168
+ changesCount: typeof pr.changed_files === 'number' ? pr.changed_files : null,
169
+ }));
170
+ } else {
171
+ if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
172
+ result = await gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests`, pat, {
173
+ state,
174
+ search,
175
+ page,
176
+ per_page: Math.min(parseInt(String(perPage), 10) || 20, 100),
177
+ order_by: orderBy,
178
+ sort,
179
+ });
180
+
181
+ items = (result.data || []).map((mr: any) => ({
182
+ id: mr.id,
183
+ iid: mr.iid,
184
+ title: mr.title,
185
+ description: mr.description,
186
+ state: mr.state,
187
+ sourceBranch: mr.source_branch,
188
+ targetBranch: mr.target_branch,
189
+ author: mr.author
190
+ ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
191
+ : null,
192
+ assignees: (mr.assignees || []).map((a: any) => ({
193
+ name: a.name,
194
+ username: a.username,
195
+ avatarUrl: a.avatar_url,
196
+ })),
197
+ reviewers: (mr.reviewers || []).map((r: any) => ({
198
+ name: r.name,
199
+ username: r.username,
200
+ avatarUrl: r.avatar_url,
201
+ })),
202
+ labels: mr.labels || [],
203
+ draft: mr.draft || mr.work_in_progress || false,
204
+ mergedBy: mr.merged_by ? { name: mr.merged_by.name, username: mr.merged_by.username } : null,
205
+ mergedAt: mr.merged_at,
206
+ createdAt: mr.created_at,
207
+ updatedAt: mr.updated_at,
208
+ userNotesCount: mr.user_notes_count || 0,
209
+ upvotes: mr.upvotes || 0,
210
+ downvotes: mr.downvotes || 0,
211
+ webUrl: mr.web_url,
212
+ hasConflicts: mr.has_conflicts || false,
213
+ changesCount: mr.changes_count,
214
+ }));
215
+ }
216
+
217
+ ctx.body = {
218
+ success: true,
219
+ data: items,
220
+ pagination: {
221
+ page: parseInt(String(page), 10),
222
+ perPage: parseInt(String(perPage), 10),
223
+ total: result.total,
224
+ totalPages: result.totalPages,
225
+ },
226
+ };
227
+ await next();
228
+ }
229
+
230
+ export async function mergeRequestDetail(ctx: Context, next: () => Promise<void>) {
231
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
232
+ const params = getEffectiveActionParams(ctx);
233
+ const { mrIid } = params;
234
+
235
+ if (!mrIid) {
236
+ ctx.throw(400, 'mrIid is required');
237
+ }
238
+
239
+ let data;
240
+ if (isGitHub) {
241
+ const [prResult, filesResult] = await Promise.all([
242
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}`, pat),
243
+ githubFetch(`/repos/${projectPath}/pulls/${mrIid}/files`, pat).catch(() => ({ data: [] })),
244
+ ]);
245
+
246
+ const pr = prResult.data;
247
+ const changes = (filesResult.data || []).map((c: any) => ({
248
+ oldPath: c.previous_filename || c.filename,
249
+ newPath: c.filename,
250
+ newFile: c.status === 'added',
251
+ renamedFile: c.status === 'renamed',
252
+ deletedFile: c.status === 'removed',
253
+ diff: c.patch,
254
+ }));
255
+
256
+ data = {
257
+ id: pr.id,
258
+ iid: pr.number,
259
+ title: pr.title,
260
+ description: pr.body,
261
+ state: pr.state === 'open' ? 'opened' : pr.merged_at ? 'merged' : 'closed',
262
+ sourceBranch: pr.head?.ref,
263
+ targetBranch: pr.base?.ref,
264
+ author: pr.user ? { name: pr.user.login, username: pr.user.login, avatarUrl: pr.user.avatar_url } : null,
265
+ assignees: (pr.assignees || []).map((a: any) => ({ name: a.login, username: a.login, avatarUrl: a.avatar_url })),
266
+ reviewers: (pr.requested_reviewers || []).map((r: any) => ({
267
+ name: r.login,
268
+ username: r.login,
269
+ avatarUrl: r.avatar_url,
270
+ })),
271
+ labels: (pr.labels || []).map((l: any) => l.name),
272
+ draft: pr.draft || false,
273
+ createdAt: pr.created_at,
274
+ updatedAt: pr.updated_at,
275
+ mergedBy: pr.merged_by ? { name: pr.merged_by.login, username: pr.merged_by.login } : null,
276
+ mergedAt: pr.merged_at,
277
+ closedBy: null, // Not always readily available on GitHub without extra call
278
+ closedAt: pr.closed_at,
279
+ webUrl: pr.html_url,
280
+ // `mergeable_state === 'unknown'` when GitHub is still computing — surface
281
+ // `null` instead of `false` so the UI can distinguish "no conflicts" from
282
+ // "not yet known".
283
+ hasConflicts:
284
+ pr.mergeable_state === 'dirty'
285
+ ? true
286
+ : pr.mergeable_state === 'unknown' || pr.mergeable === null
287
+ ? null
288
+ : false,
289
+ diffStats: {
290
+ additions: typeof pr.additions === 'number' ? pr.additions : null,
291
+ deletions: typeof pr.deletions === 'number' ? pr.deletions : null,
292
+ changedFiles: typeof pr.changed_files === 'number' ? pr.changed_files : null,
293
+ },
294
+ changes,
295
+ };
296
+ } else {
297
+ if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
298
+ const [mrResult, changesResult] = await Promise.all([
299
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}`, pat),
300
+ gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/changes`, pat).catch(() => ({
301
+ data: {},
302
+ })),
303
+ ]);
304
+
305
+ const mr = mrResult.data;
306
+ const changes = (changesResult.data?.changes || []).map((c: any) => ({
307
+ oldPath: c.old_path,
308
+ newPath: c.new_path,
309
+ newFile: c.new_file,
310
+ renamedFile: c.renamed_file,
311
+ deletedFile: c.deleted_file,
312
+ diff: c.diff,
313
+ }));
314
+
315
+ data = {
316
+ id: mr.id,
317
+ iid: mr.iid,
318
+ title: mr.title,
319
+ description: mr.description,
320
+ state: mr.state,
321
+ sourceBranch: mr.source_branch,
322
+ targetBranch: mr.target_branch,
323
+ author: mr.author
324
+ ? { name: mr.author.name, username: mr.author.username, avatarUrl: mr.author.avatar_url }
325
+ : null,
326
+ assignees: (mr.assignees || []).map((a: any) => ({
327
+ name: a.name,
328
+ username: a.username,
329
+ avatarUrl: a.avatar_url,
330
+ })),
331
+ reviewers: (mr.reviewers || []).map((r: any) => ({
332
+ name: r.name,
333
+ username: r.username,
334
+ avatarUrl: r.avatar_url,
335
+ })),
336
+ labels: mr.labels || [],
337
+ draft: mr.draft || mr.work_in_progress || false,
338
+ createdAt: mr.created_at,
339
+ updatedAt: mr.updated_at,
340
+ mergedBy: mr.merged_by ? { name: mr.merged_by.name, username: mr.merged_by.username } : null,
341
+ mergedAt: mr.merged_at,
342
+ closedBy: mr.closed_by ? { name: mr.closed_by.name, username: mr.closed_by.username } : null,
343
+ closedAt: mr.closed_at,
344
+ webUrl: mr.web_url,
345
+ hasConflicts: mr.has_conflicts || false,
346
+ diffStats: {
347
+ additions: mr.changes_count ? parseInt(mr.changes_count, 10) : null,
348
+ },
349
+ changes,
350
+ };
351
+ }
352
+
353
+ ctx.body = {
354
+ success: true,
355
+ data,
356
+ };
357
+ await next();
358
+ }
359
+
360
+ export async function mergeRequestNotes(ctx: Context, next: () => Promise<void>) {
361
+ const { pat, apiBase, encodedProject, projectPath, isGitHub } = await getRepoApiContext(ctx);
362
+ const params = getEffectiveActionParams(ctx);
363
+ const { mrIid, page = 1, perPage = 50 } = params;
364
+
365
+ if (!mrIid) {
366
+ ctx.throw(400, 'mrIid is required');
367
+ }
368
+
369
+ let notes = [];
370
+ const pagination = {
371
+ page: parseInt(String(page), 10),
372
+ perPage: parseInt(String(perPage), 10),
373
+ total: null,
374
+ totalPages: null as any,
375
+ };
376
+
377
+ if (isGitHub) {
378
+ const result = await githubFetch(`/repos/${projectPath}/issues/${mrIid}/comments`, pat, {
379
+ page,
380
+ per_page: Math.min(parseInt(String(perPage), 10) || 50, 100),
381
+ });
382
+
383
+ notes = (result.data || []).map((n: any) => ({
384
+ id: n.id,
385
+ body: n.body,
386
+ author: n.user ? { name: n.user.login, username: n.user.login, avatarUrl: n.user.avatar_url } : null,
387
+ createdAt: n.created_at,
388
+ updatedAt: n.updated_at,
389
+ resolvable: false,
390
+ resolved: false,
391
+ }));
392
+ pagination.totalPages = result.totalPages;
393
+ } else {
394
+ if (!pat) ctx.throw(400, 'Personal Access Token is required for GitLab API access');
395
+ const result = await gitlabFetch(apiBase, `/projects/${encodedProject}/merge_requests/${mrIid}/notes`, pat, {
396
+ page,
397
+ per_page: Math.min(parseInt(String(perPage), 10) || 50, 100),
398
+ sort: 'asc',
399
+ });
400
+
401
+ notes = (result.data || [])
402
+ .filter((n: any) => !n.system) // exclude system notes like "assigned to", "changed milestone"
403
+ .map((n: any) => ({
404
+ id: n.id,
405
+ body: n.body,
406
+ author: n.author ? { name: n.author.name, username: n.author.username, avatarUrl: n.author.avatar_url } : null,
407
+ createdAt: n.created_at,
408
+ updatedAt: n.updated_at,
409
+ resolvable: n.resolvable || false,
410
+ resolved: n.resolved || false,
411
+ }));
412
+ pagination.total = result.total;
413
+ pagination.totalPages = result.totalPages;
414
+ }
415
+
416
+ ctx.body = {
417
+ success: true,
418
+ data: notes,
419
+ pagination,
420
+ };
421
+ await next();
422
+ }