@kud/jira-cli 0.2.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -0
  3. package/dist/index.js +1412 -0
  4. package/package.json +49 -0
package/dist/index.js ADDED
@@ -0,0 +1,1412 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/api/client.ts
7
+ var jiraApiError = (status, method, url, body) => Object.assign(
8
+ new Error(`Jira API ${status} ${method} ${url}: ${truncate(body)}`),
9
+ { name: "JiraApiError", status, method, url, body }
10
+ );
11
+ var isJiraApiError = (e) => e instanceof Error && e.name === "JiraApiError";
12
+ var truncate = (s, max = 400) => s.length > max ? `${s.slice(0, max)}\u2026` : s;
13
+ var normalizeBaseUrl = (raw) => {
14
+ const trimmed = raw.trim().replace(/\/+$/, "");
15
+ return /^https?:\/\//.test(trimmed) ? trimmed : `https://${trimmed}`;
16
+ };
17
+ var DEFAULT_FIELDS = [
18
+ "summary",
19
+ "status",
20
+ "assignee",
21
+ "issuetype",
22
+ "priority",
23
+ "project",
24
+ "labels",
25
+ "updated"
26
+ ];
27
+ var createJiraClient = (options) => {
28
+ const doFetch = options.fetch ?? globalThis.fetch;
29
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
30
+ const customFields = options.customFields ?? [];
31
+ const authHeader = `Basic ${Buffer.from(`${options.email}:${options.token}`).toString("base64")}`;
32
+ const request = async (path, init = {}) => {
33
+ const url = path.startsWith("http") ? path : `${baseUrl}${path.startsWith("/") ? "" : "/"}${path}`;
34
+ const res = await doFetch(url, {
35
+ ...init,
36
+ headers: {
37
+ Authorization: authHeader,
38
+ "Content-Type": "application/json",
39
+ Accept: "application/json",
40
+ // Jira localises error bodies from the account's language. Errors here
41
+ // are read by scripts and pasted into issues, so pin them to English.
42
+ "Accept-Language": "en",
43
+ ...init.headers
44
+ }
45
+ });
46
+ if (init.raw) return res;
47
+ if (!res.ok) {
48
+ throw jiraApiError(
49
+ res.status,
50
+ init.method ?? "GET",
51
+ url,
52
+ await res.text()
53
+ );
54
+ }
55
+ if (res.status === 204) return void 0;
56
+ return await res.json();
57
+ };
58
+ const fieldList = (extra) => [
59
+ .../* @__PURE__ */ new Set([
60
+ ...extra ?? DEFAULT_FIELDS,
61
+ ...customFields.map((f) => f.id),
62
+ ...options.sprintField ? [options.sprintField] : []
63
+ ])
64
+ ];
65
+ const searchPage = (jql, opts = {}) => request("/rest/api/3/search/jql", {
66
+ method: "POST",
67
+ body: JSON.stringify({
68
+ jql,
69
+ fields: fieldList(opts.fields),
70
+ maxResults: opts.maxResults ?? 50,
71
+ ...opts.nextPageToken ? { nextPageToken: opts.nextPageToken } : {},
72
+ ...opts.expand ? { expand: opts.expand } : {}
73
+ })
74
+ });
75
+ const searchIssues = async (jql, opts = {}) => {
76
+ const limit = opts.limit ?? 50;
77
+ const issues = [];
78
+ const seenTokens = /* @__PURE__ */ new Set();
79
+ let token = opts.nextPageToken;
80
+ while (issues.length < limit) {
81
+ const page = await searchPage(jql, {
82
+ ...opts,
83
+ nextPageToken: token,
84
+ maxResults: Math.min(100, limit - issues.length)
85
+ });
86
+ if (page.issues.length === 0) break;
87
+ issues.push(...page.issues);
88
+ const next = page.nextPageToken;
89
+ if (!next || page.isLast || seenTokens.has(next)) break;
90
+ seenTokens.add(next);
91
+ token = next;
92
+ }
93
+ return issues.slice(0, limit);
94
+ };
95
+ return {
96
+ request,
97
+ customFields,
98
+ sprintField: options.sprintField,
99
+ searchPage,
100
+ searchIssues,
101
+ getIssue: (key) => request(
102
+ `/rest/api/3/issue/${encodeURIComponent(key)}?fields=${fieldList([
103
+ ...DEFAULT_FIELDS,
104
+ "description",
105
+ "comment",
106
+ "reporter",
107
+ "created",
108
+ "attachment"
109
+ ]).join(",")}`
110
+ ),
111
+ getTransitions: (key) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/transitions`),
112
+ transitionIssue: (key, transitionId) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/transitions`, {
113
+ method: "POST",
114
+ body: JSON.stringify({ transition: { id: transitionId } })
115
+ }),
116
+ addComment: (key, body) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/comment`, {
117
+ method: "POST",
118
+ body: JSON.stringify({ body })
119
+ }),
120
+ getMe: () => request("/rest/api/3/myself"),
121
+ getFields: () => request("/rest/api/3/field"),
122
+ getProjects: () => request("/rest/api/3/project?expand=description"),
123
+ getBoards: () => request("/rest/agile/1.0/board"),
124
+ getSprints: (boardId, state) => request(
125
+ `/rest/agile/1.0/board/${boardId}/sprint${state ? `?state=${state}` : ""}`
126
+ ),
127
+ // ── issues ────────────────────────────────────────────────────────────
128
+ createIssue: (fields) => request("/rest/api/3/issue", {
129
+ method: "POST",
130
+ body: JSON.stringify({ fields })
131
+ }),
132
+ updateIssue: (key, fields) => request(`/rest/api/3/issue/${encodeURIComponent(key)}`, {
133
+ method: "PUT",
134
+ body: JSON.stringify({ fields })
135
+ }),
136
+ deleteIssue: (key, deleteSubtasks = false) => request(
137
+ `/rest/api/3/issue/${encodeURIComponent(key)}?deleteSubtasks=${deleteSubtasks}`,
138
+ { method: "DELETE" }
139
+ ),
140
+ assignIssue: (key, accountId) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/assignee`, {
141
+ method: "PUT",
142
+ body: JSON.stringify({ accountId })
143
+ }),
144
+ getComments: (key) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/comment`),
145
+ deleteComment: (key, commentId) => request(
146
+ `/rest/api/3/issue/${encodeURIComponent(key)}/comment/${encodeURIComponent(commentId)}`,
147
+ { method: "DELETE" }
148
+ ),
149
+ getWatchers: (key) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/watchers`),
150
+ addWatcher: (key, accountId) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/watchers`, {
151
+ method: "POST",
152
+ body: JSON.stringify(accountId)
153
+ }),
154
+ removeWatcher: (key, accountId) => request(
155
+ `/rest/api/3/issue/${encodeURIComponent(key)}/watchers?accountId=${encodeURIComponent(accountId)}`,
156
+ { method: "DELETE" }
157
+ ),
158
+ getWorklogs: (key) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/worklog`),
159
+ addWorklog: (key, body) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/worklog`, {
160
+ method: "POST",
161
+ body: JSON.stringify(body)
162
+ }),
163
+ getChangelog: (key) => request(`/rest/api/3/issue/${encodeURIComponent(key)}/changelog`),
164
+ getIssueLinkTypes: () => request("/rest/api/3/issueLinkType"),
165
+ linkIssues: (type, inwardKey, outwardKey) => request("/rest/api/3/issueLink", {
166
+ method: "POST",
167
+ body: JSON.stringify({
168
+ type: { name: type },
169
+ inwardIssue: { key: inwardKey },
170
+ outwardIssue: { key: outwardKey }
171
+ })
172
+ }),
173
+ // ── projects ──────────────────────────────────────────────────────────
174
+ getProject: (key) => request(
175
+ `/rest/api/3/project/${encodeURIComponent(key)}?expand=description,lead,url`
176
+ ),
177
+ getProjectVersions: (key) => request(`/rest/api/3/project/${encodeURIComponent(key)}/versions`),
178
+ getProjectComponents: (key) => request(`/rest/api/3/project/${encodeURIComponent(key)}/components`),
179
+ getProjectStatuses: (key) => request(`/rest/api/3/project/${encodeURIComponent(key)}/statuses`),
180
+ // ── agile ─────────────────────────────────────────────────────────────
181
+ getBoard: (id) => request(`/rest/agile/1.0/board/${id}`),
182
+ getBoardIssues: (id, jql) => request(
183
+ `/rest/agile/1.0/board/${id}/issue${jql ? `?jql=${encodeURIComponent(jql)}` : ""}`
184
+ ),
185
+ getBacklog: (id) => request(`/rest/agile/1.0/board/${id}/backlog`),
186
+ getSprint: (id) => request(`/rest/agile/1.0/sprint/${id}`),
187
+ getSprintIssues: (id) => request(`/rest/agile/1.0/sprint/${id}/issue`),
188
+ getBoardEpics: (id) => request(`/rest/agile/1.0/board/${id}/epic`),
189
+ getEpicIssues: (id) => request(`/rest/agile/1.0/epic/${encodeURIComponent(id)}/issue`),
190
+ // ── people ────────────────────────────────────────────────────────────
191
+ searchUsers: (query, maxResults = 20) => request(
192
+ `/rest/api/3/user/search?query=${encodeURIComponent(query)}&maxResults=${maxResults}`
193
+ ),
194
+ searchAssignableUsers: (query, projectKey, maxResults = 20) => request(
195
+ `/rest/api/3/user/assignable/search?query=${encodeURIComponent(query)}&project=${encodeURIComponent(projectKey)}&maxResults=${maxResults}`
196
+ ),
197
+ // ── instance metadata ─────────────────────────────────────────────────
198
+ getIssueTypes: () => request("/rest/api/3/issuetype"),
199
+ getPriorities: () => request("/rest/api/3/priority"),
200
+ getResolutions: () => request("/rest/api/3/resolution"),
201
+ getStatuses: () => request("/rest/api/3/status"),
202
+ getLabels: () => request("/rest/api/3/label?maxResults=1000"),
203
+ getFilters: () => request("/rest/api/3/filter/search?expand=jql&maxResults=50"),
204
+ getDashboards: () => request("/rest/api/3/dashboard"),
205
+ getServerInfo: () => request("/rest/api/3/serverInfo"),
206
+ getMyPermissions: (projectKey) => request(
207
+ `/rest/api/3/mypermissions${projectKey ? `?projectKey=${encodeURIComponent(projectKey)}` : ""}`
208
+ ),
209
+ /**
210
+ * The count the removed `total` field used to give. Deliberately named
211
+ * approximate because that is what Atlassian guarantees — it is an index
212
+ * estimate, not a scan, and will disagree with a full page walk.
213
+ */
214
+ approximateCount: (jql) => request("/rest/api/3/search/approximate-count", {
215
+ method: "POST",
216
+ body: JSON.stringify({ jql })
217
+ })
218
+ };
219
+ };
220
+
221
+ // src/commands/attachment.ts
222
+ import { writeFileSync } from "fs";
223
+ import { basename, resolve } from "path";
224
+
225
+ // src/api/attachments.ts
226
+ var mediaRefs = (node) => {
227
+ if (!node || typeof node !== "object") return [];
228
+ const n = node;
229
+ const here = n.type === "media" ? [
230
+ {
231
+ ...typeof n.attrs?.["id"] === "string" ? { id: n.attrs["id"] } : {},
232
+ ...typeof n.attrs?.["alt"] === "string" ? { filename: n.attrs["alt"] } : {}
233
+ }
234
+ ] : [];
235
+ return [...here, ...(n.content ?? []).flatMap(mediaRefs)];
236
+ };
237
+ var locateAttachments = (issue) => {
238
+ const attachments = issue.fields["attachment"] ?? [];
239
+ const origins = /* @__PURE__ */ new Map();
240
+ const note = (ref, origin) => {
241
+ const match = attachments.find(
242
+ (a) => ref.filename !== void 0 && a.filename === ref.filename || ref.id !== void 0 && a.id === ref.id
243
+ );
244
+ if (!match) return;
245
+ origins.set(match.id, [...origins.get(match.id) ?? [], origin]);
246
+ };
247
+ for (const ref of mediaRefs(issue.fields.description))
248
+ note(ref, { kind: "description" });
249
+ for (const comment of issue.fields.comment?.comments ?? [])
250
+ for (const ref of mediaRefs(comment.body))
251
+ note(ref, {
252
+ kind: "comment",
253
+ commentId: comment.id,
254
+ author: comment.author?.displayName
255
+ });
256
+ return attachments.map((a) => ({
257
+ ...a,
258
+ origins: origins.get(a.id) ?? [{ kind: "issue" }]
259
+ }));
260
+ };
261
+ var TEXTUAL = /^(text\/|application\/(json|xml|x-yaml|yaml|javascript|sql|x-sh))/;
262
+ var TEXTUAL_EXTENSIONS = /\.(txt|md|markdown|log|json|ya?ml|csv|tsv|xml|html?|css|jsx?|tsx?|py|rb|go|rs|java|kt|sh|zsh|bash|sql|ini|toml|conf|env|diff|patch)$/i;
263
+ var isTextual = (attachment) => TEXTUAL.test(attachment.mimeType) || TEXTUAL_EXTENSIONS.test(attachment.filename);
264
+ var downloadAttachment = async (client, id, fetchImpl = globalThis.fetch) => {
265
+ const res = await client.request(
266
+ `/rest/api/3/attachment/content/${encodeURIComponent(id)}`,
267
+ { redirect: "manual", raw: true }
268
+ );
269
+ const location = res.headers.get("location");
270
+ const final = res.status >= 300 && res.status < 400 && location ? await fetchImpl(location) : res;
271
+ if (!final.ok) {
272
+ throw new Error(
273
+ `could not download attachment ${id}: ${final.status} ${final.statusText}`
274
+ );
275
+ }
276
+ return {
277
+ bytes: new Uint8Array(await final.arrayBuffer()),
278
+ mimeType: final.headers.get("content-type")
279
+ };
280
+ };
281
+
282
+ // src/output/format.ts
283
+ var identity = (s) => s;
284
+ var wrap = (open, close) => (s) => `\x1B[${open}m${s}\x1B[${close}m`;
285
+ var palette = (isTty, env = process.env) => {
286
+ const on = isTty && !env["NO_COLOR"] && env["TERM"] !== "dumb";
287
+ const c = (open, close) => on ? wrap(open, close) : identity;
288
+ return {
289
+ on,
290
+ dim: c("2", "22"),
291
+ bold: c("1", "22")
292
+ };
293
+ };
294
+ var ANSI = /\u001b\[[0-9;]*m/g;
295
+ var width = (s) => s.replace(ANSI, "").length;
296
+ var pad = (s, to) => s + " ".repeat(Math.max(0, to - width(s)));
297
+ var table = (rows, columns) => {
298
+ if (rows.length === 0) return "";
299
+ const cells = rows.map((r) => columns.map((c) => c.value(r)));
300
+ const widths = columns.map(
301
+ (c, i) => Math.max(width(c.header), ...cells.map((row2) => width(row2[i])))
302
+ );
303
+ const line = (values) => values.map((v, i) => {
304
+ const w = widths[i];
305
+ return columns[i]?.align === "right" ? " ".repeat(Math.max(0, w - width(v))) + v : pad(v, w);
306
+ }).join(" ").trimEnd();
307
+ return [line(columns.map((c) => c.header)), ...cells.map(line)].join("\n");
308
+ };
309
+ var truncate2 = (s, max) => s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}\u2026`;
310
+
311
+ // src/config.ts
312
+ import { readFileSync } from "fs";
313
+ import { homedir } from "os";
314
+ import { join } from "path";
315
+ var configPath = () => process.env["JIRA_CONFIG_FILE"] || join(
316
+ process.env["XDG_CONFIG_HOME"] || join(homedir(), ".config"),
317
+ "jira",
318
+ "config.json"
319
+ );
320
+ var readFileConfig = (path = configPath()) => {
321
+ let raw;
322
+ try {
323
+ raw = readFileSync(path, "utf8");
324
+ } catch {
325
+ return {};
326
+ }
327
+ const parsed = JSON.parse(raw);
328
+ if (parsed.customFields && !Array.isArray(parsed.customFields))
329
+ throw new Error(`${path}: customFields must be an array of {id,label}`);
330
+ if ("token" in parsed || "apiToken" in parsed)
331
+ throw new Error(
332
+ `${path} contains a token. Tokens belong in ATLASSIAN_API_TOKEN, not in a file that gets shared and backed up \u2014 remove it.`
333
+ );
334
+ return parsed;
335
+ };
336
+ var loadConfig = (env = process.env, path = configPath()) => {
337
+ const file = readFileConfig(path);
338
+ const baseUrl = env["ATLASSIAN_BASE_URL"] || file.baseUrl;
339
+ const email = env["ATLASSIAN_USER_EMAIL"] || file.email;
340
+ const token = env["ATLASSIAN_API_TOKEN"];
341
+ const missing = [
342
+ ["ATLASSIAN_BASE_URL", baseUrl],
343
+ ["ATLASSIAN_USER_EMAIL", email],
344
+ ["ATLASSIAN_API_TOKEN", token]
345
+ ].filter(([, v]) => !v).map(([k]) => k);
346
+ if (missing.length > 0) return { missing };
347
+ return {
348
+ config: {
349
+ ...file,
350
+ baseUrl: normalizeBaseUrl(baseUrl),
351
+ email,
352
+ token
353
+ }
354
+ };
355
+ };
356
+
357
+ // src/commands/context.ts
358
+ var exitError = (code, message) => Object.assign(new Error(message), { name: "ExitError", code });
359
+ var isExitError = (e) => e instanceof Error && e.name === "ExitError";
360
+ var context = () => {
361
+ const loaded = loadConfig();
362
+ if ("missing" in loaded) {
363
+ throw exitError(
364
+ 2,
365
+ `missing environment variables: ${loaded.missing.join(", ")}
366
+
367
+ Set them, then retry:
368
+ export ATLASSIAN_BASE_URL=myorg.atlassian.net
369
+ export ATLASSIAN_USER_EMAIL=you@example.com
370
+ export ATLASSIAN_API_TOKEN=... # id.atlassian.com/manage-profile/security/api-tokens`
371
+ );
372
+ }
373
+ const { config } = loaded;
374
+ return {
375
+ config,
376
+ client: createJiraClient(config),
377
+ out: palette(process.stdout.isTTY === true)
378
+ };
379
+ };
380
+ var printJson = (value) => {
381
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
382
+ `);
383
+ };
384
+
385
+ // src/commands/attachment.ts
386
+ var humanSize = (bytes) => {
387
+ const units = ["B", "KB", "MB", "GB"];
388
+ const exponent = Math.min(
389
+ units.length - 1,
390
+ Math.floor(Math.log(Math.max(bytes, 1)) / Math.log(1024))
391
+ );
392
+ const value = bytes / 1024 ** exponent;
393
+ return `${exponent === 0 ? value : value.toFixed(1)}${units[exponent]}`;
394
+ };
395
+ var describeOrigin = (a) => a.origins.map(
396
+ (o) => o.kind === "comment" ? `comment by ${o.author ?? "unknown"}` : o.kind === "description" ? "description" : "issue"
397
+ ).join(", ");
398
+ var pick = (attachments, selector) => {
399
+ const byId = attachments.find((a) => a.id === selector);
400
+ if (byId) return byId;
401
+ const matches = attachments.filter(
402
+ (a) => a.filename === selector || a.filename.toLowerCase().includes(selector.toLowerCase())
403
+ );
404
+ if (matches.length === 1) return matches[0];
405
+ if (matches.length === 0)
406
+ throw exitError(
407
+ 1,
408
+ `no attachment matching '${selector}'. Available: ${attachments.map((a) => a.filename).join(", ") || "none"}`
409
+ );
410
+ throw exitError(
411
+ 1,
412
+ `'${selector}' matches ${matches.length} attachments: ${matches.map((a) => `${a.filename} (${a.id})`).join(", ")}. Use the id.`
413
+ );
414
+ };
415
+ var registerAttachmentCommands = (program2) => {
416
+ const attachment = program2.command("attachment").alias("attach").description("list and read files attached to an issue");
417
+ attachment.command("list <key>").alias("ls").description("list the files attached to an issue").option("--json", "emit JSON").action(async (key, options) => {
418
+ const ctx = context();
419
+ const attachments = locateAttachments(await ctx.client.getIssue(key));
420
+ if (options.json) return printJson(attachments);
421
+ if (attachments.length === 0) {
422
+ process.stderr.write(`${key} has no attachments
423
+ `);
424
+ return;
425
+ }
426
+ process.stdout.write(
427
+ `${table(attachments, [
428
+ { header: "ID", value: (a) => a.id },
429
+ { header: "FILENAME", value: (a) => a.filename },
430
+ { header: "SIZE", value: (a) => humanSize(a.size), align: "right" },
431
+ { header: "TYPE", value: (a) => a.mimeType },
432
+ { header: "FROM", value: (a) => describeOrigin(a) }
433
+ ])}
434
+ `
435
+ );
436
+ });
437
+ attachment.command("read <key> <selector>").alias("cat").description("print a text attachment to stdout").action(async (key, selector) => {
438
+ const ctx = context();
439
+ const attachments = locateAttachments(await ctx.client.getIssue(key));
440
+ const target = pick(attachments, selector);
441
+ const { bytes, mimeType } = await downloadAttachment(
442
+ ctx.client,
443
+ target.id
444
+ );
445
+ if (!isTextual(target) && !mimeType?.startsWith("text/")) {
446
+ throw exitError(
447
+ 1,
448
+ `${target.filename} is ${target.mimeType}, not text. Use: jira attachment get ${key} ${selector} --output <path>`
449
+ );
450
+ }
451
+ process.stdout.write(new TextDecoder().decode(bytes));
452
+ });
453
+ attachment.command("get <key> <selector>").alias("download").description("download an attachment to a file").option("-o, --output <path>", "destination path, or '-' for stdout").action(
454
+ async (key, selector, options) => {
455
+ const ctx = context();
456
+ const attachments = locateAttachments(await ctx.client.getIssue(key));
457
+ const target = pick(attachments, selector);
458
+ const { bytes } = await downloadAttachment(ctx.client, target.id);
459
+ if (options.output === "-") {
460
+ process.stdout.write(bytes);
461
+ return;
462
+ }
463
+ const destination = resolve(
464
+ options.output ?? basename(target.filename) ?? target.id
465
+ );
466
+ writeFileSync(destination, bytes);
467
+ process.stderr.write(
468
+ `${target.filename} \u2192 ${destination} (${humanSize(bytes.length)})
469
+ `
470
+ );
471
+ }
472
+ );
473
+ };
474
+
475
+ // src/commands/agile.ts
476
+ var issueRows = [
477
+ { header: "KEY", value: (i) => i.key },
478
+ { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
479
+ { header: "SUMMARY", value: (i) => truncate2(i.fields.summary ?? "", 72) },
480
+ {
481
+ header: "ASSIGNEE",
482
+ value: (i) => i.fields.assignee?.displayName ?? "unassigned"
483
+ }
484
+ ];
485
+ var writeIssues = (issues, json) => {
486
+ if (json) return printJson(issues);
487
+ if (issues.length === 0) {
488
+ process.stderr.write("no issues\n");
489
+ return;
490
+ }
491
+ process.stdout.write(`${table(issues, issueRows)}
492
+ `);
493
+ };
494
+ var registerBoardCommands = (program2) => {
495
+ const board = program2.command("board").description("boards, backlogs and epics");
496
+ board.command("list").alias("ls").description("list boards").option("--json", "emit JSON").action(async (options) => {
497
+ const ctx = context();
498
+ const { values } = await ctx.client.getBoards();
499
+ if (options.json) return printJson(values);
500
+ process.stdout.write(
501
+ `${table(values, [
502
+ { header: "ID", value: (b) => String(b.id) },
503
+ { header: "NAME", value: (b) => b.name },
504
+ { header: "TYPE", value: (b) => b.type ?? "\u2014" }
505
+ ])}
506
+ `
507
+ );
508
+ });
509
+ board.command("issues <id>").description("issues on a board").option("-q, --jql <jql>", "narrow with JQL").option("--json", "emit JSON").action(async (id, options) => {
510
+ const ctx = context();
511
+ const { issues } = await ctx.client.getBoardIssues(
512
+ Number(id),
513
+ options.jql
514
+ );
515
+ writeIssues(issues, options.json);
516
+ });
517
+ board.command("backlog <id>").description("the backlog for a board").option("--json", "emit JSON").action(async (id, options) => {
518
+ const ctx = context();
519
+ const { issues } = await ctx.client.getBacklog(Number(id));
520
+ writeIssues(issues, options.json);
521
+ });
522
+ board.command("epics <id>").description("epics on a board").option("--json", "emit JSON").action(async (id, options) => {
523
+ const ctx = context();
524
+ const { values } = await ctx.client.getBoardEpics(Number(id));
525
+ if (options.json) return printJson(values);
526
+ process.stdout.write(
527
+ `${table(values, [
528
+ { header: "KEY", value: (e) => e.key },
529
+ { header: "NAME", value: (e) => e.name },
530
+ { header: "DONE", value: (e) => e.done ? "yes" : "no" }
531
+ ])}
532
+ `
533
+ );
534
+ });
535
+ };
536
+ var registerSprintCommands = (program2) => {
537
+ const sprint = program2.command("sprint").description("sprints and their work");
538
+ sprint.command("list <boardId>").alias("ls").description("sprints on a board").option(
539
+ "--state <state>",
540
+ "active, future or closed; comma-separate to combine"
541
+ ).option("--json", "emit JSON").action(
542
+ async (boardId, options) => {
543
+ const ctx = context();
544
+ const { values } = await ctx.client.getSprints(
545
+ Number(boardId),
546
+ options.state
547
+ );
548
+ if (options.json) return printJson(values);
549
+ process.stdout.write(
550
+ `${table(values, [
551
+ { header: "ID", value: (s) => String(s.id) },
552
+ { header: "NAME", value: (s) => s.name },
553
+ { header: "STATE", value: (s) => s.state },
554
+ { header: "ENDS", value: (s) => s.endDate?.slice(0, 10) ?? "\u2014" }
555
+ ])}
556
+ `
557
+ );
558
+ }
559
+ );
560
+ sprint.command("issues <id>").description("issues in a sprint").option("--json", "emit JSON").action(async (id, options) => {
561
+ const ctx = context();
562
+ const { issues } = await ctx.client.getSprintIssues(Number(id));
563
+ writeIssues(issues, options.json);
564
+ });
565
+ sprint.command("view <id>").description("show one sprint").option("--json", "emit JSON").action(async (id, options) => {
566
+ const ctx = context();
567
+ const found = await ctx.client.getSprint(Number(id));
568
+ if (options.json) return printJson(found);
569
+ const { dim } = ctx.out;
570
+ process.stdout.write(
571
+ `${[
572
+ found.name,
573
+ `${dim("state")} ${found.state}`,
574
+ `${dim("start")} ${found.startDate?.slice(0, 10) ?? "\u2014"}`,
575
+ `${dim("end")} ${found.endDate?.slice(0, 10) ?? "\u2014"}`
576
+ ].join("\n")}
577
+ `
578
+ );
579
+ });
580
+ };
581
+ var registerEpicCommands = (program2) => {
582
+ program2.command("epic <key>").description("issues under an epic").option("--json", "emit JSON").action(async (key, options) => {
583
+ const ctx = context();
584
+ const { issues } = await ctx.client.getEpicIssues(key);
585
+ writeIssues(issues, options.json);
586
+ });
587
+ };
588
+
589
+ // src/commands/issue.ts
590
+ import { execFile } from "child_process";
591
+
592
+ // src/api/adf.ts
593
+ var markUp = (text, marks) => (marks ?? []).reduce((acc, mark) => {
594
+ if (mark.type === "code") return `\`${acc}\``;
595
+ if (mark.type === "strong") return `**${acc}**`;
596
+ if (mark.type === "em") return `_${acc}_`;
597
+ if (mark.type === "strike") return `~~${acc}~~`;
598
+ if (mark.type === "link") return `[${acc}](${mark.attrs?.["href"] ?? ""})`;
599
+ return acc;
600
+ }, text);
601
+ var resolveMedia = () => void 0;
602
+ var children = (node, sep = "") => (node.content ?? []).map(render).join(sep);
603
+ var listItems = (node, bullet) => (node.content ?? []).map((item, i) => {
604
+ const body = children(item, "\n\n").trim();
605
+ const [first = "", ...rest] = body.split("\n");
606
+ const marker = bullet(i);
607
+ const indent = " ".repeat(marker.length);
608
+ return [
609
+ `${marker}${first}`,
610
+ ...rest.map((l) => l ? `${indent}${l}` : l)
611
+ ].join("\n");
612
+ }).join("\n");
613
+ var row = (node) => `| ${(node.content ?? []).map((cell) => children(cell, " ").trim().replace(/\n+/g, " ")).join(" | ")} |`;
614
+ var renderTable = (node) => {
615
+ const rows = node.content ?? [];
616
+ if (rows.length === 0) return "";
617
+ const isHeader = (r) => (r.content ?? []).some((c) => c.type === "tableHeader");
618
+ const [first] = rows;
619
+ const rendered = rows.map(row);
620
+ if (first && isHeader(first)) {
621
+ const columns = (first.content ?? []).length;
622
+ rendered.splice(1, 0, `|${" --- |".repeat(columns)}`);
623
+ }
624
+ return rendered.join("\n");
625
+ };
626
+ var render = (node) => {
627
+ switch (node.type) {
628
+ case "doc":
629
+ return children(node, "\n\n");
630
+ case "paragraph":
631
+ return children(node);
632
+ case "text":
633
+ return markUp(node.text ?? "", node.marks);
634
+ case "hardBreak":
635
+ return "\n";
636
+ case "heading":
637
+ return `${"#".repeat(Number(node.attrs?.["level"] ?? 1))} ${children(node)}`;
638
+ case "bulletList":
639
+ return listItems(node, () => "- ");
640
+ case "orderedList":
641
+ return listItems(
642
+ node,
643
+ (i) => `${Number(node.attrs?.["order"] ?? 1) + i}. `
644
+ );
645
+ case "codeBlock":
646
+ return `\`\`\`${node.attrs?.["language"] ?? ""}
647
+ ${children(node)}
648
+ \`\`\``;
649
+ case "blockquote":
650
+ return children(node, "\n\n").split("\n").map((l) => `> ${l}`).join("\n");
651
+ case "panel":
652
+ return `> [!${String(node.attrs?.["panelType"] ?? "note").toUpperCase()}]
653
+ ${children(
654
+ node,
655
+ "\n\n"
656
+ ).split("\n").map((l) => `> ${l}`).join("\n")}`;
657
+ case "rule":
658
+ return "---";
659
+ case "table":
660
+ return renderTable(node);
661
+ case "mediaSingle":
662
+ case "mediaGroup":
663
+ return children(node, "\n");
664
+ case "media": {
665
+ const alt = node.attrs?.["alt"];
666
+ if (typeof alt === "string" && alt) return `[attachment: ${alt}]`;
667
+ const id = String(node.attrs?.["id"] ?? "");
668
+ const name = resolveMedia(id);
669
+ return name ? `[attachment: ${name}]` : `[attachment: ${id || "unknown"}]`;
670
+ }
671
+ case "mention": {
672
+ const label = String(node.attrs?.["text"] ?? node.attrs?.["id"] ?? "");
673
+ return label.startsWith("@") ? label : `@${label}`;
674
+ }
675
+ case "emoji":
676
+ return String(node.attrs?.["text"] ?? node.attrs?.["shortName"] ?? "");
677
+ case "date":
678
+ return String(node.attrs?.["timestamp"] ?? "");
679
+ case "status":
680
+ return `[${String(node.attrs?.["text"] ?? "").toUpperCase()}]`;
681
+ case "inlineCard":
682
+ return String(node.attrs?.["url"] ?? "");
683
+ default:
684
+ return children(node, "\n\n");
685
+ }
686
+ };
687
+ var adfToMarkdown = (doc, media) => {
688
+ if (typeof doc === "string") return doc;
689
+ if (!doc || typeof doc !== "object") return "";
690
+ const previous = resolveMedia;
691
+ resolveMedia = media ?? (() => void 0);
692
+ try {
693
+ return render(doc).replace(/\n{3,}/g, "\n\n").trim();
694
+ } finally {
695
+ resolveMedia = previous;
696
+ }
697
+ };
698
+ var inline = (text) => {
699
+ const pattern = /(`[^`]+`)|(\[[^\]]+\]\([^)]+\))/g;
700
+ const nodes = [];
701
+ let cursor = 0;
702
+ for (const match of text.matchAll(pattern)) {
703
+ const at = match.index;
704
+ if (at > cursor)
705
+ nodes.push({ type: "text", text: text.slice(cursor, at) });
706
+ const token = match[0];
707
+ if (token.startsWith("`")) {
708
+ nodes.push({
709
+ type: "text",
710
+ text: token.slice(1, -1),
711
+ marks: [{ type: "code" }]
712
+ });
713
+ } else {
714
+ const [, label = "", href = ""] = token.match(/\[([^\]]+)\]\(([^)]+)\)/) ?? [];
715
+ nodes.push({
716
+ type: "text",
717
+ text: label,
718
+ marks: [{ type: "link", attrs: { href } }]
719
+ });
720
+ }
721
+ cursor = at + token.length;
722
+ }
723
+ if (cursor < text.length) nodes.push({ type: "text", text: text.slice(cursor) });
724
+ return nodes.length > 0 ? nodes : [{ type: "text", text }];
725
+ };
726
+ var blockToAdf = (block) => {
727
+ const fence = block.match(/^```(\w*)\n([\s\S]*?)\n?```$/);
728
+ if (fence)
729
+ return {
730
+ type: "codeBlock",
731
+ ...fence[1] ? { attrs: { language: fence[1] } } : {},
732
+ content: [{ type: "text", text: fence[2] ?? "" }]
733
+ };
734
+ const heading = block.match(/^(#{1,6})\s+(.*)$/);
735
+ if (heading)
736
+ return {
737
+ type: "heading",
738
+ attrs: { level: heading[1]?.length ?? 1 },
739
+ content: inline(heading[2] ?? "")
740
+ };
741
+ const lines = block.split("\n");
742
+ if (lines.every((l) => /^\s*[-*]\s+/.test(l)))
743
+ return {
744
+ type: "bulletList",
745
+ content: lines.map((l) => ({
746
+ type: "listItem",
747
+ content: [
748
+ { type: "paragraph", content: inline(l.replace(/^\s*[-*]\s+/, "")) }
749
+ ]
750
+ }))
751
+ };
752
+ if (lines.every((l) => /^\s*\d+[.)]\s+/.test(l)))
753
+ return {
754
+ type: "orderedList",
755
+ content: lines.map((l) => ({
756
+ type: "listItem",
757
+ content: [
758
+ { type: "paragraph", content: inline(l.replace(/^\s*\d+[.)]\s+/, "")) }
759
+ ]
760
+ }))
761
+ };
762
+ return { type: "paragraph", content: inline(block) };
763
+ };
764
+ var markdownToAdf = (text) => ({
765
+ type: "doc",
766
+ version: 1,
767
+ content: text.replace(/\r\n/g, "\n").split(/\n{2,}/).map((b) => b.trim()).filter(Boolean).map(blockToAdf)
768
+ });
769
+
770
+ // src/commands/issue-write.ts
771
+ import { readFileSync as readFileSync2 } from "fs";
772
+ var readBody = (value) => value === "-" ? readFileSync2(0, "utf8") : value;
773
+ var resolveAccountId = async (who, projectKey) => {
774
+ if (who === "none" || who === "unassigned") return null;
775
+ if (who === "me") return (await context().client.getMe()).accountId;
776
+ if (/^[0-9a-f]{24}$|:/.test(who)) return who;
777
+ const ctx = context();
778
+ const candidates = projectKey ? await ctx.client.searchAssignableUsers(who, projectKey) : await ctx.client.searchUsers(who);
779
+ if (candidates.length === 0) throw exitError(1, `no user matching '${who}'`);
780
+ if (candidates.length > 1)
781
+ throw exitError(
782
+ 1,
783
+ `'${who}' matches ${candidates.length} people: ${candidates.map((u) => `${u.displayName} (${u.accountId})`).join(", ")}`
784
+ );
785
+ return candidates[0].accountId;
786
+ };
787
+ var registerIssueWriteCommands = (issue) => {
788
+ issue.command("create").description("create an issue").requiredOption("-p, --project <key>", "project key").requiredOption("-t, --type <type>", "issue type, e.g. Task").requiredOption("-s, --summary <text>", "summary").option("-b, --body <text>", "description; '-' reads stdin").option("-a, --assignee <who>", "assignee, or 'me'").option("-l, --label <label...>", "labels").option("--priority <name>", "priority name").option("--json", "emit JSON").action(
789
+ async (options) => {
790
+ const ctx = context();
791
+ const fields = {
792
+ project: { key: options.project },
793
+ issuetype: { name: options.type },
794
+ summary: options.summary
795
+ };
796
+ if (options.body)
797
+ fields["description"] = markdownToAdf(readBody(options.body));
798
+ if (options.label) fields["labels"] = options.label;
799
+ if (options.priority) fields["priority"] = { name: options.priority };
800
+ if (options.assignee)
801
+ fields["assignee"] = {
802
+ accountId: await resolveAccountId(
803
+ options.assignee,
804
+ options.project
805
+ )
806
+ };
807
+ const created = await ctx.client.createIssue(fields);
808
+ if (options.json) return printJson(created);
809
+ process.stdout.write(`${created.key}
810
+ `);
811
+ }
812
+ );
813
+ issue.command("edit <key>").description("change an issue's fields").option("-s, --summary <text>", "new summary").option("-b, --body <text>", "new description; '-' reads stdin").option("-l, --label <label...>", "replace labels").option("--priority <name>", "priority name").action(
814
+ async (key, options) => {
815
+ const fields = {};
816
+ if (options.summary) fields["summary"] = options.summary;
817
+ if (options.body)
818
+ fields["description"] = markdownToAdf(readBody(options.body));
819
+ if (options.label) fields["labels"] = options.label;
820
+ if (options.priority) fields["priority"] = { name: options.priority };
821
+ if (Object.keys(fields).length === 0)
822
+ throw exitError(2, "nothing to change \u2014 pass at least one option");
823
+ await context().client.updateIssue(key, fields);
824
+ process.stderr.write(`${key} updated
825
+ `);
826
+ }
827
+ );
828
+ issue.command("assign <key> <who>").description("assign an issue; 'me' or 'none' both work").action(async (key, who) => {
829
+ const accountId = await resolveAccountId(who);
830
+ await context().client.assignIssue(key, accountId);
831
+ process.stderr.write(`${key} assigned to ${accountId ? who : "nobody"}
832
+ `);
833
+ });
834
+ const comment = issue.command("comment").description("read and write comments");
835
+ comment.command("list <key>").alias("ls").description("comments on an issue").option("--json", "emit JSON").action(async (key, options) => {
836
+ const ctx = context();
837
+ const { comments } = await ctx.client.getComments(key);
838
+ if (options.json) return printJson(comments);
839
+ process.stdout.write(
840
+ `${comments.map(
841
+ (c) => [
842
+ `${ctx.out.bold(c.author?.displayName ?? "unknown")} ${ctx.out.dim(
843
+ `${c.created?.slice(0, 10) ?? ""} ${c.id}`
844
+ )}`,
845
+ adfToMarkdown(c.body)
846
+ ].join("\n")
847
+ ).join("\n\n")}
848
+ `
849
+ );
850
+ });
851
+ comment.command("add <key> <body>").description("comment on an issue; '-' reads stdin").action(async (key, body) => {
852
+ await context().client.addComment(key, markdownToAdf(readBody(body)));
853
+ process.stderr.write(`commented on ${key}
854
+ `);
855
+ });
856
+ const watch = issue.command("watch").description("watchers");
857
+ watch.command("list <key>").alias("ls").description("who is watching an issue").action(async (key) => {
858
+ const { watchers } = await context().client.getWatchers(key);
859
+ process.stdout.write(
860
+ `${table(watchers, [
861
+ { header: "ACCOUNT ID", value: (w) => w.accountId },
862
+ { header: "NAME", value: (w) => w.displayName }
863
+ ])}
864
+ `
865
+ );
866
+ });
867
+ watch.command("add <key> [who]").description("watch an issue, yourself by default").action(async (key, who = "me") => {
868
+ const accountId = await resolveAccountId(who);
869
+ if (!accountId) throw exitError(2, "cannot add 'none' as a watcher");
870
+ await context().client.addWatcher(key, accountId);
871
+ process.stderr.write(`watching ${key}
872
+ `);
873
+ });
874
+ watch.command("remove <key> [who]").description("stop watching an issue").action(async (key, who = "me") => {
875
+ const accountId = await resolveAccountId(who);
876
+ if (!accountId) throw exitError(2, "cannot remove 'none' as a watcher");
877
+ await context().client.removeWatcher(key, accountId);
878
+ process.stderr.write(`no longer watching ${key}
879
+ `);
880
+ });
881
+ const worklog = issue.command("worklog").description("time tracking");
882
+ worklog.command("list <key>").alias("ls").description("work logged on an issue").option("--json", "emit JSON").action(async (key, options) => {
883
+ const { worklogs } = await context().client.getWorklogs(key);
884
+ if (options.json) return printJson(worklogs);
885
+ process.stdout.write(
886
+ `${table(worklogs, [
887
+ { header: "WHEN", value: (w) => w.started?.slice(0, 10) ?? "\u2014" },
888
+ { header: "WHO", value: (w) => w.author?.displayName ?? "\u2014" },
889
+ { header: "SPENT", value: (w) => w.timeSpent ?? "\u2014" }
890
+ ])}
891
+ `
892
+ );
893
+ });
894
+ worklog.command("add <key> <timeSpent>").description("log work, e.g. '2h 30m'").option("-b, --body <text>", "what you did").action(
895
+ async (key, timeSpent, options) => {
896
+ await context().client.addWorklog(key, {
897
+ timeSpent,
898
+ ...options.body ? { comment: markdownToAdf(options.body) } : {}
899
+ });
900
+ process.stderr.write(`logged ${timeSpent} on ${key}
901
+ `);
902
+ }
903
+ );
904
+ issue.command("link <inward> <type> <outward>").description("link two issues, e.g. ABC-1 Blocks ABC-2").action(async (inward, type, outward) => {
905
+ await context().client.linkIssues(type, inward, outward);
906
+ process.stderr.write(`${inward} ${type} ${outward}
907
+ `);
908
+ });
909
+ issue.command("history <key>").description("what changed on an issue and when").option("--json", "emit JSON").action(async (key, options) => {
910
+ const ctx = context();
911
+ const { values } = await ctx.client.getChangelog(key);
912
+ if (options.json) return printJson(values);
913
+ process.stdout.write(
914
+ `${values.flatMap(
915
+ (entry) => (entry.items ?? []).map(
916
+ (item) => `${ctx.out.dim(entry.created?.slice(0, 10) ?? "\u2014")} ${entry.author?.displayName ?? "unknown"} ${item.field}: ${item.fromString ?? "\u2014"} \u2192 ${item.toString ?? "\u2014"}`
917
+ )
918
+ ).join("\n")}
919
+ `
920
+ );
921
+ });
922
+ };
923
+
924
+ // src/commands/issue.ts
925
+ var jqlEscape = (value) => `"${value.replace(/"/g, '\\"')}"`;
926
+ var buildJql = (options, defaultProject) => {
927
+ if (options.jql) return options.jql;
928
+ const clauses = [];
929
+ if (options.mine) clauses.push("assignee = currentUser()");
930
+ else if (options.assignee)
931
+ clauses.push(
932
+ options.assignee === "none" ? "assignee IS EMPTY" : `assignee = ${jqlEscape(options.assignee)}`
933
+ );
934
+ const project = options.project ?? defaultProject;
935
+ if (project) clauses.push(`project = ${jqlEscape(project)}`);
936
+ if (options.status) clauses.push(`status = ${jqlEscape(options.status)}`);
937
+ if (options.label) clauses.push(`labels = ${jqlEscape(options.label)}`);
938
+ if (options.sprint)
939
+ clauses.push(
940
+ options.sprint === "current" ? "sprint IN openSprints()" : `sprint = ${jqlEscape(options.sprint)}`
941
+ );
942
+ if (clauses.length === 0) clauses.push("assignee = currentUser()");
943
+ return `${clauses.join(" AND ")} ORDER BY updated DESC`;
944
+ };
945
+ var issueColumns = (ctx) => [
946
+ { header: "KEY", value: (i) => i.key },
947
+ { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
948
+ { header: "SUMMARY", value: (i) => truncate2(i.fields.summary ?? "", 72) },
949
+ {
950
+ header: "ASSIGNEE",
951
+ value: (i) => ctx.out.dim(i.fields.assignee?.displayName ?? "unassigned")
952
+ }
953
+ ];
954
+ var registerIssueCommands = (program2) => {
955
+ const issue = program2.command("issue").description("work with issues");
956
+ registerIssueWriteCommands(issue);
957
+ issue.command("list").alias("ls").description("list issues matching the given filters").option("-a, --assignee <who>", "assignee account id, email, or 'none'").option("-m, --mine", "issues assigned to you").option("-s, --status <status>", "status name, e.g. 'In Progress'").option("-p, --project <key>", "project key").option("--sprint <name>", "sprint name, or 'current' for open sprints").option("-l, --label <label>", "label").option("-q, --jql <jql>", "raw JQL, replacing all other filters").option("-n, --limit <n>", "maximum issues to return", "50").option("--json", "emit JSON").action(async (options) => {
958
+ const ctx = context();
959
+ const jql = buildJql(options, ctx.config.defaultProject);
960
+ const issues = await ctx.client.searchIssues(jql, {
961
+ limit: Number(options.limit)
962
+ });
963
+ if (options.json) return printJson(issues);
964
+ if (issues.length === 0) {
965
+ const me = await ctx.client.getMe().catch(() => null);
966
+ if (!me?.accountId)
967
+ throw exitError(
968
+ 4,
969
+ "not authenticated \u2014 check ATLASSIAN_USER_EMAIL and ATLASSIAN_API_TOKEN"
970
+ );
971
+ process.stderr.write(`no issues match: ${jql}
972
+ `);
973
+ return;
974
+ }
975
+ process.stdout.write(`${table(issues, issueColumns(ctx))}
976
+ `);
977
+ });
978
+ issue.command("view <key>").description("show one issue").option("--json", "emit JSON").option("--comments", "include comments").action(
979
+ async (key, options) => {
980
+ const ctx = context();
981
+ const found = await ctx.client.getIssue(key);
982
+ if (options.json) return printJson(found);
983
+ const { bold, dim } = ctx.out;
984
+ const f = found.fields;
985
+ const lines = [
986
+ `${bold(found.key)} ${f.summary ?? ""}`,
987
+ "",
988
+ `${dim("status")} ${f.status?.name ?? "\u2014"}`,
989
+ `${dim("type")} ${f.issuetype?.name ?? "\u2014"}`,
990
+ `${dim("assignee")} ${f.assignee?.displayName ?? "unassigned"}`,
991
+ `${dim("reporter")} ${f.reporter?.displayName ?? "\u2014"}`,
992
+ ...f.labels?.length ? [`${dim("labels")} ${f.labels.join(", ")}`] : [],
993
+ ...ctx.client.customFields.filter((cf) => f[cf.id] != null).map((cf) => `${dim(cf.label.padEnd(9))} ${formatField(f[cf.id])}`),
994
+ `${dim("url")} ${issueUrl(ctx, found.key)}`
995
+ ];
996
+ const attachments = locateAttachments(found);
997
+ const filenameOf = (id) => attachments.find((a) => a.id === id)?.filename;
998
+ if (attachments.length > 0) {
999
+ lines.push(
1000
+ "",
1001
+ dim("\u2500\u2500\u2500 attachments \u2500\u2500\u2500"),
1002
+ "",
1003
+ ...attachments.map(
1004
+ (a) => `${a.filename} ${dim(`${a.mimeType} ${a.id}`)}`
1005
+ ),
1006
+ "",
1007
+ dim(`read one with: jira attachment read ${found.key} <filename>`)
1008
+ );
1009
+ }
1010
+ const description = adfToMarkdown(f.description, filenameOf);
1011
+ if (description)
1012
+ lines.push("", dim("\u2500\u2500\u2500 description \u2500\u2500\u2500"), "", description);
1013
+ if (options.comments && f.comment?.comments?.length) {
1014
+ lines.push("", dim("\u2500\u2500\u2500 comments \u2500\u2500\u2500"));
1015
+ for (const c of f.comment.comments) {
1016
+ lines.push(
1017
+ "",
1018
+ `${bold(c.author?.displayName ?? "unknown")} ${dim(c.created?.slice(0, 10) ?? "")}`,
1019
+ adfToMarkdown(c.body, filenameOf)
1020
+ );
1021
+ }
1022
+ }
1023
+ process.stdout.write(`${lines.join("\n")}
1024
+ `);
1025
+ }
1026
+ );
1027
+ issue.command("transition <key> [status]").alias("move").description("move an issue, or list available transitions").option("--json", "emit JSON").action(
1028
+ async (key, status, options) => {
1029
+ const ctx = context();
1030
+ const { transitions } = await ctx.client.getTransitions(key);
1031
+ if (!status) {
1032
+ if (options.json) return printJson(transitions);
1033
+ process.stdout.write(
1034
+ `${table(transitions, [
1035
+ { header: "ID", value: (t) => t.id },
1036
+ { header: "NAME", value: (t) => t.name },
1037
+ { header: "TO", value: (t) => t.to?.name ?? "\u2014" }
1038
+ ])}
1039
+ `
1040
+ );
1041
+ return;
1042
+ }
1043
+ const wanted = status.toLowerCase();
1044
+ const match = transitions.find(
1045
+ (t) => t.name.toLowerCase() === wanted || t.id === status
1046
+ );
1047
+ if (!match) {
1048
+ throw exitError(
1049
+ 1,
1050
+ `no transition '${status}' on ${key}. Available: ${transitions.map((t) => t.name).join(", ")}`
1051
+ );
1052
+ }
1053
+ await ctx.client.transitionIssue(key, match.id);
1054
+ if (options.json) return printJson({ key, transition: match });
1055
+ process.stdout.write(`${key} \u2192 ${match.to?.name ?? match.name}
1056
+ `);
1057
+ }
1058
+ );
1059
+ issue.command("open <key>").description("open an issue in the browser").option("--print", "print the url instead of opening it").action(async (key, options) => {
1060
+ const ctx = context();
1061
+ const url = issueUrl(ctx, key);
1062
+ if (options.print) {
1063
+ process.stdout.write(`${url}
1064
+ `);
1065
+ return;
1066
+ }
1067
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1068
+ execFile(opener, [url]);
1069
+ });
1070
+ };
1071
+ var issueUrl = (ctx, key) => `${ctx.config.baseUrl.replace(/\/$/, "")}/browse/${key}`;
1072
+ var formatField = (value) => {
1073
+ if (value == null) return "\u2014";
1074
+ if (typeof value === "object") {
1075
+ const o = value;
1076
+ return String(
1077
+ o["value"] ?? o["name"] ?? o["displayName"] ?? JSON.stringify(value)
1078
+ );
1079
+ }
1080
+ return String(value);
1081
+ };
1082
+
1083
+ // src/commands/meta.ts
1084
+ var registerMetaCommands = (program2) => {
1085
+ const meta = program2.command("meta").description("what this instance supports: types, priorities, statuses");
1086
+ const named = (name, description, fetch) => {
1087
+ meta.command(name).description(description).option("--json", "emit JSON").action(async (options) => {
1088
+ const values = await fetch();
1089
+ if (options.json) return printJson(values);
1090
+ process.stdout.write(
1091
+ `${table(values, [
1092
+ { header: "ID", value: (v) => v.id },
1093
+ { header: "NAME", value: (v) => v.name }
1094
+ ])}
1095
+ `
1096
+ );
1097
+ });
1098
+ };
1099
+ named(
1100
+ "issuetypes",
1101
+ "issue types on this instance",
1102
+ async () => context().client.getIssueTypes()
1103
+ );
1104
+ named(
1105
+ "priorities",
1106
+ "priorities on this instance",
1107
+ async () => context().client.getPriorities()
1108
+ );
1109
+ named(
1110
+ "statuses",
1111
+ "statuses on this instance",
1112
+ async () => context().client.getStatuses()
1113
+ );
1114
+ named(
1115
+ "resolutions",
1116
+ "resolutions on this instance",
1117
+ async () => context().client.getResolutions()
1118
+ );
1119
+ named(
1120
+ "linktypes",
1121
+ "issue link types",
1122
+ async () => (await context().client.getIssueLinkTypes()).issueLinkTypes
1123
+ );
1124
+ meta.command("labels").description("every label in use").option("--json", "emit JSON").action(async (options) => {
1125
+ const { values } = await context().client.getLabels();
1126
+ if (options.json) return printJson(values);
1127
+ process.stdout.write(`${values.join("\n")}
1128
+ `);
1129
+ });
1130
+ meta.command("filters").description("saved filters you can see").option("--json", "emit JSON").action(async (options) => {
1131
+ const { values } = await context().client.getFilters();
1132
+ if (options.json) return printJson(values);
1133
+ process.stdout.write(
1134
+ `${table(values, [
1135
+ { header: "ID", value: (f) => f.id },
1136
+ { header: "NAME", value: (f) => f.name },
1137
+ { header: "JQL", value: (f) => f.jql ?? "\u2014" }
1138
+ ])}
1139
+ `
1140
+ );
1141
+ });
1142
+ meta.command("permissions [projectKey]").description("what you are allowed to do").action(async (projectKey) => {
1143
+ printJson(await context().client.getMyPermissions(projectKey));
1144
+ });
1145
+ meta.command("server").description("instance version and deployment details").action(async () => {
1146
+ printJson(await context().client.getServerInfo());
1147
+ });
1148
+ };
1149
+ var registerCountCommand = (program2) => {
1150
+ program2.command("count <jql>").description("approximate number of issues matching a query").action(async (jql) => {
1151
+ const { count } = await context().client.approximateCount(jql);
1152
+ process.stdout.write(`${count}
1153
+ `);
1154
+ });
1155
+ };
1156
+
1157
+ // src/commands/people.ts
1158
+ var registerUserCommands = (program2) => {
1159
+ const user = program2.command("user").description("find people");
1160
+ user.command("search <query>").description("search users by name or email").option("-p, --project <key>", "only users assignable on this project").option("-n, --limit <n>", "maximum users to return", "20").action(
1161
+ async (query, options) => {
1162
+ const ctx = context();
1163
+ const users = options.project ? await ctx.client.searchAssignableUsers(
1164
+ query,
1165
+ options.project,
1166
+ Number(options.limit)
1167
+ ) : await ctx.client.searchUsers(query, Number(options.limit));
1168
+ process.stdout.write(
1169
+ `${table(users, [
1170
+ { header: "ACCOUNT ID", value: (u) => u.accountId },
1171
+ { header: "NAME", value: (u) => u.displayName },
1172
+ { header: "EMAIL", value: (u) => u.emailAddress ?? "\u2014" }
1173
+ ])}
1174
+ `
1175
+ );
1176
+ }
1177
+ );
1178
+ program2.command("whoami").description("show the account these credentials belong to").option("--json", "emit JSON").action(async (options) => {
1179
+ const ctx = context();
1180
+ const me = await ctx.client.getMe();
1181
+ if (options.json) return printJson(me);
1182
+ process.stdout.write(
1183
+ `${me.displayName} <${me.emailAddress ?? "\u2014"}>
1184
+ ${ctx.out.dim(me.accountId)}
1185
+ `
1186
+ );
1187
+ });
1188
+ };
1189
+
1190
+ // src/commands/project.ts
1191
+ var registerProjectCommands = (program2) => {
1192
+ const project = program2.command("project").alias("proj").description("projects, their versions and components");
1193
+ project.command("list").alias("ls").description("list projects you can see").option("--json", "emit JSON").action(async (options) => {
1194
+ const ctx = context();
1195
+ const projects = await ctx.client.getProjects();
1196
+ if (options.json) return printJson(projects);
1197
+ process.stdout.write(
1198
+ `${table(projects, [
1199
+ { header: "KEY", value: (p) => p.key },
1200
+ { header: "NAME", value: (p) => p.name }
1201
+ ])}
1202
+ `
1203
+ );
1204
+ });
1205
+ project.command("view <key>").description("show one project").option("--json", "emit JSON").action(async (key, options) => {
1206
+ const ctx = context();
1207
+ const found = await ctx.client.getProject(key);
1208
+ if (options.json) return printJson(found);
1209
+ const { dim } = ctx.out;
1210
+ process.stdout.write(
1211
+ `${[`${found.key} ${found.name}`, `${dim("id")} ${found.id}`].join(
1212
+ "\n"
1213
+ )}
1214
+ `
1215
+ );
1216
+ });
1217
+ project.command("versions <key>").description("list a project's versions").option("--json", "emit JSON").action(async (key, options) => {
1218
+ const ctx = context();
1219
+ const versions = await ctx.client.getProjectVersions(key);
1220
+ if (options.json) return printJson(versions);
1221
+ process.stdout.write(
1222
+ `${table(versions, [
1223
+ { header: "ID", value: (v) => v.id },
1224
+ { header: "NAME", value: (v) => v.name },
1225
+ {
1226
+ header: "STATE",
1227
+ value: (v) => v.archived ? "archived" : v.released ? "released" : "open"
1228
+ },
1229
+ { header: "RELEASE", value: (v) => v.releaseDate ?? "\u2014" }
1230
+ ])}
1231
+ `
1232
+ );
1233
+ });
1234
+ project.command("components <key>").description("list a project's components").option("--json", "emit JSON").action(async (key, options) => {
1235
+ const ctx = context();
1236
+ const components = await ctx.client.getProjectComponents(key);
1237
+ if (options.json) return printJson(components);
1238
+ process.stdout.write(
1239
+ `${table(components, [
1240
+ { header: "ID", value: (c) => c.id },
1241
+ { header: "NAME", value: (c) => c.name },
1242
+ { header: "LEAD", value: (c) => c.lead?.displayName ?? "\u2014" }
1243
+ ])}
1244
+ `
1245
+ );
1246
+ });
1247
+ project.command("statuses <key>").description("list the statuses available per issue type").option("--json", "emit JSON").action(async (key, options) => {
1248
+ const ctx = context();
1249
+ const statuses = await ctx.client.getProjectStatuses(key);
1250
+ if (options.json) return printJson(statuses);
1251
+ process.stdout.write(
1252
+ `${statuses.map(
1253
+ (s) => `${s.name}
1254
+ ${s.statuses.map((x) => x.name).join(", ")}`
1255
+ ).join("\n")}
1256
+ `
1257
+ );
1258
+ });
1259
+ };
1260
+
1261
+ // src/commands/misc.ts
1262
+ import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
1263
+ import { dirname } from "path";
1264
+ var registerSearchCommand = (program2) => {
1265
+ program2.command("search <jql>").description("run a raw JQL query").option("-n, --limit <n>", "maximum issues to return", "50").option("--json", "emit JSON").action(async (jql, options) => {
1266
+ const ctx = context();
1267
+ const issues = await ctx.client.searchIssues(jql, {
1268
+ limit: Number(options.limit)
1269
+ });
1270
+ if (options.json) return printJson(issues);
1271
+ if (issues.length === 0) {
1272
+ process.stderr.write("no issues match\n");
1273
+ return;
1274
+ }
1275
+ process.stdout.write(
1276
+ `${table(issues, [
1277
+ { header: "KEY", value: (i) => i.key },
1278
+ { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
1279
+ { header: "SUMMARY", value: (i) => i.fields.summary ?? "" }
1280
+ ])}
1281
+ `
1282
+ );
1283
+ });
1284
+ };
1285
+ var registerFieldsCommand = (program2) => {
1286
+ program2.command("fields [filter]").description("list this instance's fields, to fill in your config").option("--all", "include built-in fields, not just custom ones").option("--json", "emit JSON").action(
1287
+ async (filter, options) => {
1288
+ const ctx = context();
1289
+ const all = await ctx.client.getFields();
1290
+ const needle = filter?.toLowerCase();
1291
+ const fields = all.filter((f) => options.all || f.custom).filter(
1292
+ (f) => !needle || f.name.toLowerCase().includes(needle) || f.id.toLowerCase().includes(needle)
1293
+ ).sort((a, b) => a.name.localeCompare(b.name));
1294
+ if (options.json) return printJson(fields);
1295
+ if (fields.length === 0) {
1296
+ process.stderr.write(
1297
+ `no fields match '${filter ?? ""}'. Try: jira fields --all
1298
+ `
1299
+ );
1300
+ return;
1301
+ }
1302
+ process.stdout.write(
1303
+ `${table(fields, [
1304
+ { header: "ID", value: (f) => f.id },
1305
+ { header: "NAME", value: (f) => f.name },
1306
+ { header: "TYPE", value: (f) => f.schema?.type ?? "\u2014" }
1307
+ ])}
1308
+ `
1309
+ );
1310
+ process.stderr.write(
1311
+ `
1312
+ ${ctx.out.dim(
1313
+ `${fields.length} fields \u2014 add the ones you use to ${configPath()}:
1314
+ { "customFields": [{ "id": "customfield_10002", "label": "points" }] }`
1315
+ )}
1316
+ `
1317
+ );
1318
+ }
1319
+ );
1320
+ };
1321
+ var METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
1322
+ var registerApiCommand = (program2) => {
1323
+ program2.command("api <path>").description("call any Jira REST endpoint directly").option("-X, --method <method>", "HTTP method", "GET").option("-d, --data <json>", "request body as JSON").action(
1324
+ async (path, options) => {
1325
+ const ctx = context();
1326
+ const method = options.method.toUpperCase();
1327
+ if (!METHODS.has(method))
1328
+ throw exitError(2, `unsupported method '${options.method}'`);
1329
+ const result = await ctx.client.request(path, {
1330
+ method,
1331
+ ...options.data ? { body: options.data } : {}
1332
+ });
1333
+ printJson(result ?? null);
1334
+ }
1335
+ );
1336
+ };
1337
+ var registerInitCommand = (program2) => {
1338
+ program2.command("init").description("write a starter config file").option("--base-url <url>", "your Jira instance, e.g. myorg.atlassian.net").option("--email <email>", "your Atlassian account email").option("--force", "overwrite an existing config").action(
1339
+ async (options) => {
1340
+ const path = configPath();
1341
+ const existing = readFileConfig(path);
1342
+ if (Object.keys(existing).length > 0 && !options.force)
1343
+ throw exitError(1, `${path} already exists \u2014 pass --force to replace it`);
1344
+ const config = {
1345
+ baseUrl: options.baseUrl ?? process.env["ATLASSIAN_BASE_URL"] ?? "",
1346
+ email: options.email ?? process.env["ATLASSIAN_USER_EMAIL"] ?? "",
1347
+ customFields: []
1348
+ };
1349
+ mkdirSync(dirname(path), { recursive: true });
1350
+ writeFileSync2(path, `${JSON.stringify(config, null, 2)}
1351
+ `);
1352
+ process.stderr.write(
1353
+ `wrote ${path}
1354
+
1355
+ Set your token, which never goes in this file:
1356
+ export ATLASSIAN_API_TOKEN=...
1357
+
1358
+ Then add the custom fields you care about:
1359
+ jira fields points
1360
+ `
1361
+ );
1362
+ }
1363
+ );
1364
+ };
1365
+
1366
+ // src/index.ts
1367
+ var program = new Command();
1368
+ program.name("jira").description("Jira on the command line").version("0.2.0").addHelpText(
1369
+ "after",
1370
+ `
1371
+ Setup:
1372
+ export ATLASSIAN_API_TOKEN=... the only secret, env only
1373
+ id.atlassian.com/manage-profile/security/api-tokens
1374
+ jira init --base-url myorg.atlassian.net --email you@example.com
1375
+
1376
+ Everything else lives in ${configPath()}, and any of it can be
1377
+ overridden with ATLASSIAN_BASE_URL / ATLASSIAN_USER_EMAIL.
1378
+
1379
+ Examples:
1380
+ jira issue list --mine --status 'In Progress'
1381
+ jira issue view ABC-123 --comments
1382
+ jira attachment list ABC-123
1383
+ jira attachment read ABC-123 error.log | grep -i timeout
1384
+ jira search 'project = ABC AND created >= -7d' --json | jq '.[].key'
1385
+ `
1386
+ );
1387
+ registerIssueCommands(program);
1388
+ registerAttachmentCommands(program);
1389
+ registerSearchCommand(program);
1390
+ registerFieldsCommand(program);
1391
+ registerInitCommand(program);
1392
+ registerProjectCommands(program);
1393
+ registerBoardCommands(program);
1394
+ registerSprintCommands(program);
1395
+ registerEpicCommands(program);
1396
+ registerUserCommands(program);
1397
+ registerMetaCommands(program);
1398
+ registerCountCommand(program);
1399
+ registerApiCommand(program);
1400
+ var exitCodeFor = (error) => {
1401
+ if (isExitError(error)) return error.code;
1402
+ if (isJiraApiError(error))
1403
+ return error.status === 401 || error.status === 403 ? 4 : 1;
1404
+ return 1;
1405
+ };
1406
+ program.parseAsync(process.argv).catch((error) => {
1407
+ process.stderr.write(
1408
+ `jira: ${error instanceof Error ? error.message : String(error)}
1409
+ `
1410
+ );
1411
+ process.exit(exitCodeFor(error));
1412
+ });