@kud/jira-cli 0.2.0 → 0.3.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/dist/index.js CHANGED
@@ -1,388 +1,29 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ configPath,
4
+ context,
5
+ exitError,
6
+ isExitError,
7
+ printJson,
8
+ readFileConfig,
9
+ table,
10
+ truncate
11
+ } from "./chunk-5MFNIQDW.js";
2
12
 
3
13
  // src/index.ts
14
+ import { realpathSync } from "fs";
15
+ import { fileURLToPath } from "url";
4
16
  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
- };
17
+ import { isJiraApiError } from "@kud/jira";
220
18
 
221
19
  // src/commands/attachment.ts
222
20
  import { writeFileSync } from "fs";
223
21
  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
22
+ import {
23
+ downloadAttachment,
24
+ isTextual,
25
+ locateAttachments
26
+ } from "@kud/jira";
386
27
  var humanSize = (bytes) => {
387
28
  const units = ["B", "KB", "MB", "GB"];
388
29
  const exponent = Math.min(
@@ -476,7 +117,7 @@ var registerAttachmentCommands = (program2) => {
476
117
  var issueRows = [
477
118
  { header: "KEY", value: (i) => i.key },
478
119
  { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
479
- { header: "SUMMARY", value: (i) => truncate2(i.fields.summary ?? "", 72) },
120
+ { header: "SUMMARY", value: (i) => truncate(i.fields.summary ?? "", 72) },
480
121
  {
481
122
  header: "ASSIGNEE",
482
123
  value: (i) => i.fields.assignee?.displayName ?? "unassigned"
@@ -588,188 +229,15 @@ var registerEpicCommands = (program2) => {
588
229
 
589
230
  // src/commands/issue.ts
590
231
  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
- });
232
+ import {
233
+ adfToMarkdown as adfToMarkdown2,
234
+ locateAttachments as locateAttachments2
235
+ } from "@kud/jira";
769
236
 
770
237
  // src/commands/issue-write.ts
771
- import { readFileSync as readFileSync2 } from "fs";
772
- var readBody = (value) => value === "-" ? readFileSync2(0, "utf8") : value;
238
+ import { readFileSync } from "fs";
239
+ import { adfToMarkdown, markdownToAdf } from "@kud/jira";
240
+ var readBody = (value) => value === "-" ? readFileSync(0, "utf8") : value;
773
241
  var resolveAccountId = async (who, projectKey) => {
774
242
  if (who === "none" || who === "unassigned") return null;
775
243
  if (who === "me") return (await context().client.getMe()).accountId;
@@ -912,8 +380,8 @@ var registerIssueWriteCommands = (issue) => {
912
380
  if (options.json) return printJson(values);
913
381
  process.stdout.write(
914
382
  `${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"}`
383
+ (entry2) => (entry2.items ?? []).map(
384
+ (item) => `${ctx.out.dim(entry2.created?.slice(0, 10) ?? "\u2014")} ${entry2.author?.displayName ?? "unknown"} ${item.field}: ${item.fromString ?? "\u2014"} \u2192 ${item.toString ?? "\u2014"}`
917
385
  )
918
386
  ).join("\n")}
919
387
  `
@@ -945,7 +413,7 @@ var buildJql = (options, defaultProject) => {
945
413
  var issueColumns = (ctx) => [
946
414
  { header: "KEY", value: (i) => i.key },
947
415
  { header: "STATUS", value: (i) => i.fields.status?.name ?? "\u2014" },
948
- { header: "SUMMARY", value: (i) => truncate2(i.fields.summary ?? "", 72) },
416
+ { header: "SUMMARY", value: (i) => truncate(i.fields.summary ?? "", 72) },
949
417
  {
950
418
  header: "ASSIGNEE",
951
419
  value: (i) => ctx.out.dim(i.fields.assignee?.displayName ?? "unassigned")
@@ -993,7 +461,7 @@ var registerIssueCommands = (program2) => {
993
461
  ...ctx.client.customFields.filter((cf) => f[cf.id] != null).map((cf) => `${dim(cf.label.padEnd(9))} ${formatField(f[cf.id])}`),
994
462
  `${dim("url")} ${issueUrl(ctx, found.key)}`
995
463
  ];
996
- const attachments = locateAttachments(found);
464
+ const attachments = locateAttachments2(found);
997
465
  const filenameOf = (id) => attachments.find((a) => a.id === id)?.filename;
998
466
  if (attachments.length > 0) {
999
467
  lines.push(
@@ -1007,7 +475,7 @@ var registerIssueCommands = (program2) => {
1007
475
  dim(`read one with: jira attachment read ${found.key} <filename>`)
1008
476
  );
1009
477
  }
1010
- const description = adfToMarkdown(f.description, filenameOf);
478
+ const description = adfToMarkdown2(f.description, filenameOf);
1011
479
  if (description)
1012
480
  lines.push("", dim("\u2500\u2500\u2500 description \u2500\u2500\u2500"), "", description);
1013
481
  if (options.comments && f.comment?.comments?.length) {
@@ -1016,7 +484,7 @@ var registerIssueCommands = (program2) => {
1016
484
  lines.push(
1017
485
  "",
1018
486
  `${bold(c.author?.displayName ?? "unknown")} ${dim(c.created?.slice(0, 10) ?? "")}`,
1019
- adfToMarkdown(c.body, filenameOf)
487
+ adfToMarkdown2(c.body, filenameOf)
1020
488
  );
1021
489
  }
1022
490
  }
@@ -1024,7 +492,7 @@ var registerIssueCommands = (program2) => {
1024
492
  `);
1025
493
  }
1026
494
  );
1027
- issue.command("transition <key> [status]").alias("move").description("move an issue, or list available transitions").option("--json", "emit JSON").action(
495
+ issue.command("transition <key> [status]").alias("move").description("move an issue, or list available transitions").option("--resolution <name>", "resolution to set as part of the move").option("--json", "emit JSON").action(
1028
496
  async (key, status, options) => {
1029
497
  const ctx = context();
1030
498
  const { transitions } = await ctx.client.getTransitions(key);
@@ -1050,7 +518,11 @@ var registerIssueCommands = (program2) => {
1050
518
  `no transition '${status}' on ${key}. Available: ${transitions.map((t) => t.name).join(", ")}`
1051
519
  );
1052
520
  }
1053
- await ctx.client.transitionIssue(key, match.id);
521
+ await ctx.client.transitionIssue(
522
+ key,
523
+ match.id,
524
+ options.resolution ? { resolution: { name: options.resolution } } : void 0
525
+ );
1054
526
  if (options.json) return printJson({ key, transition: match });
1055
527
  process.stdout.write(`${key} \u2192 ${match.to?.name ?? match.name}
1056
528
  `);
@@ -1403,10 +875,54 @@ var exitCodeFor = (error) => {
1403
875
  return error.status === 401 || error.status === 403 ? 4 : 1;
1404
876
  return 1;
1405
877
  };
1406
- program.parseAsync(process.argv).catch((error) => {
878
+ var fail = (error) => {
1407
879
  process.stderr.write(
1408
880
  `jira: ${error instanceof Error ? error.message : String(error)}
1409
881
  `
1410
882
  );
1411
883
  process.exit(exitCodeFor(error));
1412
- });
884
+ };
885
+ var interactiveArgs = (argv) => {
886
+ const rest = argv.slice(2);
887
+ const screenAt = rest.indexOf("--screen");
888
+ const screen = screenAt === -1 ? void 0 : rest[screenAt + 1];
889
+ const consumed = new Set(
890
+ screenAt === -1 ? ["--mock"] : ["--mock", "--screen", screen ?? ""]
891
+ );
892
+ return {
893
+ screen,
894
+ mock: rest.includes("--mock"),
895
+ isBare: rest.every((a) => consumed.has(a))
896
+ };
897
+ };
898
+ var main = async () => {
899
+ const { screen, mock, isBare } = interactiveArgs(process.argv);
900
+ if (screen === "list" && isBare) {
901
+ const { SCREENS } = await import("./tui-4JIAFCJF.js");
902
+ process.stdout.write(`${SCREENS.join("\n")}
903
+ `);
904
+ return;
905
+ }
906
+ if (isBare) {
907
+ if (!process.stdout.isTTY) {
908
+ program.outputHelp();
909
+ return;
910
+ }
911
+ const { runTui } = await import("./tui-4JIAFCJF.js");
912
+ const [, key] = (screen ?? "").split(":");
913
+ await runTui({
914
+ screen: screen?.startsWith("detail") ? "detail" : "issues",
915
+ mock,
916
+ ...key ? { issueKey: key } : {}
917
+ });
918
+ return;
919
+ }
920
+ await program.parseAsync(process.argv);
921
+ };
922
+ var entry = process.argv[1];
923
+ if (entry && fileURLToPath(import.meta.url) === realpathSync(entry)) {
924
+ main().catch(fail);
925
+ }
926
+ export {
927
+ interactiveArgs
928
+ };