-
Notifications
You must be signed in to change notification settings - Fork 54
/
linear.ts
281 lines (244 loc) · 7.27 KB
/
linear.ts
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
import { LinearClient } from "@linear/sdk";
import { getWebhookURL, getSyncFooter } from ".";
import { linearQuery } from "./apollo";
import { LINEAR, GENERAL, GITHUB } from "./constants";
import { v4 as uuid } from "uuid";
import { LinearObject, LinearTeam, TicketState } from "../typings";
import { WebhookUpdateInput } from "@linear/sdk/dist/_generated_documents";
export const getLinearTokenURL = (): string => {
const baseURL = LINEAR.NEW_TOKEN_URL;
const sectionSelector = `#:~:text=${LINEAR.TOKEN_SECTION_HEADER.split(
" "
).join("%20")}`;
const tokenURL = `${baseURL}${sectionSelector}`;
return tokenURL;
};
export const getLinearAuthURL = (verificationCode: string): string => {
// Specify OAuth app and scopes
const params = {
client_id: LINEAR.OAUTH_ID,
redirect_uri: window.location.origin,
scope: LINEAR.SCOPES.join(","),
state: verificationCode,
response_type: "code",
prompt: "consent"
};
// Combine params in a URL-friendly string
const authURL = Object.keys(params).reduce(
(url, param, i) =>
`${url}${i == 0 ? "?" : "&"}${param}=${params[param]}`,
LINEAR.OAUTH_URL
);
return authURL;
};
export const getLinearContext = async (token: string) => {
const query = `query {
teams {
nodes {
name
id
labels {
nodes {
id
name
}
}
states {
nodes {
id
name
}
}
}
}
viewer {
name
id
}
}`;
return await linearQuery(query, token);
};
export const getLinearWebhook = async (token: string, teamName: string) => {
const callbackURL = getWebhookURL();
const query = `query GetWebhook {
webhooks {
nodes {
url
id
resourceTypes
team {
name
}
}
}
}`;
const response = await linearQuery(query, token);
if (!response?.data) {
console.error("No webhook response from Linear");
return null;
}
const webhook = response.data.webhooks?.nodes?.find(
w => w.url === callbackURL && w.team?.name === teamName
);
return webhook;
};
export const setLinearWebhook = async (token: string, teamID: string) => {
const callbackURL = getWebhookURL();
const mutation = `mutation CreateWebhook($callbackURL: String!, $teamID: String) {
webhookCreate(
input: {
url: $callbackURL
teamId: $teamID
label: "GitHub Sync"
resourceTypes: ["Issue", "Comment", "IssueLabel"]
}
) {
success
webhook {
id
enabled
}
}
}`;
return await linearQuery(mutation, token, { callbackURL, teamID });
};
export const updateLinearWebhook = async (
token: string,
teamName: string,
updates: WebhookUpdateInput
) => {
const webhook = await getLinearWebhook(token, teamName);
if (!webhook?.id) {
console.error(`Could not find webhook for Linear team ${teamName}`);
return;
}
const mutation = `mutation UpdateWebhook($input: WebhookUpdateInput!, $webhookId: String!) {
webhookUpdate(
id: $webhookId,
input: $input
) {
success
}
}`;
return await linearQuery(mutation, token, {
webhookId: webhook.id,
input: updates
});
};
export const createLinearLabel = async (
token: string,
teamID: string,
labelName: string,
color: string
) => {
const mutation = `mutation CreateLabel($teamID: String!, $labelName: String!, $color: String!) {
issueLabelCreate(
input: {
name: $labelName,
color: $color,
teamId: $teamID
}
) {
success
issueLabel {
id
name
}
}
}`;
return await linearQuery(mutation, token, {
teamID,
labelName,
color
});
};
export const saveLinearContext = async (
token: string,
team: LinearTeam,
stateLabels: { [key in TicketState]: LinearObject }
) => {
let publicLabel = team.labels?.nodes?.find?.(n => n.name === "Public");
if (!publicLabel) {
const { data } = await createLinearLabel(
token,
team.id,
"Public",
"#2DA54E"
);
if (!data?.issueLabelCreate?.issueLabel) {
alert('Please create a Linear label called "Public"');
}
publicLabel = data?.issueLabelCreate?.issueLabel;
}
if (!stateLabels) {
alert("Please select a label for each ticket state");
return;
}
const data = {
teamId: team.id,
teamName: team.name,
publicLabelId: publicLabel?.id,
toDoStateId: stateLabels.todo?.id,
doneStateId: stateLabels.done?.id,
canceledStateId: stateLabels.canceled?.id
};
const response = await fetch("/api/linear/save", {
method: "POST",
body: JSON.stringify(data)
});
return response.json();
};
export const exchangeLinearToken = async (
refreshToken: string
): Promise<{ access_token?: string }> => {
const redirectURI = window.location.origin;
const response = await fetch("/api/linear/token", {
method: "POST",
body: JSON.stringify({ refreshToken, redirectURI }),
headers: { "Content-Type": "application/json" }
});
return await response.json();
};
export const checkTeamWebhook = async (
teamId: string,
teamName: string,
token: string
): Promise<{ teamInDB?: boolean; webhookExists?: boolean }> => {
const response = await fetch("/api/linear/webhook", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
teamId,
teamName
})
});
return await response.json();
};
// Open a Linear ticket for the creator to authenticate with this app
export const inviteMember = async (
memberId: string,
teamId: string,
repoName,
linearClient: LinearClient
) => {
const issueCreator = await linearClient.user(memberId);
const message = [
`Hey @${issueCreator.displayName}!`,
`Someone on your team signed up for [Linear-GitHub Sync](${GENERAL.APP_URL}).`,
`To mirror issues you tag as Public in ${repoName}, simply follow the auth flow [here](${GENERAL.APP_URL}).`,
`If you'd like to stop seeing these messages, please ask your workspace admin to let us know!`,
getSyncFooter()
].join("\n");
linearClient.createIssue({
title: `GitHub Sync — ${issueCreator.name}, please join our workspace`,
description: message,
teamId: teamId,
assigneeId: memberId
});
};
export const generateLinearUUID = (): string => {
return `${uuid().substring(0, 28)}${GITHUB.UUID_SUFFIX}`;
};