-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathatlassian.api.cli.ts
More file actions
249 lines (226 loc) · 6.19 KB
/
atlassian.api.cli.ts
File metadata and controls
249 lines (226 loc) · 6.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import { Command } from 'commander';
import { Logger } from '../utils/logger.util.js';
import { handleCliError } from '../utils/error.util.js';
import {
handleGet,
handlePost,
handlePut,
handlePatch,
handleDelete,
} from '../controllers/atlassian.api.controller.js';
/**
* CLI module for generic Confluence API access.
* Provides commands for making GET, POST, PUT, PATCH, and DELETE requests to any Confluence API endpoint.
*/
// Create a contextualized logger for this file
const cliLogger = Logger.forContext('cli/atlassian.api.cli.ts');
// Log CLI initialization
cliLogger.debug('Confluence API CLI module initialized');
/**
* Parse JSON string with error handling and basic validation
* @param jsonString - JSON string to parse
* @param fieldName - Name of the field for error messages
* @returns Parsed JSON object
*/
function parseJson<T extends Record<string, unknown>>(
jsonString: string,
fieldName: string,
): T {
let parsed: unknown;
try {
parsed = JSON.parse(jsonString);
} catch {
throw new Error(
`Invalid JSON in --${fieldName}. Please provide valid JSON.`,
);
}
// Validate that the parsed value is an object (not null, array, or primitive)
if (
parsed === null ||
typeof parsed !== 'object' ||
Array.isArray(parsed)
) {
throw new Error(
`Invalid --${fieldName}: expected a JSON object, got ${parsed === null ? 'null' : Array.isArray(parsed) ? 'array' : typeof parsed}.`,
);
}
return parsed as T;
}
/**
* Register a read command (GET/DELETE - no body)
* @param program - Commander program instance
* @param name - Command name
* @param description - Command description
* @param handler - Controller handler function
*/
function registerReadCommand(
program: Command,
name: string,
description: string,
handler: (options: {
path: string;
queryParams?: Record<string, string>;
jq?: string;
outputFormat?: 'toon' | 'json';
}) => Promise<{ content: string }>,
): void {
program
.command(name)
.description(description)
.requiredOption(
'-p, --path <path>',
'API endpoint path (e.g., "/wiki/api/v2/spaces", "/wiki/api/v2/pages/{id}").',
)
.option(
'-q, --query-params <json>',
'Query parameters as JSON string (e.g., \'{"limit": "25"}\').',
)
.option(
'--jq <expression>',
'JMESPath expression to filter/transform the response.',
)
.option(
'-o, --output-format <format>',
'Output format: "toon" (default, token-efficient) or "json".',
'toon',
)
.action(async (options) => {
const actionLogger = cliLogger.forMethod(name);
try {
actionLogger.debug(`CLI ${name} called`, options);
// Parse query params if provided
let queryParams: Record<string, string> | undefined;
if (options.queryParams) {
queryParams = parseJson<Record<string, string>>(
options.queryParams,
'query-params',
);
}
const result = await handler({
path: options.path,
queryParams,
jq: options.jq,
outputFormat: options.outputFormat as 'toon' | 'json',
});
console.log(result.content);
} catch (error) {
handleCliError(error);
}
});
}
/**
* Register a write command (POST/PUT/PATCH - with body)
* @param program - Commander program instance
* @param name - Command name
* @param description - Command description
* @param handler - Controller handler function
*/
function registerWriteCommand(
program: Command,
name: string,
description: string,
handler: (options: {
path: string;
body: Record<string, unknown>;
queryParams?: Record<string, string>;
jq?: string;
outputFormat?: 'toon' | 'json';
}) => Promise<{ content: string }>,
): void {
program
.command(name)
.description(description)
.requiredOption(
'-p, --path <path>',
'API endpoint path (e.g., "/wiki/api/v2/pages", "/wiki/api/v2/pages/{id}/labels").',
)
.requiredOption('-b, --body <json>', 'Request body as JSON string.')
.option('-q, --query-params <json>', 'Query parameters as JSON string.')
.option(
'--jq <expression>',
'JMESPath expression to filter/transform the response.',
)
.option(
'-o, --output-format <format>',
'Output format: "toon" (default, token-efficient) or "json".',
'toon',
)
.action(async (options) => {
const actionLogger = cliLogger.forMethod(name);
try {
actionLogger.debug(`CLI ${name} called`, options);
// Parse body
const body = parseJson<Record<string, unknown>>(
options.body,
'body',
);
// Parse query params if provided
let queryParams: Record<string, string> | undefined;
if (options.queryParams) {
queryParams = parseJson<Record<string, string>>(
options.queryParams,
'query-params',
);
}
const result = await handler({
path: options.path,
body,
queryParams,
jq: options.jq,
outputFormat: options.outputFormat as 'toon' | 'json',
});
console.log(result.content);
} catch (error) {
handleCliError(error);
}
});
}
/**
* Register generic Confluence API CLI commands with the Commander program
*
* @param program - The Commander program instance to register commands with
*/
function register(program: Command): void {
const methodLogger = Logger.forContext(
'cli/atlassian.api.cli.ts',
'register',
);
methodLogger.debug('Registering Confluence API CLI commands...');
// Register GET command
registerReadCommand(
program,
'get',
'GET any Confluence endpoint. Returns JSON, optionally filtered with JMESPath.',
handleGet,
);
// Register POST command
registerWriteCommand(
program,
'post',
'POST to any Confluence endpoint. Returns JSON, optionally filtered with JMESPath.',
handlePost,
);
// Register PUT command
registerWriteCommand(
program,
'put',
'PUT to any Confluence endpoint. Returns JSON, optionally filtered with JMESPath.',
handlePut,
);
// Register PATCH command
registerWriteCommand(
program,
'patch',
'PATCH any Confluence endpoint. Returns JSON, optionally filtered with JMESPath.',
handlePatch,
);
// Register DELETE command
registerReadCommand(
program,
'delete',
'DELETE any Confluence endpoint. Returns JSON (if any), optionally filtered with JMESPath.',
handleDelete,
);
methodLogger.debug('CLI commands registered successfully');
}
export default { register };