-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbackground.js
More file actions
411 lines (384 loc) · 16.5 KB
/
Copy pathbackground.js
File metadata and controls
411 lines (384 loc) · 16.5 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
const api = typeof browser !== "undefined" && browser.runtime ? browser : chrome;
const GRAPHQL_URL = "https://api.github.com/graphql";
async function getSettings() {
const stored = await api.storage.local.get(["token", "fields", "ageEnabled", "ageUnit"]);
return {
token: (stored.token || "").trim(),
fields: parseFields(stored.fields),
ageEnabled: stored.ageEnabled === true,
ageUnit: stored.ageUnit || "months"
};
}
// pulls: [{owner, repo, number}] -> { "owner/repo!number": { association, bot, login, fork, additions, deletions, files, mergeState, draft } }
async function fetchPullRequests(pulls) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const byRepo = new Map();
for (const it of pulls) {
const key = `${it.owner}/${it.repo}`;
if (!byRepo.has(key)) byRepo.set(key, { owner: it.owner, repo: it.repo, numbers: new Set() });
byRepo.get(key).numbers.add(Number(it.number));
}
const parts = [];
let r = 0;
for (const { owner, repo, numbers } of byRepo.values()) {
const items = [...numbers].map((n) => `p${n}: pullRequest(number: ${n}) { number isDraft authorAssociation author { __typename login } isCrossRepository additions deletions changedFiles mergeStateStatus }`);
parts.push(`r${r++}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) { nameWithOwner ${items.join("\n")} }`);
}
const data = await graphql(token, `{ ${parts.join("\n")} }`, { partial: true });
const result = {};
for (const repoNode of Object.values(data)) {
if (!repoNode || !repoNode.nameWithOwner) continue;
for (const [alias, pr] of Object.entries(repoNode)) {
if (!alias.startsWith("p") || !pr || typeof pr !== "object") continue;
result[`${repoNode.nameWithOwner}!${pr.number}`] = {
association: pr.authorAssociation || "NONE",
bot: Boolean(pr.author && pr.author.__typename === "Bot"),
login: pr.author ? pr.author.login : null,
fork: Boolean(pr.isCrossRepository),
additions: pr.additions, deletions: pr.deletions, files: pr.changedFiles,
mergeState: pr.mergeStateStatus || "UNKNOWN",
draft: Boolean(pr.isDraft)
};
}
}
return { pulls: result };
}
function parseFields(raw) {
return String(raw || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
}
async function graphql(token, query, { partial = false } = {}) {
const res = await fetch(GRAPHQL_URL, {
method: "POST",
headers: {
Authorization: `bearer ${token}`,
"Content-Type": "application/json",
"User-Agent": "github-issue-toolkit"
},
body: JSON.stringify({ query })
});
if (res.status === 401) {
throw new Error("Token rejected by GitHub (401). Check it in the extension options.");
}
if (!res.ok) {
throw new Error(`GitHub API responded with HTTP ${res.status}`);
}
const json = await res.json();
if (json.errors && (!json.data || !partial)) {
throw new Error(json.errors.map((e) => e.message).join("; "));
}
return json.data || {};
}
// `withOptions` also asks for the options a single-select field defines, which gives the kanban board its
// column order. Not every GitHub deployment knows that selection, so the caller falls back to asking without it.
function fieldValueFragment(withOptions) {
return `
issueFieldValues(first: 30) {
nodes {
__typename
... on IssueFieldSingleSelectValue { name color field { ... on IssueFieldSingleSelect { id name ${withOptions ? "options { id name color }" : ""} } } }
... on IssueFieldMultiSelectValue { value field { ... on IssueFieldMultiSelect { name } } }
... on IssueFieldTextValue { value field { ... on IssueFieldText { name } } }
... on IssueFieldNumberValue { value field { ... on IssueFieldNumber { name } } }
... on IssueFieldDateValue { value field { ... on IssueFieldDate { name } } }
}
}`;
}
const FIELD_VALUE_FRAGMENT = fieldValueFragment(false);
// One field value as the content script wants it: the field name, the value as text, its colour, and,
// for a single select, the options of the field in the order the organization defined them.
function fieldValue(node) {
const fieldName = node.field && node.field.name;
if (!fieldName) return null;
const value = node.__typename === "IssueFieldSingleSelectValue" ? node.name : node.value;
if (value === null || value === undefined || value === "") return null;
const options = node.field && Array.isArray(node.field.options)
? node.field.options.map((o) => ({ id: o.id, name: o.name, color: o.color || "GRAY" }))
: null;
return {
field: fieldName,
fieldId: (node.field && node.field.id) || null,
value: String(value),
color: node.color || "GRAY",
kind: node.__typename.replace(/^IssueField|Value$/g, "").toLowerCase(),
options
};
}
async function fetchFieldValues(issues) {
const { token, fields, ageEnabled } = await getSettings();
if (!token) {
return { error: "NO_TOKEN" };
}
if (!fields.length && !ageEnabled) {
return { error: "NO_FIELDS" };
}
const byRepo = new Map();
for (const it of issues) {
const key = `${it.owner}/${it.repo}`;
if (!byRepo.has(key)) byRepo.set(key, { owner: it.owner, repo: it.repo, numbers: new Set() });
byRepo.get(key).numbers.add(Number(it.number));
}
const repoParts = [];
let r = 0;
for (const { owner, repo, numbers } of byRepo.values()) {
const issueParts = [...numbers].map(
(n) => `i${n}: issue(number: ${n}) { number createdAt ${fields.length ? FIELD_VALUE_FRAGMENT : ""} }`
);
repoParts.push(
`r${r++}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(repo)}) { nameWithOwner ${issueParts.join("\n")} }`
);
}
// partial: a single missing issue (deleted, transferred, no access) must not fail the whole page.
const data = await graphql(token, `{ ${repoParts.join("\n")} }`, { partial: true });
const wanted = new Set(fields.map((f) => f.toLowerCase()));
const result = {};
const created = {};
for (const repoNode of Object.values(data)) {
if (!repoNode || !repoNode.nameWithOwner) continue;
for (const [alias, issueNode] of Object.entries(repoNode)) {
if (!alias.startsWith("i") || !issueNode || typeof issueNode !== "object") continue;
const key = `${repoNode.nameWithOwner}#${issueNode.number}`;
if (issueNode.createdAt) created[key] = issueNode.createdAt;
const values = [];
for (const node of (issueNode.issueFieldValues && issueNode.issueFieldValues.nodes) || []) {
const v = fieldValue(node);
if (!v || !wanted.has(v.field.toLowerCase())) continue;
values.push({ field: v.field, value: v.value, color: v.color });
}
values.sort((a, b) => fields.findIndex((f) => f.toLowerCase() === a.field.toLowerCase())
- fields.findIndex((f) => f.toLowerCase() === b.field.toLowerCase()));
result[key] = values;
}
}
return { values: result, created, fields };
}
// ---------------------------------------------------------------------------
// Epic kanban: every sub-issue of one issue, with the field values the board groups and orders by
// ---------------------------------------------------------------------------
const SUB_ISSUE_PAGE = 100;
const SUB_ISSUE_MAX_PAGES = 5;
// Whether this GitHub knows the option list of a single-select field: unknown until one query has answered.
// A deployment that does not know it is asked again after a while, so one passing error never disables the
// column order and the drag targets for the rest of the worker's life.
let selectOptionsKnown = null;
let selectOptionsRetryAt = 0;
const SELECT_OPTIONS_RETRY_MS = 10 * 60 * 1000;
// The validation error GraphQL returns for a selection the schema does not have, and nothing else.
const UNKNOWN_OPTIONS_SELECTION = /Field 'options' doesn't exist on type 'IssueFieldSingleSelect'/;
function subIssueQuery(ref, cursor, withOptions) {
return `{ r: repository(owner: ${JSON.stringify(ref.owner)}, name: ${JSON.stringify(ref.repo)}) {
issue(number: ${Number(ref.number)}) {
number
title
subIssues(first: ${SUB_ISSUE_PAGE}${cursor ? `, after: ${JSON.stringify(cursor)}` : ""}) {
totalCount
pageInfo { hasNextPage endCursor }
nodes {
id number title url state stateReason createdAt
repository { nameWithOwner }
issueType { name color }
assignees(first: 3) { nodes { login avatarUrl } }
${fieldValueFragment(withOptions)}
}
}
}
} }`;
}
async function subIssuePage(token, ref, cursor) {
if (selectOptionsKnown === false && Date.now() >= selectOptionsRetryAt) selectOptionsKnown = null;
if (selectOptionsKnown !== false) {
try {
const data = await graphql(token, subIssueQuery(ref, cursor, true), { partial: true });
selectOptionsKnown = true;
return data;
} catch (err) {
// Only an unknown `options` selection is worth a second, plainer attempt; anything else is the real answer.
if (!UNKNOWN_OPTIONS_SELECTION.test(err.message || "")) throw err;
selectOptionsKnown = false;
selectOptionsRetryAt = Date.now() + SELECT_OPTIONS_RETRY_MS;
}
}
return graphql(token, subIssueQuery(ref, cursor, false), { partial: true });
}
function subIssueItem(node) {
const nameWithOwner = node.repository ? node.repository.nameWithOwner : "";
const [owner, repo] = nameWithOwner.split("/");
const values = [];
for (const valueNode of (node.issueFieldValues && node.issueFieldValues.nodes) || []) {
const value = fieldValue(valueNode);
if (value) values.push(value);
}
return {
key: `${nameWithOwner}#${node.number}`,
id: node.id,
owner,
repo,
number: node.number,
title: node.title,
url: node.url,
state: node.state,
stateReason: node.stateReason || null,
createdAt: node.createdAt,
type: node.issueType ? node.issueType.name : null,
typeColor: node.issueType ? node.issueType.color : null,
assignees: ((node.assignees && node.assignees.nodes) || []).map((a) => ({ login: a.login, avatarUrl: a.avatarUrl })),
values
};
}
// All sub-issues of `ref`, paginated, with every field value they carry: the board groups and orders by
// fields that are not necessarily among the ones configured for badges.
async function fetchEpic(ref) {
const { token, fields } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const items = [];
let cursor = null;
let total = 0;
for (let page = 0; page < SUB_ISSUE_MAX_PAGES; page++) {
const data = await subIssuePage(token, ref, cursor);
const issue = data.r && data.r.issue;
if (!issue) return { error: `Issue ${ref.owner}/${ref.repo}#${ref.number} not found or not accessible with this token.` };
const connection = issue.subIssues || {};
total = connection.totalCount || total;
for (const node of connection.nodes || []) {
if (node) items.push(subIssueItem(node));
}
if (!connection.pageInfo || !connection.pageInfo.hasNextPage) break;
cursor = connection.pageInfo.endCursor;
}
return { items, total, fields };
}
// Moving a card writes to GitHub: a single-select field value, or the state of the issue. Nothing else
// is written, and only a drag the user performed asks for it.
async function moveIssue(move) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const issueId = JSON.stringify(String(move.issueId || ""));
if (move.kind === "state") {
// An issue that was closed as not planned is closed that way again; everything else is completed.
const reason = move.stateReason === "NOT_PLANNED" ? "NOT_PLANNED" : "COMPLETED";
const mutation = move.state === "CLOSED"
? `mutation { closeIssue(input: { issueId: ${issueId}, stateReason: ${reason} }) { issue { number state } } }`
: `mutation { reopenIssue(input: { issueId: ${issueId} }) { issue { number state } } }`;
await graphql(token, mutation);
return { ok: true };
}
if (move.kind !== "field" || !move.fieldId) return { error: "This column cannot be a drop target." };
const fieldId = JSON.stringify(String(move.fieldId));
if (!move.optionId) {
await graphql(token, `mutation { deleteIssueFieldValue(input: { issueId: ${issueId}, fieldId: ${fieldId} }) { success } }`);
return { ok: true };
}
const set = `mutation { createIssueFieldValue(input: { issueId: ${issueId}, issueField: { fieldId: ${fieldId}, singleSelectOptionId: ${JSON.stringify(String(move.optionId))} } }) { issueFieldValue { __typename } } }`;
try {
await graphql(token, set);
} catch (err) {
// The input is a create-or-update, but a deployment that refuses to overwrite gets the value cleared first.
if (!/exist/i.test(err.message || "")) throw err;
await graphql(token, `mutation { deleteIssueFieldValue(input: { issueId: ${issueId}, fieldId: ${fieldId} }) { success } }`);
await graphql(token, set);
}
return { ok: true };
}
function issueSelection(ref) {
return `repository(owner: ${JSON.stringify(ref.owner)}, name: ${JSON.stringify(ref.repo)}) {
nameWithOwner
issue(number: ${Number(ref.number)}) {
id number title state url createdAt
issueType { name color }
parent { number repository { nameWithOwner } }
}
}`;
}
function pickIssue(repoNode) {
if (!repoNode || !repoNode.issue) return null;
const i = repoNode.issue;
return {
id: i.id,
number: i.number,
title: i.title,
state: i.state,
url: i.url,
createdAt: i.createdAt,
type: i.issueType ? i.issueType.name : null,
typeColor: i.issueType ? i.issueType.color : null,
parent: i.parent ? `${i.parent.repository.nameWithOwner}#${i.parent.number}` : null,
nameWithOwner: repoNode.nameWithOwner
};
}
// Title, type and node id of one issue, used when pinning it.
async function fetchIssueMeta(ref) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const data = await graphql(token, `{ r: ${issueSelection(ref)} }`);
const issue = pickIssue(data.r);
if (!issue) return { error: `Issue ${ref.owner}/${ref.repo}#${ref.number} not found or not accessible with this token.` };
return { issue };
}
// Make `child` a sub-issue of `parent`. Needs a token with write access to the child's repository.
async function linkSubIssue(parent, child, replaceParent) {
const { token } = await getSettings();
if (!token) return { error: "NO_TOKEN" };
const data = await graphql(token, `{ p: ${issueSelection(parent)} c: ${issueSelection(child)} }`);
const p = pickIssue(data.p);
const c = pickIssue(data.c);
if (!p) return { error: `Epic ${parent.owner}/${parent.repo}#${parent.number} not found.` };
if (!c) return { error: `Issue ${child.owner}/${child.repo}#${child.number} not found.` };
if (c.parent && !replaceParent) {
return { error: "HAS_PARENT", parent: c.parent };
}
const mutation = `mutation {
addSubIssue(input: { issueId: ${JSON.stringify(p.id)}, subIssueId: ${JSON.stringify(c.id)}, replaceParent: ${replaceParent ? "true" : "false"} }) {
issue { number }
subIssue { number }
}
}`;
await graphql(token, mutation);
return { ok: true, parent: `${p.nameWithOwner}#${p.number}`, child: `${c.nameWithOwner}#${c.number}` };
}
function reply(promise, sendResponse) {
promise
.then(sendResponse)
.catch((err) => sendResponse({ error: err.message || String(err) }));
return true;
}
api.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (!msg) return false;
if (msg.type === "fetchFieldValues") {
return reply(fetchFieldValues(msg.issues || []), sendResponse);
}
if (msg.type === "fetchPullRequests") {
return reply(fetchPullRequests(msg.pulls || []), sendResponse);
}
if (msg.type === "fetchEpic") {
return reply(fetchEpic(msg.issue), sendResponse);
}
if (msg.type === "moveIssue") {
return reply(moveIssue(msg.move || {}), sendResponse);
}
if (msg.type === "fetchIssueMeta") {
return reply(fetchIssueMeta(msg.issue), sendResponse);
}
if (msg.type === "linkSubIssue") {
return reply(linkSubIssue(msg.parent, msg.child, Boolean(msg.replaceParent)), sendResponse);
}
if (msg.type === "openOptions") {
api.runtime.openOptionsPage();
sendResponse({ ok: true });
return false;
}
if (msg.type === "testToken") {
return reply((async () => {
const token = String(msg.token || "").trim();
if (!token) return { error: "No token given" };
const data = await graphql(token, "{ viewer { login } }");
return { login: data.viewer && data.viewer.login };
})(), sendResponse);
}
return false;
});
api.action.onClicked.addListener(() => {
api.runtime.openOptionsPage();
});