tabherd 0.0.0-stage → 0.6.0
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.
- package/CHANGELOG.md +166 -0
- package/LICENSE +674 -0
- package/README.md +540 -2
- package/launcher/npm.js +9 -0
- package/lib/agents.js +324 -0
- package/lib/codex-client.js +306 -0
- package/lib/codex-rollout.js +251 -0
- package/lib/codex.js +424 -0
- package/lib/comfy.js +479 -0
- package/lib/completed.js +55 -0
- package/lib/copilot.js +359 -0
- package/lib/cursor.js +516 -0
- package/lib/dismissed.js +30 -0
- package/lib/filters.js +120 -0
- package/lib/groups.js +144 -0
- package/lib/history.js +253 -0
- package/lib/llamacpp.js +159 -0
- package/lib/lmstudio.js +134 -0
- package/lib/localai.js +291 -0
- package/lib/memory.js +55 -0
- package/lib/ollama.js +124 -0
- package/lib/open-dashboard.js +39 -0
- package/lib/opencode.js +371 -0
- package/lib/repos.js +81 -0
- package/lib/saved.js +33 -0
- package/lib/secrets.js +196 -0
- package/lib/session-id.js +9 -0
- package/lib/settings.js +231 -0
- package/lib/store.js +44 -0
- package/lib/terminals/index.js +62 -0
- package/lib/terminals/kitty.js +126 -0
- package/lib/terminals/linux.js +310 -0
- package/lib/terminals/macos.js +468 -0
- package/lib/terminals/tmux.js +89 -0
- package/lib/terminals/unix-driver.js +172 -0
- package/lib/terminals/unix.js +204 -0
- package/lib/terminals/unsupported.js +22 -0
- package/lib/terminals/wezterm.js +103 -0
- package/lib/terminals/windows-close.ps1 +125 -0
- package/lib/terminals/windows-focus.ps1 +235 -0
- package/lib/terminals/windows-pick-folder.ps1 +57 -0
- package/lib/terminals/windows-titles.js +124 -0
- package/lib/terminals/windows-titles.ps1 +95 -0
- package/lib/terminals/windows.js +166 -0
- package/lib/ticket-refs.js +184 -0
- package/lib/tickets.js +437 -0
- package/lib/todos.js +166 -0
- package/lib/trackers.js +541 -0
- package/lib/transcript.js +314 -0
- package/lib/updates.js +186 -0
- package/package.json +44 -4
- package/public/app.js +4077 -0
- package/public/favicon.svg +1 -0
- package/public/icons/tabherd-128.png +0 -0
- package/public/icons/tabherd-16.png +0 -0
- package/public/icons/tabherd-20.png +0 -0
- package/public/icons/tabherd-24.png +0 -0
- package/public/icons/tabherd-256.png +0 -0
- package/public/icons/tabherd-32.png +0 -0
- package/public/icons/tabherd-40.png +0 -0
- package/public/icons/tabherd-48.png +0 -0
- package/public/icons/tabherd-512.png +0 -0
- package/public/icons/tabherd-64.png +0 -0
- package/public/index.html +655 -0
- package/public/lang/es.js +742 -0
- package/public/style.css +1443 -0
- package/server.js +814 -0
package/lib/trackers.js
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { execFile } = require('child_process');
|
|
5
|
+
|
|
6
|
+
// Ticket trackers: Jira sites, Linear, GitHub Issues and Zendesk, each with
|
|
7
|
+
// its sign-in. They're kept in settings.json, encrypted, and set in
|
|
8
|
+
// Settings → Tickets. A token never goes back to the page. See
|
|
9
|
+
// docs/ticket-links.md.
|
|
10
|
+
|
|
11
|
+
const TYPES = ['jira', 'linear', 'github', 'zendesk'];
|
|
12
|
+
const MAX_TRACKERS = 20;
|
|
13
|
+
const MAX_PREFIXES = 50;
|
|
14
|
+
const REQUEST_MS = 10000;
|
|
15
|
+
// Where Linear's API and Atlassian's gateway for scoped Jira tokens are.
|
|
16
|
+
// Tests point them at stand-ins.
|
|
17
|
+
const endpoints = { linear: 'https://api.linear.app/graphql', atlassian: 'https://api.atlassian.com' };
|
|
18
|
+
|
|
19
|
+
const text = (value, max) => (typeof value === 'string' && value.length <= max && !/[\r\n]/.test(value) ? value.trim() : undefined);
|
|
20
|
+
|
|
21
|
+
// An https address, or http on this computer, without a login in it.
|
|
22
|
+
function address(value) {
|
|
23
|
+
const v = text(value, 500)?.replace(/\/+$/, '');
|
|
24
|
+
if (!v) return undefined;
|
|
25
|
+
try {
|
|
26
|
+
const u = new URL(v);
|
|
27
|
+
const local = ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
28
|
+
return (u.protocol === 'https:' || (u.protocol === 'http:' && local)) && !u.username && !u.password && !u.search && !u.hash ? v : undefined;
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ABC, OPS: a project or team key's letters, upper case.
|
|
35
|
+
function prefixes(list) {
|
|
36
|
+
if (list === undefined) return [];
|
|
37
|
+
if (!Array.isArray(list) || list.length > MAX_PREFIXES) return undefined;
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const p of list) {
|
|
40
|
+
const v = typeof p === 'string' ? p.trim().toUpperCase() : '';
|
|
41
|
+
if (!/^[A-Z][A-Z0-9_]{0,19}$/.test(v)) return undefined;
|
|
42
|
+
if (!out.includes(v)) out.push(v);
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A tracker as saved, or undefined if it isn't valid.
|
|
48
|
+
function clean(t) {
|
|
49
|
+
if (!t || typeof t !== 'object' || !TYPES.includes(t.type)) return undefined;
|
|
50
|
+
const id = typeof t.id === 'string' && /^[0-9a-f-]{36}$/i.test(t.id) ? t.id : undefined;
|
|
51
|
+
const name = text(t.name, 60);
|
|
52
|
+
const token = t.token === undefined ? '' : text(t.token, 4000);
|
|
53
|
+
const email = t.email === undefined ? '' : text(t.email, 200);
|
|
54
|
+
const list = prefixes(t.prefixes);
|
|
55
|
+
if (!id || !name || token === undefined || email === undefined || !list) return undefined;
|
|
56
|
+
const needsAddress = t.type === 'jira' || t.type === 'zendesk';
|
|
57
|
+
const url = needsAddress ? address(t.url) : '';
|
|
58
|
+
if (url === undefined) return undefined;
|
|
59
|
+
return {
|
|
60
|
+
id,
|
|
61
|
+
type: t.type,
|
|
62
|
+
name,
|
|
63
|
+
url,
|
|
64
|
+
// Jira and Zendesk sign in with an email and token. Without an email, a
|
|
65
|
+
// Jira token is a Data Center personal access token.
|
|
66
|
+
email: t.type === 'jira' || t.type === 'zendesk' ? email : '',
|
|
67
|
+
// Zendesk: an API token, or an OAuth access token.
|
|
68
|
+
auth: t.type === 'zendesk' && t.auth === 'oauth' ? 'oauth' : 'token',
|
|
69
|
+
prefixes: t.type === 'github' ? [] : list,
|
|
70
|
+
// GitHub uses gh's own sign-in.
|
|
71
|
+
token: t.type === 'github' ? '' : token,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function cleanList(list) {
|
|
76
|
+
if (!Array.isArray(list) || list.length > MAX_TRACKERS) return undefined;
|
|
77
|
+
const out = list.map(clean);
|
|
78
|
+
return out.includes(undefined) ? undefined : out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// What the page may see: everything but the token, which only says if it's set.
|
|
82
|
+
const forPage = (list) => list.map(({ token, ...t }) => ({ ...t, tokenSet: Boolean(token) }));
|
|
83
|
+
|
|
84
|
+
const ERRORS = {
|
|
85
|
+
type: 'Choose Jira, Linear, GitHub Issues or Zendesk.',
|
|
86
|
+
name: 'Give it a name, of up to 60 characters.',
|
|
87
|
+
url: 'Give its address, such as https://example.atlassian.net.',
|
|
88
|
+
prefixes: 'Key prefixes are letters and digits, starting with a letter, such as ABC.',
|
|
89
|
+
full: `There can be at most ${MAX_TRACKERS} trackers.`,
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// The list with one tracker added or changed. A token left out is kept; an
|
|
93
|
+
// empty one is cleared.
|
|
94
|
+
function save(list, incoming) {
|
|
95
|
+
if (!incoming || typeof incoming !== 'object' || !TYPES.includes(incoming.type)) return { ok: false, error: ERRORS.type };
|
|
96
|
+
const old = list.find((t) => t.id === incoming.id);
|
|
97
|
+
if (!old && list.length >= MAX_TRACKERS) return { ok: false, error: ERRORS.full };
|
|
98
|
+
const merged = { ...incoming, id: old ? old.id : crypto.randomUUID(), token: incoming.token === undefined ? old?.token || '' : incoming.token };
|
|
99
|
+
const tracker = clean(merged);
|
|
100
|
+
if (!tracker) {
|
|
101
|
+
if (!text(merged.name, 60)) return { ok: false, error: ERRORS.name };
|
|
102
|
+
if (!prefixes(merged.prefixes)) return { ok: false, error: ERRORS.prefixes };
|
|
103
|
+
if ((merged.type === 'jira' || merged.type === 'zendesk') && !address(merged.url)) return { ok: false, error: ERRORS.url };
|
|
104
|
+
return { ok: false, error: 'Not a valid tracker.' };
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, tracker, list: old ? list.map((t) => (t.id === old.id ? tracker : t)) : [...list, tracker] };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const remove = (list, id) => list.filter((t) => t.id !== id);
|
|
110
|
+
|
|
111
|
+
// ---- signing in ----------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
async function request(url, { method = 'GET', headers = {}, body } = {}) {
|
|
114
|
+
const res = await fetch(url, {
|
|
115
|
+
method,
|
|
116
|
+
headers: { Accept: 'application/json', ...headers, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
117
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
118
|
+
signal: AbortSignal.timeout(REQUEST_MS),
|
|
119
|
+
redirect: 'error',
|
|
120
|
+
});
|
|
121
|
+
const data = await res.json().catch(() => null);
|
|
122
|
+
return { status: res.status, data };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const basic = (user, pass) => `Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`;
|
|
126
|
+
|
|
127
|
+
function jiraAuth(t) {
|
|
128
|
+
return t.email ? basic(t.email, t.token) : `Bearer ${t.token}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// The base address that takes this tracker's token: the site, or for a
|
|
132
|
+
// scoped Cloud token, Atlassian's gateway with the site's cloud ID. Kept per
|
|
133
|
+
// tracker and token, so it's found once.
|
|
134
|
+
const jiraBases = new Map();
|
|
135
|
+
const jiraKey = (t) => `${t.id}:${crypto.createHash('sha256').update(`${t.url} ${t.email} ${t.token}`).digest('hex')}`;
|
|
136
|
+
|
|
137
|
+
// Jira Cloud's API is version 3. Data Center, signed in with a personal
|
|
138
|
+
// access token rather than an email, has version 2.
|
|
139
|
+
const jiraApi = (t) => (t.email ? '/rest/api/3' : '/rest/api/2');
|
|
140
|
+
const refused = (status) => status === 401 || status === 403;
|
|
141
|
+
|
|
142
|
+
// Asks a Jira site, at the address that takes its token. A refused request
|
|
143
|
+
// did nothing, so it's safe to send again through the gateway.
|
|
144
|
+
async function jiraCall(t, route, { method = 'GET', body } = {}) {
|
|
145
|
+
const known = jiraBases.get(jiraKey(t));
|
|
146
|
+
const options = { method, headers: { Authorization: jiraAuth(t) }, body };
|
|
147
|
+
if (known) return request(`${known}${jiraApi(t)}${route}`, options);
|
|
148
|
+
let base = t.url;
|
|
149
|
+
let answer = await request(`${base}${jiraApi(t)}${route}`, options);
|
|
150
|
+
if (refused(answer.status) && t.email) {
|
|
151
|
+
// A scoped token is refused at the site's own address.
|
|
152
|
+
const tenant = await request(`${t.url}/_edge/tenant_info`);
|
|
153
|
+
if (tenant.data?.cloudId && /^[0-9a-f-]{36}$/i.test(tenant.data.cloudId)) {
|
|
154
|
+
const gateway = `${endpoints.atlassian}/ex/jira/${tenant.data.cloudId}`;
|
|
155
|
+
const through = await request(`${gateway}${jiraApi(t)}${route}`, options);
|
|
156
|
+
if (!refused(through.status)) [base, answer] = [gateway, through];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// Signed in, whether or not what was asked for is there.
|
|
160
|
+
if ([200, 201, 204, 404].includes(answer.status)) jiraBases.set(jiraKey(t), base);
|
|
161
|
+
return answer;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const jiraGet = (t, route) => jiraCall(t, route);
|
|
165
|
+
|
|
166
|
+
const jiraMyself = (t) => jiraGet(t, '/myself');
|
|
167
|
+
|
|
168
|
+
// Runs gh; tests swap it for a stand-in.
|
|
169
|
+
let gh = (args) =>
|
|
170
|
+
new Promise((resolve) => {
|
|
171
|
+
execFile('gh', args, { timeout: REQUEST_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
172
|
+
resolve(err ? { ok: false, missing: err.code === 'ENOENT', stdout: '', stderr: String(stderr || '') } : { ok: true, stdout });
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
const useGh = (fn) => {
|
|
176
|
+
gh = fn;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
// Signs in and says as whom: { ok, as } or { ok: false, error }. Nothing in an
|
|
180
|
+
// error comes from the token.
|
|
181
|
+
async function test(t) {
|
|
182
|
+
try {
|
|
183
|
+
if (t.type === 'github') {
|
|
184
|
+
const r = await gh(['api', 'user', '--jq', '.login']);
|
|
185
|
+
if (r.missing) return { ok: false, error: "GitHub's command-line tool, gh, isn't installed. Get it from cli.github.com." };
|
|
186
|
+
if (!r.ok || !r.stdout.trim()) return { ok: false, error: "gh isn't signed in. Run gh auth login." };
|
|
187
|
+
return { ok: true, as: r.stdout.trim() };
|
|
188
|
+
}
|
|
189
|
+
if (!t.token) return { ok: false, error: 'Set its token first.' };
|
|
190
|
+
if (t.type === 'jira') {
|
|
191
|
+
const r = await jiraMyself(t);
|
|
192
|
+
if (r.status === 200) return { ok: true, as: r.data?.displayName || r.data?.emailAddress || 'you' };
|
|
193
|
+
if (r.status === 401 || r.status === 403) return { ok: false, error: 'Jira refused the sign-in. Check the email and API token.' };
|
|
194
|
+
return { ok: false, error: `Jira answered ${r.status}. Check the site's address.` };
|
|
195
|
+
}
|
|
196
|
+
if (t.type === 'linear') {
|
|
197
|
+
const r = await request(endpoints.linear, { method: 'POST', headers: { Authorization: t.token }, body: { query: '{ viewer { name } }' } });
|
|
198
|
+
if (r.status === 200 && r.data?.data?.viewer) return { ok: true, as: r.data.data.viewer.name || 'you' };
|
|
199
|
+
return { ok: false, error: 'Linear refused the key. Check it in Linear → Settings → Security & access.' };
|
|
200
|
+
}
|
|
201
|
+
if (t.type === 'zendesk') {
|
|
202
|
+
const auth = t.auth === 'oauth' ? `Bearer ${t.token}` : basic(`${t.email}/token`, t.token);
|
|
203
|
+
const r = await request(`${t.url}/api/v2/users/me.json`, { headers: { Authorization: auth } });
|
|
204
|
+
// Zendesk answers a refused sign-in with an anonymous user.
|
|
205
|
+
if (r.status === 200 && r.data?.user?.id) return { ok: true, as: r.data.user.name || r.data.user.email || 'you' };
|
|
206
|
+
if (r.status === 200 || r.status === 401 || r.status === 403) return { ok: false, error: 'Zendesk refused the sign-in. Check the email and token, and that API token access is on in Admin Center.' };
|
|
207
|
+
return { ok: false, error: `Zendesk answered ${r.status}. Check the address.` };
|
|
208
|
+
}
|
|
209
|
+
return { ok: false, error: ERRORS.type };
|
|
210
|
+
} catch (err) {
|
|
211
|
+
return { ok: false, error: err.name === 'TimeoutError' ? "It didn't answer in time." : "Couldn't reach it. Check the address and your connection." };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---- reading tickets ------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
// Each tracker's statuses, in the dashboard's groups: to do, in progress,
|
|
218
|
+
// done, and closed without being done.
|
|
219
|
+
const JIRA_CATEGORY = { new: 'todo', indeterminate: 'progress', done: 'done' };
|
|
220
|
+
const LINEAR_STATE = { triage: 'todo', backlog: 'todo', unstarted: 'todo', started: 'progress', completed: 'done', canceled: 'closed', duplicate: 'closed' };
|
|
221
|
+
const ZENDESK_STATUS = { new: 'todo', open: 'progress', pending: 'progress', hold: 'progress', solved: 'done', closed: 'done' };
|
|
222
|
+
const KEY = /^[A-Z][A-Z0-9_]{0,19}-[1-9]\d{0,8}$/;
|
|
223
|
+
const GITHUB = /^([a-z0-9][a-z0-9-]{0,38})\/([a-z0-9._-]{1,100})#([1-9]\d{0,8})$/;
|
|
224
|
+
const NUMBER = /^#([1-9]\d{0,9})$/;
|
|
225
|
+
const capital = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);
|
|
226
|
+
|
|
227
|
+
const missing = { ok: false, missing: true };
|
|
228
|
+
const signInRefused = { ok: false, auth: true, error: 'It refused the sign-in. Check its token.' };
|
|
229
|
+
const answered = (name, status) => ({ ok: false, error: `${name} answered ${status}.` });
|
|
230
|
+
|
|
231
|
+
// A Jira Cloud description, from Atlassian Document Format to text much as
|
|
232
|
+
// Linear and GitHub give theirs: headings and paragraphs apart, lists as -
|
|
233
|
+
// and 1., links with their addresses, code in ``` and quotes with >. Images
|
|
234
|
+
// and attachments are left out.
|
|
235
|
+
function adfText(doc) {
|
|
236
|
+
const inline = (nodes = []) =>
|
|
237
|
+
nodes
|
|
238
|
+
.map((n) => {
|
|
239
|
+
if (n.type === 'text') {
|
|
240
|
+
const href = n.marks?.find((m) => m.type === 'link')?.attrs?.href;
|
|
241
|
+
return href && href !== n.text ? `${n.text} (${href})` : n.text || '';
|
|
242
|
+
}
|
|
243
|
+
if (n.type === 'hardBreak') return '\n';
|
|
244
|
+
if (n.type === 'inlineCard') return n.attrs?.url || '';
|
|
245
|
+
// Mentions, emoji, statuses and dates carry their text.
|
|
246
|
+
return n.attrs?.text || n.attrs?.shortName || inline(n.content);
|
|
247
|
+
})
|
|
248
|
+
.join('');
|
|
249
|
+
const blocks = (nodes = []) =>
|
|
250
|
+
nodes.flatMap((n) => {
|
|
251
|
+
if (n.type === 'paragraph' || n.type === 'heading') return [inline(n.content)];
|
|
252
|
+
if (n.type === 'bulletList' || n.type === 'orderedList') {
|
|
253
|
+
const items = (n.content || []).map((item, i) => {
|
|
254
|
+
const mark = n.type === 'bulletList' ? '- ' : `${(n.attrs?.order || 1) + i}. `;
|
|
255
|
+
return mark + blocks(item.content).join('\n').replace(/\n/g, `\n${' '.repeat(mark.length)}`);
|
|
256
|
+
});
|
|
257
|
+
return [items.join('\n')];
|
|
258
|
+
}
|
|
259
|
+
if (n.type === 'codeBlock') return [`\`\`\`\n${inline(n.content)}\n\`\`\``];
|
|
260
|
+
if (n.type === 'blockquote') return [blocks(n.content).join('\n\n').replace(/^/gm, '> ')];
|
|
261
|
+
if (n.type === 'rule') return ['---'];
|
|
262
|
+
if (n.type === 'table') return [(n.content || []).map((row) => (row.content || []).map((cell) => blocks(cell.content).join(' ').replace(/\n/g, ' ')).join(' | ')).join('\n')];
|
|
263
|
+
if (n.type === 'mediaSingle' || n.type === 'mediaGroup' || n.type === 'media') return [];
|
|
264
|
+
// Panels, expands, layouts and anything newer: what's in them.
|
|
265
|
+
return n.content?.some((c) => c.type === 'text') ? [inline(n.content)] : blocks(n.content);
|
|
266
|
+
});
|
|
267
|
+
return blocks(doc?.content)
|
|
268
|
+
.filter((b) => b.trim())
|
|
269
|
+
.join('\n\n');
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// A ticket's description, as text: Jira Cloud's is a document, Data Center's
|
|
273
|
+
// and the others' are text already.
|
|
274
|
+
const asText = (value) => (value && typeof value === 'object' ? adfText(value) : typeof value === 'string' ? value : '').replace(/\r\n?/g, '\n').trim();
|
|
275
|
+
|
|
276
|
+
async function readJira(t, key, { description = false } = {}) {
|
|
277
|
+
if (!KEY.test(key)) return missing;
|
|
278
|
+
const r = await jiraGet(t, `/issue/${encodeURIComponent(key)}?fields=summary,status,assignee${description ? ',description' : ''}`);
|
|
279
|
+
if (r.status === 404) return missing;
|
|
280
|
+
if (refused(r.status)) return signInRefused;
|
|
281
|
+
if (r.status !== 200 || !r.data?.key) return answered('Jira', r.status);
|
|
282
|
+
const f = r.data.fields || {};
|
|
283
|
+
return {
|
|
284
|
+
ok: true,
|
|
285
|
+
ticket: {
|
|
286
|
+
key: r.data.key,
|
|
287
|
+
title: f.summary || '',
|
|
288
|
+
status: f.status?.name || '',
|
|
289
|
+
category: JIRA_CATEGORY[f.status?.statusCategory?.key] || 'progress',
|
|
290
|
+
assignee: f.assignee?.displayName || null,
|
|
291
|
+
url: `${t.url}/browse/${r.data.key}`,
|
|
292
|
+
...(description ? { description: asText(f.description) } : {}),
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function readLinear(t, key, { description = false } = {}) {
|
|
298
|
+
if (!KEY.test(key)) return missing;
|
|
299
|
+
const query = `query($id: String!) { issue(id: $id) { identifier title url state { name type } assignee { name }${description ? ' description' : ''} } }`;
|
|
300
|
+
const r = await request(endpoints.linear, { method: 'POST', headers: { Authorization: t.token }, body: { query, variables: { id: key } } });
|
|
301
|
+
const issue = r.data?.data?.issue;
|
|
302
|
+
if (r.status === 200 && issue?.identifier) {
|
|
303
|
+
return {
|
|
304
|
+
ok: true,
|
|
305
|
+
ticket: {
|
|
306
|
+
key: issue.identifier,
|
|
307
|
+
title: issue.title || '',
|
|
308
|
+
status: issue.state?.name || '',
|
|
309
|
+
category: LINEAR_STATE[issue.state?.type] || 'progress',
|
|
310
|
+
assignee: issue.assignee?.name || null,
|
|
311
|
+
url: typeof issue.url === 'string' && issue.url.startsWith('https://linear.app/') ? issue.url : null,
|
|
312
|
+
...(description ? { description: asText(issue.description) } : {}),
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
const errors = (r.data?.errors || []).map((e) => `${e.message || ''} ${e.extensions?.type || ''}`).join(' ');
|
|
317
|
+
if (refused(r.status) || /authenticat/i.test(errors)) return signInRefused;
|
|
318
|
+
if (/not found/i.test(errors)) return missing;
|
|
319
|
+
return answered('Linear', r.status);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function readGitHub(key, { description = false } = {}) {
|
|
323
|
+
const m = key.match(GITHUB);
|
|
324
|
+
if (!m) return missing;
|
|
325
|
+
const r = await gh(['api', `repos/${m[1]}/${m[2]}/issues/${m[3]}`]);
|
|
326
|
+
if (r.missing) return { ok: false, error: "GitHub's command-line tool, gh, isn't installed. Get it from cli.github.com." };
|
|
327
|
+
if (!r.ok) {
|
|
328
|
+
if (/HTTP (404|410)|Not Found/i.test(r.stderr || '')) return missing;
|
|
329
|
+
if (/HTTP 401|gh auth login|authentication/i.test(r.stderr || '')) return { ok: false, auth: true, error: "gh isn't signed in. Run gh auth login." };
|
|
330
|
+
return { ok: false, error: "gh couldn't read it." };
|
|
331
|
+
}
|
|
332
|
+
let d;
|
|
333
|
+
try {
|
|
334
|
+
d = JSON.parse(r.stdout);
|
|
335
|
+
} catch {
|
|
336
|
+
return { ok: false, error: "gh couldn't read it." };
|
|
337
|
+
}
|
|
338
|
+
// A pull request's number answers as an issue too.
|
|
339
|
+
const pull = Boolean(d.pull_request);
|
|
340
|
+
const done = pull ? Boolean(d.pull_request.merged_at) : d.state_reason !== 'not_planned';
|
|
341
|
+
return {
|
|
342
|
+
ok: true,
|
|
343
|
+
ticket: {
|
|
344
|
+
key: `${m[1]}/${m[2]}#${m[3]}`,
|
|
345
|
+
title: d.title || '',
|
|
346
|
+
status: d.state === 'open' ? 'Open' : pull ? (done ? 'Merged' : 'Closed') : done ? 'Closed' : 'Not planned',
|
|
347
|
+
category: d.state === 'open' ? 'progress' : done ? 'done' : 'closed',
|
|
348
|
+
assignee: d.assignee?.login || null,
|
|
349
|
+
url: `https://github.com/${m[1]}/${m[2]}/${pull ? 'pull' : 'issues'}/${m[3]}`,
|
|
350
|
+
pullRequest: pull,
|
|
351
|
+
...(description ? { description: asText(d.body) } : {}),
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function readZendesk(t, key, { description = false } = {}) {
|
|
357
|
+
const m = key.match(NUMBER);
|
|
358
|
+
if (!m) return missing;
|
|
359
|
+
const auth = t.auth === 'oauth' ? `Bearer ${t.token}` : basic(`${t.email}/token`, t.token);
|
|
360
|
+
const r = await request(`${t.url}/api/v2/tickets/${m[1]}.json`, { headers: { Authorization: auth } });
|
|
361
|
+
if (r.status === 404) return missing;
|
|
362
|
+
if (refused(r.status)) return signInRefused;
|
|
363
|
+
const z = r.data?.ticket;
|
|
364
|
+
if (r.status !== 200 || !z?.id) return answered('Zendesk', r.status);
|
|
365
|
+
return {
|
|
366
|
+
ok: true,
|
|
367
|
+
ticket: {
|
|
368
|
+
key: `#${z.id}`,
|
|
369
|
+
title: z.subject || '',
|
|
370
|
+
status: capital(z.status || ''),
|
|
371
|
+
category: ZENDESK_STATUS[z.status] || 'progress',
|
|
372
|
+
assignee: null,
|
|
373
|
+
url: `${t.url}/agent/tickets/${z.id}`,
|
|
374
|
+
// Its first comment.
|
|
375
|
+
...(description ? { description: asText(z.description) } : {}),
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// One ticket from one tracker: { ok: true, ticket: { key, title, status,
|
|
381
|
+
// category, assignee, url } }, with its description as text too if asked
|
|
382
|
+
// for; { ok: false, missing: true } when the tracker says there's no such
|
|
383
|
+
// ticket; else { ok: false, error }, with auth: true if the sign-in was
|
|
384
|
+
// refused. Nothing in an error comes from the token.
|
|
385
|
+
async function read(t, key, options = {}) {
|
|
386
|
+
try {
|
|
387
|
+
if (t.type === 'github') return await readGitHub(key, options);
|
|
388
|
+
if (!t.token) return { ok: false, auth: true, error: 'Set its token first.' };
|
|
389
|
+
if (t.type === 'jira') return await readJira(t, key, options);
|
|
390
|
+
if (t.type === 'linear') return await readLinear(t, key, options);
|
|
391
|
+
if (t.type === 'zendesk') return await readZendesk(t, key, options);
|
|
392
|
+
return missing;
|
|
393
|
+
} catch (err) {
|
|
394
|
+
return { ok: false, error: err.name === 'TimeoutError' ? "It didn't answer in time." : "Couldn't reach it." };
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ---- writing back -----------------------------------------------------------------
|
|
399
|
+
|
|
400
|
+
// What a write answers when the tracker won't let it, or fails.
|
|
401
|
+
const cantWrite = { ok: false, error: 'It refused: check that its token can write.' };
|
|
402
|
+
const failed = (status) => (refused(status) ? cantWrite : { ok: false, error: `It answered ${status}.` });
|
|
403
|
+
const zendeskAuth = (t) => (t.auth === 'oauth' ? `Bearer ${t.token}` : basic(`${t.email}/token`, t.token));
|
|
404
|
+
|
|
405
|
+
// A comment for Jira Cloud, in Atlassian Document Format: its paragraphs,
|
|
406
|
+
// with line breaks and links kept.
|
|
407
|
+
function adf(text) {
|
|
408
|
+
const inline = (paragraph) => {
|
|
409
|
+
const nodes = [];
|
|
410
|
+
paragraph.split('\n').forEach((line, i) => {
|
|
411
|
+
if (i) nodes.push({ type: 'hardBreak' });
|
|
412
|
+
let at = 0;
|
|
413
|
+
for (const m of line.matchAll(/https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]]/g)) {
|
|
414
|
+
if (m.index > at) nodes.push({ type: 'text', text: line.slice(at, m.index) });
|
|
415
|
+
nodes.push({ type: 'text', text: m[0], marks: [{ type: 'link', attrs: { href: m[0] } }] });
|
|
416
|
+
at = m.index + m[0].length;
|
|
417
|
+
}
|
|
418
|
+
if (at < line.length) nodes.push({ type: 'text', text: line.slice(at) });
|
|
419
|
+
});
|
|
420
|
+
return nodes;
|
|
421
|
+
};
|
|
422
|
+
const paragraphs = String(text).replace(/\r\n?/g, '\n').split(/\n{2,}/).filter((p) => p.trim());
|
|
423
|
+
return { type: 'doc', version: 1, content: paragraphs.map((p) => ({ type: 'paragraph', content: inline(p.trim()) })) };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const LINEAR_DONE_STATES = 'query($id: String!) { issue(id: $id) { id team { states(filter: { type: { eq: "completed" } }) { nodes { id name position } } } } }';
|
|
427
|
+
|
|
428
|
+
async function linear(t, query, variables) {
|
|
429
|
+
const r = await request(endpoints.linear, { method: 'POST', headers: { Authorization: t.token }, body: { query, variables } });
|
|
430
|
+
const errors = (r.data?.errors || []).map((e) => e.message || '').join(' ');
|
|
431
|
+
if (refused(r.status) || /authenticat|forbidden|permission/i.test(errors)) return { ...cantWrite, data: null };
|
|
432
|
+
if (r.status !== 200 || errors) return { ok: false, error: errors ? `Linear: ${errors.slice(0, 200)}` : `It answered ${r.status}.`, data: null };
|
|
433
|
+
return { ok: true, data: r.data.data };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// The ways to move a ticket to done: [{ id, name }]. Jira's are the
|
|
437
|
+
// transitions from its status into one that's done, which depend on its
|
|
438
|
+
// workflow; Linear's, its team's completed states. GitHub closes an issue as
|
|
439
|
+
// completed, and Zendesk solves a ticket.
|
|
440
|
+
async function doneMoves(t, key) {
|
|
441
|
+
try {
|
|
442
|
+
if (t.type === 'github') return { ok: true, moves: [{ id: 'completed', name: 'Close as completed' }] };
|
|
443
|
+
if (t.type === 'zendesk') return { ok: true, moves: [{ id: 'solved', name: 'Solved' }] };
|
|
444
|
+
if (!KEY.test(key)) return missing;
|
|
445
|
+
if (t.type === 'jira') {
|
|
446
|
+
const r = await jiraGet(t, `/issue/${encodeURIComponent(key)}/transitions`);
|
|
447
|
+
if (r.status !== 200) return failed(r.status);
|
|
448
|
+
const moves = (r.data?.transitions || []).filter((x) => x.to?.statusCategory?.key === 'done').map((x) => ({ id: String(x.id), name: x.name || x.to?.name || '' }));
|
|
449
|
+
return { ok: true, moves };
|
|
450
|
+
}
|
|
451
|
+
if (t.type === 'linear') {
|
|
452
|
+
const r = await linear(t, LINEAR_DONE_STATES, { id: key });
|
|
453
|
+
if (!r.ok) return r;
|
|
454
|
+
const nodes = r.data?.issue?.team?.states?.nodes || [];
|
|
455
|
+
return { ok: true, moves: [...nodes].sort((a, b) => a.position - b.position).map((s) => ({ id: s.id, name: s.name })) };
|
|
456
|
+
}
|
|
457
|
+
return missing;
|
|
458
|
+
} catch (err) {
|
|
459
|
+
return { ok: false, error: err.name === 'TimeoutError' ? "It didn't answer in time." : "Couldn't reach it." };
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// Comments on a ticket and moves it to done, as asked: { comment, publicReply,
|
|
464
|
+
// move }, where move is one of doneMoves()' IDs. Answers { ok, done }, where
|
|
465
|
+
// done lists what was done before anything failed: 'comment', 'move'.
|
|
466
|
+
async function write(t, key, { comment = null, publicReply = false, move = null } = {}) {
|
|
467
|
+
const done = [];
|
|
468
|
+
const fail = (r) => ({ ...r, done });
|
|
469
|
+
try {
|
|
470
|
+
if (t.type === 'github') {
|
|
471
|
+
const m = key.match(GITHUB);
|
|
472
|
+
if (!m) return fail(missing);
|
|
473
|
+
const issue = `repos/${m[1]}/${m[2]}/issues/${m[3]}`;
|
|
474
|
+
if (comment) {
|
|
475
|
+
const r = await gh(['api', '-X', 'POST', `${issue}/comments`, '-f', `body=${comment}`]);
|
|
476
|
+
if (!r.ok) return fail({ ok: false, error: r.missing ? "GitHub's command-line tool, gh, isn't installed. Get it from cli.github.com." : "gh couldn't post the comment." });
|
|
477
|
+
done.push('comment');
|
|
478
|
+
}
|
|
479
|
+
if (move) {
|
|
480
|
+
const r = await gh(['api', '-X', 'PATCH', issue, '-f', 'state=closed', '-f', 'state_reason=completed']);
|
|
481
|
+
if (!r.ok) return fail({ ok: false, error: "gh couldn't close it." });
|
|
482
|
+
done.push('move');
|
|
483
|
+
}
|
|
484
|
+
return { ok: true, done };
|
|
485
|
+
}
|
|
486
|
+
if (!t.token) return fail({ ok: false, auth: true, error: 'Set its token first.' });
|
|
487
|
+
if (t.type === 'jira') {
|
|
488
|
+
if (!KEY.test(key)) return fail(missing);
|
|
489
|
+
const issue = `/issue/${encodeURIComponent(key)}`;
|
|
490
|
+
if (comment) {
|
|
491
|
+
// Cloud takes a document; Data Center, plain text.
|
|
492
|
+
const r = await jiraCall(t, `${issue}/comment`, { method: 'POST', body: { body: t.email ? adf(comment) : comment } });
|
|
493
|
+
if (r.status !== 201 && r.status !== 200) return fail(failed(r.status));
|
|
494
|
+
done.push('comment');
|
|
495
|
+
}
|
|
496
|
+
if (move) {
|
|
497
|
+
const r = await jiraCall(t, `${issue}/transitions`, { method: 'POST', body: { transition: { id: String(move) } } });
|
|
498
|
+
if (r.status !== 204 && r.status !== 200) return fail(failed(r.status));
|
|
499
|
+
done.push('move');
|
|
500
|
+
}
|
|
501
|
+
return { ok: true, done };
|
|
502
|
+
}
|
|
503
|
+
if (t.type === 'linear') {
|
|
504
|
+
if (!KEY.test(key)) return fail(missing);
|
|
505
|
+
const found = await linear(t, 'query($id: String!) { issue(id: $id) { id } }', { id: key });
|
|
506
|
+
const issueId = found.data?.issue?.id;
|
|
507
|
+
if (!found.ok || !issueId) return fail(found.ok ? missing : found);
|
|
508
|
+
if (comment) {
|
|
509
|
+
const r = await linear(t, 'mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success } }', { input: { issueId, body: comment } });
|
|
510
|
+
if (!r.ok || !r.data?.commentCreate?.success) return fail(r.ok ? { ok: false, error: "Linear didn't take the comment." } : r);
|
|
511
|
+
done.push('comment');
|
|
512
|
+
}
|
|
513
|
+
if (move) {
|
|
514
|
+
const r = await linear(t, 'mutation($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }', { id: issueId, input: { stateId: String(move) } });
|
|
515
|
+
if (!r.ok || !r.data?.issueUpdate?.success) return fail(r.ok ? { ok: false, error: "Linear didn't move it." } : r);
|
|
516
|
+
done.push('move');
|
|
517
|
+
}
|
|
518
|
+
return { ok: true, done };
|
|
519
|
+
}
|
|
520
|
+
if (t.type === 'zendesk') {
|
|
521
|
+
const m = key.match(NUMBER);
|
|
522
|
+
if (!m) return fail(missing);
|
|
523
|
+
// One request does both. A comment is an internal note unless it's a
|
|
524
|
+
// public reply, which emails the requester, as solving does.
|
|
525
|
+
const ticket = {};
|
|
526
|
+
if (comment) ticket.comment = { body: comment, public: Boolean(publicReply) };
|
|
527
|
+
if (move) ticket.status = 'solved';
|
|
528
|
+
if (!Object.keys(ticket).length) return { ok: true, done };
|
|
529
|
+
const r = await request(`${t.url}/api/v2/tickets/${m[1]}.json`, { method: 'PUT', headers: { Authorization: zendeskAuth(t) }, body: { ticket } });
|
|
530
|
+
if (r.status !== 200) return fail(failed(r.status));
|
|
531
|
+
if (comment) done.push('comment');
|
|
532
|
+
if (move) done.push('move');
|
|
533
|
+
return { ok: true, done };
|
|
534
|
+
}
|
|
535
|
+
return fail(missing);
|
|
536
|
+
} catch (err) {
|
|
537
|
+
return fail({ ok: false, error: err.name === 'TimeoutError' ? "It didn't answer in time." : "Couldn't reach it." });
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
module.exports = { TYPES, clean, cleanList, forPage, save, remove, test, read, doneMoves, write, adf, endpoints, useGh };
|