@kud/jira-cli 0.11.0 → 0.12.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 (3) hide show
  1. package/README.md +15 -0
  2. package/dist/index.js +211 -4
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -205,6 +205,21 @@ jira fields points
205
205
 
206
206
  Named fields are requested on every search and shown in `issue view`.
207
207
 
208
+ ## Automation rules
209
+
210
+ ```sh
211
+ jira automation list --project SHOP # --state ENABLED|DISABLED, --limit, --json
212
+ jira automation get 0192e5ac-0e25-71de-ba7b-d972e6a2049a > rule.json
213
+ jira automation update 0192e5ac-0e25-71de-ba7b-d972e6a2049a --file rule.json
214
+ jira automation create --file rule.json # prints the new rule's UUID; - reads stdin
215
+ jira automation disable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
216
+ jira automation enable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
217
+ ```
218
+
219
+ These use Atlassian's [Automation REST API](https://developer.atlassian.com/cloud/automation/rest/api-group-rule-management/) with the same classic API token as everything else; nothing new to configure. The account behind it needs the **Jira administrator** global permission (Administer Jira): Jira answers a project admin with a bare 403, even for rules scoped to that project, and the CLI says so and exits 4. Project admins can still manage their project's rules in the Jira web UI.
220
+
221
+ `create` and `update` take the shape `get` prints, `{ "rule": { … } }`, or a bare rule. The cloud ID is read from the site's `/_edge/tenant_info`; set `ATLASSIAN_CLOUD_ID` to skip that call. Requests go through the site's gateway by default; `--host api` (or `ATLASSIAN_AUTOMATION_HOST=api`) sends them to `api.atlassian.com` instead.
222
+
208
223
  ## Escape hatch
209
224
 
210
225
  Anything not covered:
package/dist/index.js CHANGED
@@ -14,7 +14,212 @@ import { realpathSync } from "fs";
14
14
  import { createRequire } from "module";
15
15
  import { fileURLToPath } from "url";
16
16
  import { Command } from "commander";
17
- import { configPath as configPath2, isJiraApiError } from "@kud/jira";
17
+ import { configPath as configPath2, isJiraApiError as isJiraApiError2 } from "@kud/jira";
18
+
19
+ // src/commands/automation.ts
20
+ import { readFileSync } from "fs";
21
+ import { isJiraApiError } from "@kud/jira";
22
+ var HOSTS = /* @__PURE__ */ new Set(["site", "api"]);
23
+ var automationHost = (flag, env = process.env) => {
24
+ const raw = (flag ?? env["ATLASSIAN_AUTOMATION_HOST"] ?? "site").toLowerCase();
25
+ if (!HOSTS.has(raw))
26
+ throw exitError(2, `unknown automation host '${raw}' \u2014 use 'site' or 'api'`);
27
+ return raw;
28
+ };
29
+ var automationBase = (host, baseUrl, cloudId) => host === "api" ? `https://api.atlassian.com/automation/public/jira/${cloudId}/rest/v1` : `${baseUrl}/gateway/api/automation/public/jira/${cloudId}/rest/v1`;
30
+ var resolveCloudId = async (client, env = process.env) => {
31
+ const fromEnv = env["ATLASSIAN_CLOUD_ID"];
32
+ if (fromEnv) return fromEnv;
33
+ const tenant = await client.request(
34
+ "/_edge/tenant_info"
35
+ );
36
+ if (!tenant?.cloudId)
37
+ throw exitError(
38
+ 1,
39
+ "could not read this site's cloud ID from /_edge/tenant_info \u2014 set ATLASSIAN_CLOUD_ID"
40
+ );
41
+ return tenant.cloudId;
42
+ };
43
+ var explainAuthFailure = (error) => {
44
+ if (!isJiraApiError(error)) return error;
45
+ if (error.status === 401)
46
+ return exitError(
47
+ 4,
48
+ "Jira rejected the credentials for the Automation API.\nATLASSIAN_API_TOKEN must be a classic API token (basic auth with ATLASSIAN_USER_EMAIL) \u2014\nthe rule management API is closed to OAuth 2.0 and Forge apps.\n id.atlassian.com/manage-profile/security/api-tokens"
49
+ );
50
+ if (error.status === 403)
51
+ return exitError(
52
+ 4,
53
+ `Automation API refused ${error.method} (403).
54
+ Managing automation rules needs the Jira administrator global permission
55
+ (Administer Jira) on the account behind ATLASSIAN_API_TOKEN; project admin is not enough,
56
+ even for rules scoped to that project. Ask a Jira admin to grant it, or to run the command.
57
+ A project admin can still create and edit that project's rules in the Jira web UI.`
58
+ );
59
+ return error;
60
+ };
61
+ var automation = async (hostFlag) => {
62
+ const host = automationHost(hostFlag);
63
+ const ctx = context();
64
+ const cloudId = await resolveCloudId(ctx.client);
65
+ const base = automationBase(host, ctx.config.baseUrl, cloudId);
66
+ const call = async (path, init = {}) => {
67
+ try {
68
+ return await ctx.client.request(`${base}${path}`, init);
69
+ } catch (error) {
70
+ throw explainAuthFailure(error);
71
+ }
72
+ };
73
+ return { ctx, cloudId, call };
74
+ };
75
+ var nextCursor = (next) => {
76
+ if (!next) return void 0;
77
+ const query = next.includes("?") ? next.slice(next.indexOf("?")) : next;
78
+ return new URLSearchParams(query).get("cursor") ?? void 0;
79
+ };
80
+ var projectAri = (cloudId, projectId) => `ari:cloud:jira:${cloudId}:project/${projectId}`;
81
+ var rulePayload = (raw, file) => {
82
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
83
+ throw exitError(1, `${file}: expected a JSON object holding a rule`);
84
+ return "rule" in raw ? raw : { rule: raw };
85
+ };
86
+ var readRuleFile = (file) => {
87
+ const text = file === "-" ? readFileSync(0, "utf8") : readFileSync(file, "utf8");
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(text);
91
+ } catch (error) {
92
+ throw exitError(
93
+ 1,
94
+ `${file}: not valid JSON \u2014 ${error instanceof Error ? error.message : String(error)}`
95
+ );
96
+ }
97
+ return rulePayload(parsed, file);
98
+ };
99
+ var STATES = /* @__PURE__ */ new Set(["ENABLED", "DISABLED"]);
100
+ var hostOption = (command) => command.option(
101
+ "--host <site|api>",
102
+ "where to reach the Automation API: the site gateway, or api.atlassian.com (env: ATLASSIAN_AUTOMATION_HOST)"
103
+ );
104
+ var setState = (automationCommand, name, state) => {
105
+ hostOption(
106
+ automationCommand.command(`${name} <uuid>`).description(`${name} a rule`)
107
+ ).action(async (uuid, options) => {
108
+ const { call } = await automation(options.host);
109
+ await call(`/rule/${encodeURIComponent(uuid)}/state`, {
110
+ method: "PUT",
111
+ body: JSON.stringify({ value: state })
112
+ });
113
+ process.stderr.write(`${name}d ${uuid}
114
+ `);
115
+ });
116
+ };
117
+ var registerAutomationCommands = (program2) => {
118
+ const automationCommand = program2.command("automation").description("list, read, create and switch Jira Automation rules").addHelpText(
119
+ "after",
120
+ `
121
+ Needs the Jira administrator global permission on the account behind
122
+ ATLASSIAN_API_TOKEN (a classic API token). Project admin is not enough.
123
+
124
+ Examples:
125
+ jira automation list --project SHOP
126
+ jira automation get 0192e5ac-0e25-71de-ba7b-d972e6a2049a > rule.json
127
+ jira automation update 0192e5ac-0e25-71de-ba7b-d972e6a2049a --file rule.json
128
+ jira automation disable 0192e5ac-0e25-71de-ba7b-d972e6a2049a
129
+ `
130
+ );
131
+ hostOption(
132
+ automationCommand.command("list").description("list rules, optionally only those scoped to a project").option("-p, --project <key>", "only rules scoped to this project").option("--state <state>", "ENABLED or DISABLED").option("-n, --limit <n>", "maximum rules to return", "100").option("--json", "emit JSON")
133
+ ).action(
134
+ async (options) => {
135
+ const limit = Number(options.limit);
136
+ if (!Number.isInteger(limit) || limit < 1)
137
+ throw exitError(1, `--limit must be a positive whole number`);
138
+ const state = options.state?.toUpperCase();
139
+ if (state && !STATES.has(state))
140
+ throw exitError(1, `--state must be ENABLED or DISABLED`);
141
+ const { ctx, cloudId, call } = await automation(options.host);
142
+ let scope;
143
+ if (options.project) {
144
+ const project = await ctx.client.request(
145
+ `/rest/api/3/project/${encodeURIComponent(options.project)}`
146
+ );
147
+ scope = projectAri(cloudId, project.id);
148
+ }
149
+ const rules = [];
150
+ let cursor;
151
+ do {
152
+ const page = await call("/rule/summary", {
153
+ method: "POST",
154
+ body: JSON.stringify({
155
+ limit: Math.min(100, limit - rules.length),
156
+ ...scope ? { scope } : {},
157
+ ...state ? { state } : {},
158
+ ...cursor ? { cursor } : {}
159
+ })
160
+ });
161
+ rules.push(...page?.data ?? []);
162
+ cursor = nextCursor(page?.links?.next);
163
+ } while (cursor && rules.length < limit);
164
+ if (options.json) {
165
+ printJson(rules);
166
+ warnIfTruncated(rules.length, limit, { exitCode: true });
167
+ return;
168
+ }
169
+ if (rules.length === 0) {
170
+ process.stderr.write("no rules match\n");
171
+ return;
172
+ }
173
+ process.stdout.write(
174
+ `${table(rules, [
175
+ { header: "UUID", value: (r) => r.uuid },
176
+ { header: "STATE", value: (r) => r.state },
177
+ { header: "NAME", value: (r) => r.name }
178
+ ])}
179
+ `
180
+ );
181
+ warnIfTruncated(rules.length, limit, { exitCode: false });
182
+ }
183
+ );
184
+ hostOption(
185
+ automationCommand.command("get <uuid>").description("print a rule's full configuration as JSON").option(
186
+ "--redact",
187
+ "redact sensitive fields such as secrets in web requests"
188
+ )
189
+ ).action(async (uuid, options) => {
190
+ const { call } = await automation(options.host);
191
+ const query = options.redact ? "?redactSensitiveFields=true" : "";
192
+ printJson(await call(`/rule/${encodeURIComponent(uuid)}${query}`));
193
+ });
194
+ hostOption(
195
+ automationCommand.command("create").description("create a rule from a JSON file (the shape `get` prints)").requiredOption("-f, --file <path>", "rule JSON, or - for stdin")
196
+ ).action(async (options) => {
197
+ const body = readRuleFile(options.file);
198
+ const { call } = await automation(options.host);
199
+ const created = await call("/rule", {
200
+ method: "POST",
201
+ body: JSON.stringify(body)
202
+ });
203
+ process.stdout.write(`${created?.ruleUuid ?? ""}
204
+ `);
205
+ });
206
+ hostOption(
207
+ automationCommand.command("update <uuid>").description(
208
+ "replace a rule with the JSON in a file (the shape `get` prints)"
209
+ ).requiredOption("-f, --file <path>", "rule JSON, or - for stdin")
210
+ ).action(async (uuid, options) => {
211
+ const body = readRuleFile(options.file);
212
+ const { call } = await automation(options.host);
213
+ await call(`/rule/${encodeURIComponent(uuid)}`, {
214
+ method: "PUT",
215
+ body: JSON.stringify(body)
216
+ });
217
+ process.stderr.write(`updated ${uuid}
218
+ `);
219
+ });
220
+ setState(automationCommand, "enable", "ENABLED");
221
+ setState(automationCommand, "disable", "DISABLED");
222
+ };
18
223
 
19
224
  // src/commands/attachment.ts
20
225
  import { writeFileSync } from "fs";
@@ -270,7 +475,7 @@ import { execFile } from "child_process";
270
475
  import { adfToMarkdown as adfToMarkdown2, flattenIssueLinks as flattenIssueLinks2, locateAttachments as locateAttachments2 } from "@kud/jira";
271
476
 
272
477
  // src/commands/issue-write.ts
273
- import { readFileSync } from "fs";
478
+ import { readFileSync as readFileSync2 } from "fs";
274
479
  import { adfToMarkdown, flattenIssueLinks, markdownToAdf } from "@kud/jira";
275
480
 
276
481
  // src/commands/confirm.ts
@@ -300,7 +505,7 @@ var rankPosition = (options) => {
300
505
  if (before) return { before };
301
506
  return { after };
302
507
  };
303
- var readBody = (value) => value === "-" ? readFileSync(0, "utf8") : value;
508
+ var readBody = (value) => value === "-" ? readFileSync2(0, "utf8") : value;
304
509
  var projectOf = (issueKey) => issueKey.split("-")[0];
305
510
  var collectLink = (value, prior) => [
306
511
  ...prior,
@@ -1161,6 +1366,7 @@ Examples:
1161
1366
  jira attachment list ABC-123
1162
1367
  jira attachment read ABC-123 error.log | grep -i timeout
1163
1368
  jira search 'project = ABC AND created >= -7d' --json | jq '.[].key'
1369
+ jira automation list --project ABC
1164
1370
  `
1165
1371
  );
1166
1372
  registerIssueCommands(program);
@@ -1176,10 +1382,11 @@ registerEpicCommands(program);
1176
1382
  registerUserCommands(program);
1177
1383
  registerMetaCommands(program);
1178
1384
  registerCountCommand(program);
1385
+ registerAutomationCommands(program);
1179
1386
  registerApiCommand(program);
1180
1387
  var exitCodeFor = (error) => {
1181
1388
  if (isExitError(error)) return error.code;
1182
- if (isJiraApiError(error))
1389
+ if (isJiraApiError2(error))
1183
1390
  return error.status === 401 || error.status === 403 ? 4 : 1;
1184
1391
  return 1;
1185
1392
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kud/jira-cli",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Jira on the command line — read issues, comments and attachments as plain text",
6
6
  "keywords": [