@giantswarm-io/pro 1.11.2 → 1.15.0-rc.2

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.
@@ -31,8 +31,8 @@ export const DEFAULT_BOARD = 'roadmap';
31
31
  * Board registry mapping human-readable keys to project IDs and metadata.
32
32
  */
33
33
  export const BOARDS = {
34
- roadmap: { id: ROADMAP_BOARD_ID, name: 'Roadmap Board' },
35
- customer: { id: CUSTOMER_BOARD_ID, name: 'Customer Board' }
34
+ roadmap: { id: ROADMAP_BOARD_ID, number: 273, name: 'Roadmap Board' },
35
+ customer: { id: CUSTOMER_BOARD_ID, number: 345, name: 'Customer Board' }
36
36
  };
37
37
 
38
38
  /**
@@ -101,6 +101,92 @@ const LIST_ITEMS_OVERVIEW_QUERY = `
101
101
  }
102
102
  `;
103
103
 
104
+ // The fields list_issues reads of each item, shared by the paged read and
105
+ // the read by item ids (LIST_ITEMS_BY_ID_QUERY).
106
+ const LIST_ITEM_SELECTION = `
107
+ id
108
+ fieldValues(first: 100) {
109
+ nodes {
110
+ ... on ProjectV2ItemFieldTextValue {
111
+ text
112
+ field {
113
+ ... on ProjectV2FieldCommon {
114
+ name
115
+ }
116
+ }
117
+ }
118
+ ... on ProjectV2ItemFieldDateValue {
119
+ date
120
+ field {
121
+ ... on ProjectV2FieldCommon {
122
+ name
123
+ }
124
+ }
125
+ }
126
+ ... on ProjectV2ItemFieldSingleSelectValue {
127
+ name
128
+ field {
129
+ ... on ProjectV2FieldCommon {
130
+ name
131
+ }
132
+ }
133
+ }
134
+ ... on ProjectV2ItemFieldIterationValue {
135
+ duration
136
+ iterationId
137
+ startDate
138
+ title
139
+ field {
140
+ ... on ProjectV2FieldCommon {
141
+ name
142
+ }
143
+ }
144
+ }
145
+ ... on ProjectV2ItemFieldMilestoneValue {
146
+ milestone {
147
+ title
148
+ description
149
+ dueOn
150
+ }
151
+ field {
152
+ ... on ProjectV2FieldCommon {
153
+ name
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ content {
160
+ __typename
161
+ ... on Issue {
162
+ title
163
+ number
164
+ url
165
+ state
166
+ createdAt
167
+ updatedAt
168
+ closedAt
169
+ repository {
170
+ nameWithOwner
171
+ isPrivate
172
+ url
173
+ }
174
+ assignees(first: 100) {
175
+ nodes {
176
+ login
177
+ }
178
+ }
179
+ id
180
+ labels(first: 100) {
181
+ nodes {
182
+ id
183
+ name
184
+ }
185
+ }
186
+ }
187
+ }
188
+ `;
189
+
104
190
  // List items in a project
105
191
  const LIST_ITEMS_QUERY = `
106
192
  query GetProjectItems($projectId: ID!, $first: Int!, $after: String, $filterQuery: String) {
@@ -113,87 +199,28 @@ const LIST_ITEMS_QUERY = `
113
199
  hasNextPage
114
200
  startCursor
115
201
  }
202
+ nodes {
203
+ ${LIST_ITEM_SELECTION}
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ `;
210
+
211
+ // The ids of a page of matching items, without their content: a cheap walk
212
+ // of a long listing whose items are then read in parallel by id.
213
+ const LIST_ITEM_IDS_QUERY = `
214
+ query GetProjectItemIds($projectId: ID!, $after: String, $filterQuery: String) {
215
+ node(id: $projectId) {
216
+ ... on ProjectV2 {
217
+ items(first: 100, after: $after, query: $filterQuery) {
218
+ pageInfo {
219
+ endCursor
220
+ hasNextPage
221
+ }
116
222
  nodes {
117
223
  id
118
- fieldValues(first: 100) {
119
- nodes {
120
- ... on ProjectV2ItemFieldTextValue {
121
- text
122
- field {
123
- ... on ProjectV2FieldCommon {
124
- name
125
- }
126
- }
127
- }
128
- ... on ProjectV2ItemFieldDateValue {
129
- date
130
- field {
131
- ... on ProjectV2FieldCommon {
132
- name
133
- }
134
- }
135
- }
136
- ... on ProjectV2ItemFieldSingleSelectValue {
137
- name
138
- field {
139
- ... on ProjectV2FieldCommon {
140
- name
141
- }
142
- }
143
- }
144
- ... on ProjectV2ItemFieldIterationValue {
145
- duration
146
- iterationId
147
- startDate
148
- title
149
- field {
150
- ... on ProjectV2FieldCommon {
151
- name
152
- }
153
- }
154
- }
155
- ... on ProjectV2ItemFieldMilestoneValue {
156
- milestone {
157
- title
158
- description
159
- dueOn
160
- }
161
- field {
162
- ... on ProjectV2FieldCommon {
163
- name
164
- }
165
- }
166
- }
167
- }
168
- }
169
- content {
170
- __typename
171
- ... on Issue {
172
- title
173
- number
174
- url
175
- state
176
- createdAt
177
- updatedAt
178
- closedAt
179
- repository {
180
- nameWithOwner
181
- isPrivate
182
- url
183
- }
184
- assignees(first: 100) {
185
- nodes {
186
- login
187
- }
188
- }
189
- labels(first: 100) {
190
- nodes {
191
- id
192
- name
193
- }
194
- }
195
- }
196
- }
197
224
  }
198
225
  }
199
226
  }
@@ -201,6 +228,17 @@ const LIST_ITEMS_QUERY = `
201
228
  }
202
229
  `;
203
230
 
231
+ // Items by their project item ids, with the same fields as LIST_ITEMS_QUERY
232
+ const LIST_ITEMS_BY_ID_QUERY = `
233
+ query GetProjectItemsById($ids: [ID!]!) {
234
+ nodes(ids: $ids) {
235
+ ... on ProjectV2Item {
236
+ ${LIST_ITEM_SELECTION}
237
+ }
238
+ }
239
+ }
240
+ `;
241
+
204
242
  // List fields in a project
205
243
  const LIST_FIELDS_QUERY = `
206
244
  query ($projectId: ID!, $first: Int!, $after: String) {
@@ -211,7 +249,7 @@ const LIST_FIELDS_QUERY = `
211
249
  __typename
212
250
  ... on ProjectV2Field { id name dataType }
213
251
  ... on ProjectV2SingleSelectField { id name dataType options { id name color description } }
214
- ... on ProjectV2IterationField { id name dataType configuration { duration startDay iterations { id title duration startDate } } }
252
+ ... on ProjectV2IterationField { id name dataType configuration { duration startDay iterations { id title duration startDate } completedIterations { id title duration startDate } } }
215
253
  }
216
254
  pageInfo { endCursor hasNextPage }
217
255
  }
@@ -254,6 +292,30 @@ mutation ClearProjectV2ItemField($projectId: ID!, $itemId: ID!, $fieldId: ID!) {
254
292
  }
255
293
  `;
256
294
 
295
+ // An issue's relation lists: "blocked by", "blocking" and "relates to".
296
+ // get_issue_details reads a short page of each, list_issue_relations a full one.
297
+ const RELATION_FIELDS = ['blockedBy', 'blocking', 'relatesTo'];
298
+ const DETAIL_RELATIONS_PAGE = 50;
299
+ const RELATIONS_PAGE = 100;
300
+ const relationLists = first => RELATION_FIELDS
301
+ .map(field => `${field}(first: ${first}) { totalCount pageInfo { hasNextPage } nodes { number title url state repository { nameWithOwner } } }`)
302
+ .join('\n');
303
+
304
+ // Open dependency counts of list_issues' issues, by issue node ID. Not part of
305
+ // LIST_ITEMS_QUERY: issueDependenciesSummary is non-null, so an error on one
306
+ // issue's summary would null that item's content; here it nulls only its node.
307
+ const DEPENDENCY_COUNTS_PAGE = 100;
308
+ const DEPENDENCY_COUNTS_QUERY = `
309
+ query GetDependencyCounts($ids: [ID!]!) {
310
+ nodes(ids: $ids) {
311
+ ... on Issue {
312
+ id
313
+ issueDependenciesSummary { blockedBy blocking }
314
+ }
315
+ }
316
+ }
317
+ `;
318
+
257
319
  const ISSUE_DETAIL_QUERY = `
258
320
  query($id: ID!) {
259
321
  node(id: $id) {
@@ -306,6 +368,7 @@ const ISSUE_DETAIL_QUERY = `
306
368
  }
307
369
  }
308
370
  content {
371
+ __typename
309
372
  ... on Issue {
310
373
  id
311
374
  title
@@ -404,6 +467,86 @@ const ISSUE_NODE_ID_QUERY = `
404
467
  }
405
468
  `;
406
469
 
470
+ // Issue relations: "blocked by" / "blocking" dependencies and "relates to"
471
+ // links, a full page of each (relationLists).
472
+ const ISSUE_RELATIONS_QUERY = `
473
+ query GetIssueRelations($owner: String!, $repo: String!, $number: Int!) {
474
+ repository(owner: $owner, name: $repo) {
475
+ issue(number: $number) {
476
+ id
477
+ number
478
+ title
479
+ url
480
+ state
481
+ repository { nameWithOwner }
482
+ ${relationLists(RELATIONS_PAGE)}
483
+ }
484
+ }
485
+ }
486
+ `;
487
+
488
+ // The relations of a board item's issue, for get_issue_details. A request of
489
+ // its own: the lists are non-null in GitHub's schema, so an error on a whole
490
+ // list nulls the issue, and that must not cost the rest of the details.
491
+ const ITEM_RELATIONS_QUERY = `
492
+ query GetItemRelations($id: ID!) {
493
+ node(id: $id) {
494
+ ... on ProjectV2Item {
495
+ content {
496
+ __typename
497
+ ... on Issue {
498
+ ${relationLists(DETAIL_RELATIONS_PAGE)}
499
+ }
500
+ }
501
+ }
502
+ }
503
+ }
504
+ `;
505
+
506
+ // Both issues of a relation write, in one request.
507
+ const RELATION_ISSUE_IDS_QUERY = `
508
+ query GetRelationIssueIds($owner: String!, $repo: String!, $number: Int!, $relatedOwner: String!, $relatedRepo: String!, $relatedNumber: Int!) {
509
+ issue: repository(owner: $owner, name: $repo) {
510
+ issue(number: $number) { id }
511
+ }
512
+ related: repository(owner: $relatedOwner, name: $relatedRepo) {
513
+ issue(number: $relatedNumber) { id }
514
+ }
515
+ }
516
+ `;
517
+
518
+ const ADD_BLOCKED_BY_MUTATION = `
519
+ mutation AddBlockedBy($issueId: ID!, $blockingIssueId: ID!) {
520
+ addBlockedBy(input: { issueId: $issueId, blockingIssueId: $blockingIssueId }) {
521
+ issue { id }
522
+ }
523
+ }
524
+ `;
525
+
526
+ const REMOVE_BLOCKED_BY_MUTATION = `
527
+ mutation RemoveBlockedBy($issueId: ID!, $blockingIssueId: ID!) {
528
+ removeBlockedBy(input: { issueId: $issueId, blockingIssueId: $blockingIssueId }) {
529
+ issue { id }
530
+ }
531
+ }
532
+ `;
533
+
534
+ const ADD_RELATES_TO_MUTATION = `
535
+ mutation AddRelatesTo($issueId: ID!, $relatedIssueId: ID!) {
536
+ addRelatesTo(input: { issueId: $issueId, relatedIssueId: $relatedIssueId }) {
537
+ issue { id }
538
+ }
539
+ }
540
+ `;
541
+
542
+ const REMOVE_RELATES_TO_MUTATION = `
543
+ mutation RemoveRelatesTo($issueId: ID!, $relatedIssueId: ID!) {
544
+ removeRelatesTo(input: { issueId: $issueId, relatedIssueId: $relatedIssueId }) {
545
+ issue { id }
546
+ }
547
+ }
548
+ `;
549
+
407
550
  const USER_ID_QUERY = `
408
551
  query GetUserNodeId($login: String!) {
409
552
  user(login: $login) {
@@ -412,6 +555,30 @@ const USER_ID_QUERY = `
412
555
  }
413
556
  `;
414
557
 
558
+ // Single item lookup by its project item ID: the board it belongs to and the
559
+ // issue behind it, so writes can name a missing or misplaced item.
560
+ const BOARD_ITEM_QUERY = `
561
+ query GetBoardItem($itemId: ID!) {
562
+ node(id: $itemId) {
563
+ ... on ProjectV2Item {
564
+ id
565
+ project {
566
+ id
567
+ number
568
+ }
569
+ content {
570
+ ... on Issue {
571
+ number
572
+ repository {
573
+ nameWithOwner
574
+ }
575
+ }
576
+ }
577
+ }
578
+ }
579
+ }
580
+ `;
581
+
415
582
  // Batched lookup: resolve a list of ProjectV2Item IDs to their underlying
416
583
  // issue's node ID, repository + number in a single round trip, using GitHub's
417
584
  // root-level `nodes(ids:)` query. The response array is in the same order
@@ -486,6 +653,8 @@ const ADD_COMMENT_MUTATION = `
486
653
  export {
487
654
  REPO_ID_QUERY,
488
655
  LIST_ITEMS_QUERY,
656
+ LIST_ITEM_IDS_QUERY,
657
+ LIST_ITEMS_BY_ID_QUERY,
489
658
  LIST_ITEMS_OVERVIEW_QUERY,
490
659
  LIST_FIELDS_QUERY,
491
660
  UPDATE_ITEM_FIELD_MUTATION,
@@ -495,8 +664,21 @@ export {
495
664
  ADD_ITEM_TO_PROJECT_MUTATION,
496
665
  ARCHIVE_ITEM_MUTATION,
497
666
  ISSUE_NODE_ID_QUERY,
667
+ ISSUE_RELATIONS_QUERY,
668
+ ITEM_RELATIONS_QUERY,
669
+ RELATION_ISSUE_IDS_QUERY,
670
+ RELATION_FIELDS,
671
+ DETAIL_RELATIONS_PAGE,
672
+ DEPENDENCY_COUNTS_QUERY,
673
+ DEPENDENCY_COUNTS_PAGE,
674
+ RELATIONS_PAGE,
675
+ ADD_BLOCKED_BY_MUTATION,
676
+ REMOVE_BLOCKED_BY_MUTATION,
677
+ ADD_RELATES_TO_MUTATION,
678
+ REMOVE_RELATES_TO_MUTATION,
498
679
  USER_ID_QUERY,
499
680
  ITEM_ISSUE_REFS_QUERY,
681
+ BOARD_ITEM_QUERY,
500
682
  CLOSE_ISSUE_MUTATION,
501
683
  REOPEN_ISSUE_MUTATION,
502
684
  ADD_COMMENT_MUTATION
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Issue Relations Core Module
3
+ *
4
+ * Plain functions for GitHub's issue relations besides parent/child
5
+ * (sub-issues.js): "blocked by" / "blocking" dependencies and "relates to"
6
+ * links. GitHub exposes them through GraphQL only, by issue node ID, and
7
+ * across repositories.
8
+ *
9
+ * All functions take explicit { owner, repo, issue_number } targets plus an
10
+ * optional per-request token (falls back to GITHUB_API_TOKEN).
11
+ */
12
+
13
+ import { graphQLWithAuth, withPartialData } from './api.js';
14
+ import { logger } from './logger.js';
15
+ import {
16
+ ISSUE_RELATIONS_QUERY,
17
+ ITEM_RELATIONS_QUERY,
18
+ RELATION_ISSUE_IDS_QUERY,
19
+ RELATION_FIELDS,
20
+ DEPENDENCY_COUNTS_QUERY,
21
+ DEPENDENCY_COUNTS_PAGE,
22
+ ADD_BLOCKED_BY_MUTATION,
23
+ REMOVE_BLOCKED_BY_MUTATION,
24
+ ADD_RELATES_TO_MUTATION,
25
+ REMOVE_RELATES_TO_MUTATION
26
+ } from './project.js';
27
+
28
+ /**
29
+ * The relations a caller can set, read from the issue it names:
30
+ * - blocked_by: the related issue blocks the issue
31
+ * - blocking: the issue blocks the related issue (blocked_by, reversed)
32
+ * - relates_to: the two issues are related
33
+ */
34
+ export const RELATION_TYPES = ['blocked_by', 'blocking', 'relates_to'];
35
+
36
+ /**
37
+ * Whether a GraphQL error lies inside a relation list: a related issue the
38
+ * token cannot read, or one that was deleted. It costs that issue, not the
39
+ * answer.
40
+ */
41
+ export { RELATION_FIELDS };
42
+
43
+ export const inRelationList = error => Boolean(error.path?.some(p => RELATION_FIELDS.includes(p)));
44
+
45
+ /**
46
+ * Whether a GraphQL error is on a whole relation list (the list itself, its
47
+ * totalCount or pageInfo), not on one issue in it.
48
+ */
49
+ const onRelationList = error => {
50
+ const at = error.path?.findIndex(p => RELATION_FIELDS.includes(p)) ?? -1;
51
+ return at >= 0 && error.path[at + 1] !== 'nodes';
52
+ };
53
+
54
+ /**
55
+ * Compact one related issue from a relation connection node.
56
+ * @param {Object} node - Issue node ({ number, title, url, state, repository })
57
+ * @returns {{ number: number, title: string, url: string, state: string, repository: string|null }}
58
+ * - the shape of a sub-issue in sub-issues.js: lowercase state, `repository` as owner/name
59
+ */
60
+ export function compactRelatedIssue(node) {
61
+ return {
62
+ number: node.number,
63
+ title: node.title,
64
+ url: node.url,
65
+ state: node.state?.toLowerCase(),
66
+ repository: node.repository?.nameWithOwner ?? null
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Compact a relation connection to its issues. `truncated` and `totalCount`
72
+ * flag a connection with a next page. `hidden` counts the issues the caller
73
+ * cannot see: nodes read as null (no access, deleted) and, on a last page,
74
+ * the issues totalCount counts that GitHub left out of the nodes.
75
+ * @param {{ totalCount?: number, pageInfo?: { hasNextPage: boolean }, nodes?: Array }} [connection]
76
+ * @returns {{ issues: Array, hidden?: number, truncated?: true, totalCount?: number }}
77
+ */
78
+ export function compactRelation(connection) {
79
+ const nodes = connection?.nodes ?? [];
80
+ const relation = { issues: nodes.filter(Boolean).map(compactRelatedIssue) };
81
+ const totalCount = connection?.totalCount ?? nodes.length;
82
+ const truncated = Boolean(connection?.pageInfo?.hasNextPage);
83
+ const left = truncated ? 0 : Math.max(totalCount - nodes.length, 0);
84
+ const hidden = nodes.length - relation.issues.length + left;
85
+ if (hidden > 0) relation.hidden = hidden;
86
+ if (truncated) Object.assign(relation, { truncated: true, totalCount });
87
+ return relation;
88
+ }
89
+
90
+ /**
91
+ * The error to report when an issue's relations could not be read at all:
92
+ * the one on a whole relation list, which nulls the issue, rather than one
93
+ * on an issue inside a list.
94
+ * @param {Array} errors - GraphQL errors
95
+ * @returns {Object|undefined}
96
+ */
97
+ const relationListError = errors => errors.find(onRelationList) ?? errors[0];
98
+
99
+ /** GitHub's answer for a missing repository or issue of the ones named. */
100
+ const isNotFound = error => error.type === 'NOT_FOUND';
101
+ /** The same, for the repository/issue a query is rooted at (`repository`, `issue`, `related`). */
102
+ const isRootNotFound = error => isNotFound(error) && (error.path?.length ?? 0) <= 2;
103
+
104
+ const notFound = ({ owner, repo, issue_number }) =>
105
+ new Error(`Issue ${owner}/${repo}#${issue_number} not found or not accessible`);
106
+
107
+ /**
108
+ * List an issue's relations (a full page of each kind: RELATIONS_PAGE).
109
+ * @param {{ owner: string, repo: string, issue_number: number }} target
110
+ * @param {string} [token] - Optional per-request GitHub token
111
+ * @returns {Promise<{ issue: Object, blockedBy: Object, blocking: Object, relatesTo: Object }>}
112
+ */
113
+ export async function listIssueRelations({ owner, repo, issue_number }, token) {
114
+ // A missing issue is named below; an unreadable related issue is left out
115
+ // of its list and counted as hidden.
116
+ const { data, errors } = await withPartialData(
117
+ graphQLWithAuth(ISSUE_RELATIONS_QUERY, { owner, repo, number: issue_number }, token),
118
+ error => isRootNotFound(error) || inRelationList(error)
119
+ );
120
+ const issue = data?.repository?.issue;
121
+ if (!issue) {
122
+ // An error on a whole relation list nulls the issue too (the lists are
123
+ // non-null); that is no missing issue, so its message is passed on.
124
+ const other = relationListError(errors.filter(e => !isRootNotFound(e)));
125
+ throw other ? Object.assign(new Error(other.message), { errors }) : notFound({ owner, repo, issue_number });
126
+ }
127
+ if (errors.length > 0) {
128
+ logger.warn('Issue relations partly unreadable', { owner, repo, issue_number, errors: errors.map(e => e.message) });
129
+ }
130
+ return {
131
+ issue: compactRelatedIssue(issue),
132
+ blockedBy: compactRelation(issue.blockedBy),
133
+ blocking: compactRelation(issue.blocking),
134
+ relatesTo: compactRelation(issue.relatesTo)
135
+ };
136
+ }
137
+
138
+ /**
139
+ * The relations of a board item's issue (a short page of each), or null when
140
+ * the item holds no issue (a pull request, a draft). An error on a whole
141
+ * relation list is thrown; an unreadable related issue is counted as hidden.
142
+ * @param {string} itemId - The project item ID
143
+ * @param {string} [token] - Optional per-request GitHub token
144
+ * @returns {Promise<{ blockedBy: Object, blocking: Object, relatesTo: Object }|null>}
145
+ */
146
+ export async function getItemRelations(itemId, token) {
147
+ const { data, errors } = await withPartialData(
148
+ graphQLWithAuth(ITEM_RELATIONS_QUERY, { id: itemId }, token),
149
+ inRelationList
150
+ );
151
+ const content = data?.node?.content;
152
+ if (!content) {
153
+ if (errors.length > 0) throw Object.assign(new Error(relationListError(errors).message), { errors });
154
+ return null;
155
+ }
156
+ if (content.__typename !== 'Issue') return null;
157
+ if (errors.length > 0) {
158
+ logger.warn('Issue relations partly unreadable', { itemId, errors: errors.map(e => e.message) });
159
+ }
160
+ return {
161
+ blockedBy: compactRelation(content.blockedBy),
162
+ blocking: compactRelation(content.blocking),
163
+ relatesTo: compactRelation(content.relatesTo)
164
+ };
165
+ }
166
+
167
+ /** Dependency-count pages requested at once. */
168
+ const DEPENDENCY_COUNTS_CONCURRENCY = 4;
169
+
170
+ /**
171
+ * The open dependency counts of issues, by issue node ID, for list_issues,
172
+ * read in pages of DEPENDENCY_COUNTS_PAGE, a few at once. An issue whose counts
173
+ * cannot be read is left out of the map; a page that fails costs its issues
174
+ * only, and `error` names the first such failure.
175
+ * @param {string[]} issueIds - Issue node IDs
176
+ * @param {string} [token] - Optional per-request GitHub token
177
+ * @returns {Promise<{ counts: Map<string, { blockedBy: number, blocking: number }>, error?: string }>}
178
+ */
179
+ export async function getDependencyCounts(issueIds, token) {
180
+ const pages = [];
181
+ for (let i = 0; i < issueIds.length; i += DEPENDENCY_COUNTS_PAGE) {
182
+ pages.push(issueIds.slice(i, i + DEPENDENCY_COUNTS_PAGE));
183
+ }
184
+ // A few pages at once: a whole board at once would trip GitHub's
185
+ // secondary rate limit.
186
+ const answers = [];
187
+ for (let i = 0; i < pages.length; i += DEPENDENCY_COUNTS_CONCURRENCY) {
188
+ answers.push(...await Promise.allSettled(pages.slice(i, i + DEPENDENCY_COUNTS_CONCURRENCY).map(ids => withPartialData(
189
+ graphQLWithAuth(DEPENDENCY_COUNTS_QUERY, { ids }, token),
190
+ // Every node is nullable: an error costs that issue's counts only.
191
+ error => error.path?.[0] === 'nodes' && error.path.length > 1
192
+ ))));
193
+ }
194
+ const counts = new Map();
195
+ let error;
196
+ for (const answer of answers) {
197
+ if (answer.status === 'rejected') {
198
+ logger.warn('Dependency counts unreadable', { error: answer.reason?.message });
199
+ error ??= answer.reason?.message ?? String(answer.reason);
200
+ continue;
201
+ }
202
+ const { data, errors } = answer.value;
203
+ if (errors.length > 0) {
204
+ logger.warn('Dependency counts partly unreadable', { errors: errors.map(e => e.message) });
205
+ }
206
+ for (const node of data?.nodes ?? []) {
207
+ if (node?.id && node.issueDependenciesSummary) counts.set(node.id, node.issueDependenciesSummary);
208
+ }
209
+ }
210
+ return { counts, ...(error ? { error } : {}) };
211
+ }
212
+
213
+ async function setIssueRelation(issue, relation, related, remove, token) {
214
+ if (!RELATION_TYPES.includes(relation)) {
215
+ throw new Error(`Unknown relation '${relation}'. Expected one of: ${RELATION_TYPES.join(', ')}`);
216
+ }
217
+ if (issue.owner.toLowerCase() === related.owner.toLowerCase()
218
+ && issue.repo.toLowerCase() === related.repo.toLowerCase()
219
+ && issue.issue_number === related.issue_number) {
220
+ throw new Error('An issue cannot be related to itself');
221
+ }
222
+ const { data: ids } = await withPartialData(graphQLWithAuth(RELATION_ISSUE_IDS_QUERY, {
223
+ owner: issue.owner,
224
+ repo: issue.repo,
225
+ number: issue.issue_number,
226
+ relatedOwner: related.owner,
227
+ relatedRepo: related.repo,
228
+ relatedNumber: related.issue_number
229
+ }, token), isRootNotFound);
230
+ const issueId = ids?.issue?.issue?.id;
231
+ const relatedId = ids?.related?.issue?.id;
232
+ if (!issueId) throw notFound(issue);
233
+ if (!relatedId) throw notFound(related);
234
+ // A renamed or transferred repository can name one issue two ways.
235
+ if (issueId === relatedId) throw new Error('An issue cannot be related to itself');
236
+ if (relation === 'relates_to') {
237
+ const mutation = remove ? REMOVE_RELATES_TO_MUTATION : ADD_RELATES_TO_MUTATION;
238
+ await graphQLWithAuth(mutation, { issueId, relatedIssueId: relatedId }, token);
239
+ return;
240
+ }
241
+ // "blocking" is "blocked by" with the two issues swapped.
242
+ const [blockedId, blockingId] = relation === 'blocked_by' ? [issueId, relatedId] : [relatedId, issueId];
243
+ const mutation = remove ? REMOVE_BLOCKED_BY_MUTATION : ADD_BLOCKED_BY_MUTATION;
244
+ await graphQLWithAuth(mutation, { issueId: blockedId, blockingIssueId: blockingId }, token);
245
+ }
246
+
247
+ /**
248
+ * Set a relation between two issues.
249
+ * @param {{ owner: string, repo: string, issue_number: number }} issue - The issue the relation is read from
250
+ * @param {'blocked_by'|'blocking'|'relates_to'} relation
251
+ * @param {{ owner: string, repo: string, issue_number: number }} related - The other issue
252
+ * @param {string} [token] - Optional per-request GitHub token
253
+ * @returns {Promise<void>}
254
+ */
255
+ export async function addIssueRelation(issue, relation, related, token) {
256
+ await setIssueRelation(issue, relation, related, false, token);
257
+ }
258
+
259
+ /**
260
+ * Remove a relation between two issues.
261
+ * @param {{ owner: string, repo: string, issue_number: number }} issue - The issue the relation is read from
262
+ * @param {'blocked_by'|'blocking'|'relates_to'} relation
263
+ * @param {{ owner: string, repo: string, issue_number: number }} related - The other issue
264
+ * @param {string} [token] - Optional per-request GitHub token
265
+ * @returns {Promise<void>}
266
+ */
267
+ export async function removeIssueRelation(issue, relation, related, token) {
268
+ await setIssueRelation(issue, relation, related, true, token);
269
+ }