-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-client.mjs
More file actions
372 lines (345 loc) · 10.3 KB
/
github-client.mjs
File metadata and controls
372 lines (345 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { notionPageMarker } from './mapper.mjs';
const GITHUB_API_BASE = 'https://api.github.com';
const GITHUB_GRAPHQL_ENDPOINT = 'https://api.github.com/graphql';
const GITHUB_API_VERSION = '2022-11-28';
export function createGitHubClient(config, fetchImpl = fetch) {
let projectFieldsPromise;
function headers(extra = {}) {
return {
Authorization: `Bearer ${config.githubToken}`,
Accept: 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': GITHUB_API_VERSION,
...extra,
};
}
async function githubRequest(pathOrUrl, options = {}) {
const url = pathOrUrl.startsWith('http') ? pathOrUrl : `${GITHUB_API_BASE}${pathOrUrl}`;
const response = await fetchImpl(url, {
...options,
headers: headers(options.headers),
});
const bodyText = await response.text();
const body = bodyText ? JSON.parse(bodyText) : {};
if (!response.ok) {
throw new Error(`GitHub API ${response.status}: ${body.message || bodyText}`);
}
return body;
}
async function githubGraphql(query, variables = {}) {
const response = await fetchImpl(GITHUB_GRAPHQL_ENDPOINT, {
method: 'POST',
headers: headers(),
body: JSON.stringify({ query, variables }),
});
const bodyText = await response.text();
const body = bodyText ? JSON.parse(bodyText) : {};
if (!response.ok) {
throw new Error(`GitHub GraphQL API ${response.status}: ${body.message || bodyText}`);
}
if (Array.isArray(body.errors) && body.errors.length > 0) {
throw new Error(`GitHub GraphQL API errors: ${body.errors.map((error) => error.message).join('; ')}`);
}
return body.data || {};
}
async function getProjectFields() {
if (!config.githubProjectId) return new Map();
projectFieldsPromise ||= githubGraphql(PROJECT_FIELDS_QUERY, {
projectId: config.githubProjectId,
}).then((data) => {
const fields = new Map();
for (const field of data.node?.fields?.nodes || []) {
if (!field?.name) continue;
fields.set(field.name, {
id: field.id,
name: field.name,
dataType: field.dataType,
options: field.options || [],
});
}
return fields;
});
return projectFieldsPromise;
}
const repoPath = `/repos/${encodeURIComponent(config.githubOwner)}/${encodeURIComponent(config.githubRepo)}`;
return {
createIssue(issue) {
return githubRequest(`${repoPath}/issues`, {
method: 'POST',
body: JSON.stringify(issue),
});
},
getIssue(number) {
return githubRequest(`${repoPath}/issues/${encodeURIComponent(number)}`);
},
addComment(number, body) {
return githubRequest(`${repoPath}/issues/${encodeURIComponent(number)}/comments`, {
method: 'POST',
body: JSON.stringify({ body }),
});
},
async findIssueByNotionPageId(pageId) {
const q = [
`repo:${config.githubOwner}/${config.githubRepo}`,
'type:issue',
'in:body',
`"${notionPageMarker(pageId)}"`,
].join(' ');
const response = await githubRequest(`/search/issues?q=${encodeURIComponent(q)}`);
return response.items?.[0] || null;
},
async setPriorityLabel(number, selectedLabel, allowedLabels = []) {
for (const label of allowedLabels.filter((candidate) => candidate !== selectedLabel)) {
try {
await githubRequest(`${repoPath}/issues/${encodeURIComponent(number)}/labels/${encodeURIComponent(label)}`, {
method: 'DELETE',
});
} catch (error) {
if (!/GitHub API 404:/.test(error.message)) throw error;
}
}
return githubRequest(`${repoPath}/issues/${encodeURIComponent(number)}/labels`, {
method: 'POST',
body: JSON.stringify({ labels: [selectedLabel] }),
});
},
async ensureProjectItem(issueNodeId) {
if (!config.githubProjectId) return null;
try {
const data = await githubGraphql(ADD_PROJECT_ITEM_MUTATION, {
projectId: config.githubProjectId,
contentId: issueNodeId,
});
return normalizeProjectItem(data.addProjectV2ItemById?.item);
} catch (error) {
if (!/already|exists/i.test(error.message)) throw error;
return this.getProjectItemForIssue(issueNodeId);
}
},
async getProjectItemForIssue(issueNodeId) {
if (!config.githubProjectId) return null;
const data = await githubGraphql(PROJECT_ITEM_FOR_ISSUE_QUERY, {
contentId: issueNodeId,
});
const nodes = data.node?.projectItems?.nodes || [];
const item = nodes.find((node) => node?.project?.id === config.githubProjectId);
return item ? normalizeProjectItem(item) : null;
},
async setProjectItemFields(itemId, values) {
if (!config.githubProjectId || !itemId) return;
const fields = await getProjectFields();
for (const [name, value] of Object.entries(values || {})) {
if (value === '' || value === null || value === undefined) continue;
const field = fields.get(name);
if (!field) throw new Error(`Unknown GitHub Project field: ${name}`);
await githubGraphql(UPDATE_PROJECT_ITEM_FIELD_MUTATION, {
projectId: config.githubProjectId,
itemId,
fieldId: field.id,
value: projectFieldValue(field, value),
});
}
},
};
}
const FIELD_NAME_FRAGMENT = `
field {
... on ProjectV2FieldCommon {
name
}
}
`;
const FIELD_VALUES_SELECTION = `
fieldValues(first: 100) {
nodes {
__typename
... on ProjectV2ItemFieldSingleSelectValue {
${FIELD_NAME_FRAGMENT}
name
}
... on ProjectV2ItemFieldTextValue {
${FIELD_NAME_FRAGMENT}
text
}
... on ProjectV2ItemFieldNumberValue {
${FIELD_NAME_FRAGMENT}
number
}
... on ProjectV2ItemFieldDateValue {
${FIELD_NAME_FRAGMENT}
date
}
... on ProjectV2ItemFieldIterationValue {
${FIELD_NAME_FRAGMENT}
title
startDate
}
... on ProjectV2ItemFieldLabelValue {
${FIELD_NAME_FRAGMENT}
labels(first: 20) {
nodes {
name
}
}
}
... on ProjectV2ItemFieldUserValue {
${FIELD_NAME_FRAGMENT}
users(first: 20) {
nodes {
login
name
}
}
}
... on ProjectV2ItemFieldMilestoneValue {
${FIELD_NAME_FRAGMENT}
milestone {
title
}
}
... on ProjectV2ItemFieldRepositoryValue {
${FIELD_NAME_FRAGMENT}
repository {
nameWithOwner
}
}
}
}
`;
const ADD_PROJECT_ITEM_MUTATION = `
mutation AddProjectItem($projectId: ID!, $contentId: ID!) {
addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
item {
id
fullDatabaseId
}
}
}
`;
const PROJECT_ITEM_FOR_ISSUE_QUERY = `
query ProjectItemForIssue($contentId: ID!) {
node(id: $contentId) {
... on Issue {
projectItems(first: 20) {
nodes {
id
fullDatabaseId
project {
id
}
${FIELD_VALUES_SELECTION}
}
}
}
}
}
`;
const PROJECT_FIELDS_QUERY = `
query ProjectFields($projectId: ID!) {
node(id: $projectId) {
... on ProjectV2 {
fields(first: 50) {
nodes {
__typename
... on ProjectV2Field {
id
name
dataType
}
... on ProjectV2SingleSelectField {
id
name
dataType
options {
id
name
}
}
... on ProjectV2IterationField {
id
name
dataType
}
}
}
}
}
}
`;
const UPDATE_PROJECT_ITEM_FIELD_MUTATION = `
mutation UpdateProjectItemField(
$projectId: ID!,
$itemId: ID!,
$fieldId: ID!,
$value: ProjectV2FieldValue!
) {
updateProjectV2ItemFieldValue(input: {
projectId: $projectId,
itemId: $itemId,
fieldId: $fieldId,
value: $value
}) {
projectV2Item {
id
}
}
}
`;
function normalizeProjectItem(item) {
if (!item) return null;
const fields = {};
for (const value of item.fieldValues?.nodes || []) {
const name = value?.field?.name;
if (!name) continue;
const normalized = normalizeFieldValue(value);
if (normalized !== undefined) fields[name] = normalized;
}
return {
id: item.id,
fullDatabaseId: item.fullDatabaseId,
fields,
};
}
function normalizeFieldValue(value) {
switch (value.__typename) {
case 'ProjectV2ItemFieldSingleSelectValue':
return value.name || '';
case 'ProjectV2ItemFieldTextValue':
return value.text || '';
case 'ProjectV2ItemFieldNumberValue':
return value.number ?? '';
case 'ProjectV2ItemFieldDateValue':
return value.date || '';
case 'ProjectV2ItemFieldIterationValue':
return value.title || value.startDate || '';
case 'ProjectV2ItemFieldLabelValue':
return (value.labels?.nodes || []).map((label) => label.name).filter(Boolean).join(', ');
case 'ProjectV2ItemFieldUserValue':
return (value.users?.nodes || []).map((user) => user.login || user.name).filter(Boolean).join(', ');
case 'ProjectV2ItemFieldMilestoneValue':
return value.milestone?.title || '';
case 'ProjectV2ItemFieldRepositoryValue':
return value.repository?.nameWithOwner || '';
default:
return undefined;
}
}
function projectFieldValue(field, value) {
switch (field.dataType) {
case 'SINGLE_SELECT': {
const option = field.options.find((candidate) => candidate.name === String(value));
if (!option) {
throw new Error(`Unknown option for GitHub Project field ${field.name}: ${value}`);
}
return { singleSelectOptionId: option.id };
}
case 'TEXT':
return { text: String(value) };
case 'DATE':
return { date: String(value) };
case 'NUMBER':
return { number: Number(value) };
default:
throw new Error(`Unsupported GitHub Project field type for ${field.name}: ${field.dataType}`);
}
}