@axway/axway-central-cli 2.17.0-rc.5 → 2.17.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 (58) hide show
  1. package/dist/cli.js +28 -6
  2. package/dist/commands/apply/index.js +24 -9
  3. package/dist/commands/completion/index.js +9 -3
  4. package/dist/commands/config/common/index.js +11 -2
  5. package/dist/commands/config/index.js +7 -2
  6. package/dist/commands/config/list.js +6 -2
  7. package/dist/commands/config/set.js +31 -4
  8. package/dist/commands/config/unset.js +12 -2
  9. package/dist/commands/create/agentResource.js +32 -12
  10. package/dist/commands/create/environment.js +16 -6
  11. package/dist/commands/create/index.js +26 -9
  12. package/dist/commands/create/serviceAccount.js +6 -2
  13. package/dist/commands/delete/index.js +33 -15
  14. package/dist/commands/edit/environment.js +21 -6
  15. package/dist/commands/edit/index.js +8 -4
  16. package/dist/commands/get/index.js +44 -27
  17. package/dist/commands/install/agents.js +73 -44
  18. package/dist/commands/install/apigeexSaasAgents.js +98 -35
  19. package/dist/commands/install/awsAgents.js +139 -89
  20. package/dist/commands/install/awsSaasAgents.js +142 -50
  21. package/dist/commands/install/azureAgents.js +79 -39
  22. package/dist/commands/install/edgeAgents.js +110 -17
  23. package/dist/commands/install/helpers/creators.js +70 -17
  24. package/dist/commands/install/helpers/deleters.js +11 -2
  25. package/dist/commands/install/helpers/getters.js +30 -4
  26. package/dist/commands/install/helpers/index.js +48 -13
  27. package/dist/commands/install/helpers/inputs.js +98 -26
  28. package/dist/commands/install/helpers/regex.js +34 -29
  29. package/dist/commands/install/helpers/templates/awsTemplates.js +23 -6
  30. package/dist/commands/install/helpers/templates/azureTemplates.js +24 -5
  31. package/dist/commands/install/helpers/templates/edgeTemplates.js +38 -7
  32. package/dist/commands/install/helpers/templates/istioTemplates.js +16 -5
  33. package/dist/commands/install/index.js +10 -4
  34. package/dist/commands/install/istioAgents.js +117 -40
  35. package/dist/commands/install/platform.js +52 -20
  36. package/dist/commands/proxies/create.js +18 -2
  37. package/dist/commands/proxies/index.js +8 -4
  38. package/dist/commands/proxies/promote.js +21 -2
  39. package/dist/common/ApiServerClient.js +173 -64
  40. package/dist/common/CacheController.js +32 -11
  41. package/dist/common/CliConfigManager.js +27 -14
  42. package/dist/common/CompositeError.js +30 -6
  43. package/dist/common/CoreConfigController.js +40 -18
  44. package/dist/common/DefinitionsManager.js +76 -29
  45. package/dist/common/Kubectl.js +25 -2
  46. package/dist/common/PlatformClient.js +63 -19
  47. package/dist/common/Renderer.js +87 -25
  48. package/dist/common/TmpFile.js +28 -11
  49. package/dist/common/bashCommands.js +22 -3
  50. package/dist/common/basicPrompts.js +43 -8
  51. package/dist/common/dataService.js +50 -22
  52. package/dist/common/errorHandler.js +9 -0
  53. package/dist/common/resultsRenderers.js +42 -10
  54. package/dist/common/types.js +341 -116
  55. package/dist/common/utils.js +99 -37
  56. package/dist/main.js +2 -0
  57. package/package.json +2 -2
  58. package/dist/commands/install/gitHubSaasAgents.js +0 -283
@@ -4,13 +4,14 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.verifyApigeeXCredentialFile = exports.validateValueRange = exports.validateValidRegex = exports.validateRegex = exports.validateNonEmptyInput = exports.validateInputIsNew = exports.runValidations = exports.filterEmptyNumberInput = exports.askUsernameAndPassword = exports.askList = exports.askInputValidation = exports.askInput = exports.MAX_FILE_SIZE = void 0;
7
+
7
8
  var _inquirer = _interopRequireDefault(require("inquirer"));
9
+
8
10
  var _fsExtra = require("fs-extra");
11
+
9
12
  var _path = require("path");
13
+
10
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
- //
12
- // Basic Prompts
13
- //
14
15
 
15
16
  /**
16
17
  * @param validators At least one InputValidation func
@@ -23,20 +24,28 @@ const runValidations = (...validators) => input => {
23
24
  const res = validator(input);
24
25
  if (typeof res === 'string') return res;
25
26
  }
27
+
26
28
  return true;
27
29
  };
30
+
28
31
  exports.runValidations = runValidations;
32
+
29
33
  const validateRegex = (regexp, message) => input => {
30
34
  return input.toString().match(regexp) ? true : message;
31
35
  };
36
+
32
37
  exports.validateRegex = validateRegex;
33
- const MAX_FILE_SIZE = exports.MAX_FILE_SIZE = process.env.NODE_ENV === 'test' ? 1e5 : 20 * 1024 * 1024;
38
+ const MAX_FILE_SIZE = process.env.NODE_ENV === 'test' ? 1e5 : 20 * 1024 * 1024;
39
+ exports.MAX_FILE_SIZE = MAX_FILE_SIZE;
40
+
34
41
  const verifyApigeeXCredentialFile = () => input => {
35
42
  let stats;
36
43
  let fileExtension = '';
44
+
37
45
  try {
38
46
  stats = (0, _fsExtra.lstatSync)(input);
39
47
  fileExtension = (0, _path.extname)(input);
48
+
40
49
  if (!stats.isFile()) {
41
50
  throw new Error(`Couldn't load the credential file: ${input}`);
42
51
  } else if (stats.size >= MAX_FILE_SIZE) {
@@ -44,32 +53,43 @@ const verifyApigeeXCredentialFile = () => input => {
44
53
  } else if (fileExtension !== '.json') {
45
54
  throw new Error(`File extension is invalid, please provide '.json' file`);
46
55
  }
56
+
47
57
  return true;
48
58
  } catch (e) {
49
59
  throw new Error(`Couldn't find the credential file: ${input}`);
50
60
  }
51
61
  };
62
+
52
63
  exports.verifyApigeeXCredentialFile = verifyApigeeXCredentialFile;
64
+
53
65
  const validateValidRegex = () => input => {
54
66
  try {
55
67
  new RegExp(input.toString());
56
68
  } catch (error) {
57
69
  return 'Please provide a valid regular expression.';
58
70
  }
71
+
59
72
  return true;
60
73
  };
74
+
61
75
  exports.validateValidRegex = validateValidRegex;
76
+
62
77
  const validateInputIsNew = (options, error) => input => {
63
78
  const isFound = options.find(opt => opt === input);
64
79
  return isFound ? error : true;
65
80
  };
81
+
66
82
  exports.validateInputIsNew = validateInputIsNew;
83
+
67
84
  const validateValueRange = (lowerLimit, upperLimit) => input => {
68
85
  const inputNum = Number(input);
86
+
69
87
  if (isNaN(inputNum)) {
70
88
  return 'Please provide a number.';
71
89
  }
90
+
72
91
  let msg = "";
92
+
73
93
  if (typeof lowerLimit !== undefined && typeof upperLimit !== undefined) {
74
94
  msg = `Please provide a number from ${lowerLimit} to ${upperLimit}`;
75
95
  } else if (typeof lowerLimit !== undefined) {
@@ -77,37 +97,47 @@ const validateValueRange = (lowerLimit, upperLimit) => input => {
77
97
  } else if (typeof upperLimit !== undefined) {
78
98
  msg = `Please provide a maximum number of ${upperLimit}`;
79
99
  }
100
+
80
101
  if (typeof lowerLimit !== undefined && inputNum < lowerLimit) {
81
102
  return msg;
82
103
  }
104
+
83
105
  if (typeof upperLimit !== undefined && inputNum > upperLimit) {
84
106
  return msg;
85
107
  }
108
+
86
109
  return true;
87
- };
110
+ }; // exporting for test
111
+
88
112
 
89
- // exporting for test
90
113
  exports.validateValueRange = validateValueRange;
114
+
91
115
  const validateNonEmptyInput = input => {
92
116
  return String(input).length ? true : 'Please provide a non-empty value.';
93
- };
117
+ }; // exporting for test
118
+
94
119
 
95
- // exporting for test
96
120
  exports.validateNonEmptyInput = validateNonEmptyInput;
121
+
97
122
  const filterEmptyNumberInput = input => {
98
123
  // clear the invalid input
99
124
  return Number.isNaN(input) ? '' : Number(input);
100
125
  };
126
+
101
127
  exports.filterEmptyNumberInput = filterEmptyNumberInput;
128
+
102
129
  const askInputValidation = (allowEmptyInput, validate) => input => {
103
130
  if (allowEmptyInput && !String(input).length) {
104
131
  return true;
105
132
  }
133
+
106
134
  const isEmpty = allowEmptyInput ? true : validateNonEmptyInput(input);
107
135
  if (typeof isEmpty === 'string') return isEmpty;
108
136
  return validate ? validate(input) : true;
109
137
  };
138
+
110
139
  exports.askInputValidation = askInputValidation;
140
+
111
141
  const askInput = async ({
112
142
  msg,
113
143
  defaultValue,
@@ -125,7 +155,9 @@ const askInput = async ({
125
155
  });
126
156
  return answers.value;
127
157
  };
158
+
128
159
  exports.askInput = askInput;
160
+
129
161
  const askList = async opts => {
130
162
  const answers = await _inquirer.default.prompt({
131
163
  type: 'list',
@@ -136,7 +168,9 @@ const askList = async opts => {
136
168
  });
137
169
  return answers.value;
138
170
  };
171
+
139
172
  exports.askList = askList;
173
+
140
174
  const askUsernameAndPassword = async (msg, defaultUsername) => {
141
175
  const answers = await _inquirer.default.prompt([{
142
176
  type: 'input',
@@ -153,4 +187,5 @@ const askUsernameAndPassword = async (msg, defaultUsername) => {
153
187
  }]);
154
188
  return answers;
155
189
  };
190
+
156
191
  exports.askUsernameAndPassword = askUsernameAndPassword;
@@ -4,27 +4,38 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.getBaseUrl = exports.dataService = void 0;
7
+
7
8
  var _amplifyCliUtils = require("@axway/amplify-cli-utils");
9
+
8
10
  var _got = require("got");
11
+
9
12
  var _flatten = _interopRequireDefault(require("lodash/flatten"));
13
+
10
14
  var _promiseLimit = _interopRequireDefault(require("promise-limit"));
15
+
11
16
  var _snooplogg = _interopRequireDefault(require("snooplogg"));
17
+
12
18
  var _url = require("url");
19
+
13
20
  var _CoreConfigController = require("./CoreConfigController");
21
+
14
22
  var _types = require("./types");
23
+
15
24
  var _utils = require("./utils");
25
+
16
26
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
27
+
17
28
  // NOTE: removing update-notifier due to some security issues reported.
18
29
  // There is suppression in '.csr-profile.json' that needed to be removed if this library is used in production code.
19
30
  // import updateNotifier from 'update-notifier';
20
31
  // import semver from 'semver';
21
-
22
32
  // dep of @axway/amplify-cli-utils -> @axway/amplify-request
23
-
24
33
  const thisPackage = require('../../package.json');
34
+
25
35
  const {
26
36
  log
27
37
  } = (0, _snooplogg.default)('central: dataService');
38
+
28
39
  const getDefaultHeaders = ({
29
40
  token,
30
41
  orgId
@@ -36,9 +47,7 @@ const getDefaultHeaders = ({
36
47
  [_types.cliVersionHeader]: thisPackage.version,
37
48
  'User-Agent': 'axway-cli'
38
49
  };
39
- };
40
-
41
- // TODO: need to refactor this part, data service is used as part of many basic command (create / update, etc.) now.
50
+ }; // TODO: need to refactor this part, data service is used as part of many basic command (create / update, etc.) now.
42
51
  // Plus need to revisit this logic since no testing can be done currently (no new prod versions has been released yet)
43
52
  // https://jira.axway.com/browse/APIGOV-14969
44
53
  // const versionCheckWarning = async () => {
@@ -55,8 +64,10 @@ const getDefaultHeaders = ({
55
64
  // }
56
65
  // };
57
66
 
67
+
58
68
  const getBaseUrl = async (baseUrl, basePath, region, orgRegion) => {
59
69
  const configuredBaseUrl = baseUrl || process.env.AXWAY_CENTRAL_BASE_URL || (await (0, _utils.getConfig)())[_types.ConfigTypes.BASE_URL];
70
+
60
71
  if (configuredBaseUrl) {
61
72
  return basePath ? configuredBaseUrl + basePath : configuredBaseUrl;
62
73
  } else {
@@ -68,27 +79,33 @@ const getBaseUrl = async (baseUrl, basePath, region, orgRegion) => {
68
79
  return basePath ? prodBaseurl + basePath : prodBaseurl;
69
80
  }
70
81
  };
82
+
71
83
  exports.getBaseUrl = getBaseUrl;
84
+
72
85
  const handleResponse = response => {
73
86
  return /application\/json/.test(response.headers['content-type']) ? JSON.parse(response.body) : response.body;
74
87
  };
88
+
75
89
  const updateRequestError = err => {
76
90
  var _err$response;
91
+
77
92
  // Do not change given object if it's a timeout error.
78
93
  if (err instanceof _got.TimeoutError) {
79
94
  return;
80
- }
95
+ } // If we have a JSON HTTP body, then turn it into a dictionary.
96
+
81
97
 
82
- // If we have a JSON HTTP body, then turn it into a dictionary.
83
98
  let jsonBody = null;
99
+
84
100
  if (err instanceof _got.RequestError && (_err$response = err.response) !== null && _err$response !== void 0 && _err$response.body) {
85
101
  jsonBody = handleResponse(err.response);
86
102
  }
103
+
87
104
  if (!jsonBody) {
88
105
  return;
89
- }
106
+ } // Turn given Error object into an "ApiServerError" or "ApiServerErrorResponse" object.
107
+
90
108
 
91
- // Turn given Error object into an "ApiServerError" or "ApiServerErrorResponse" object.
92
109
  if (typeof jsonBody.code === 'number' && typeof jsonBody.description === 'string') {
93
110
  // We received a "Platform" server error response.
94
111
  err.status = jsonBody.code;
@@ -98,7 +115,6 @@ const updateRequestError = err => {
98
115
  Object.assign(err, jsonBody);
99
116
  }
100
117
  };
101
-
102
118
  /**
103
119
  * Creates an object with various functions communicating with the API Server.
104
120
  * @param {String} clientId Client id to use.
@@ -106,6 +122,8 @@ const updateRequestError = err => {
106
122
  * @param {String} [region] The preferred region to use.
107
123
  * @returns Object containing data retrieval functions.
108
124
  */
125
+
126
+
109
127
  const dataService = async ({
110
128
  account,
111
129
  baseUrl,
@@ -132,6 +150,7 @@ const dataService = async ({
132
150
  token
133
151
  });
134
152
  const got = (0, _amplifyCliUtils.createRequestClient)();
153
+
135
154
  const fetch = async (method, url, params = {}) => {
136
155
  try {
137
156
  // add the team guid
@@ -140,28 +159,31 @@ const dataService = async ({
140
159
  parsed.searchParams.set('query', teamGuid ? `owner.id==${teamGuid},(owner.id==null;metadata.scope.owner.id==${teamGuid})` : 'owner.id==null');
141
160
  url = parsed.toString();
142
161
  }
162
+
143
163
  const response = await got[method](url, {
144
164
  followRedirect: false,
145
165
  retry: 0,
146
166
  timeout: _types.ABORT_TIMEOUT,
147
167
  ...params
148
168
  });
169
+
149
170
  if (response.statusCode === 301 || response.statusCode === 302) {
150
171
  log(`${method.toUpperCase()}: ${url} ${response.statusCode} redirecting to ${response.headers.location}`);
151
172
  return await fetch(method, response.headers.location, params);
152
173
  }
174
+
153
175
  return response;
154
176
  } catch (err) {
155
177
  updateRequestError(err);
156
178
  throw err;
157
179
  }
158
180
  };
181
+
159
182
  return {
160
183
  postFormData: (route, body, headers = {}) => {
161
184
  log(`POST (from data): ${url + route}`);
162
185
  return fetch('post', url + route, {
163
- headers: {
164
- ...defaultHeaders,
186
+ headers: { ...defaultHeaders,
165
187
  ...body.getHeaders(),
166
188
  ...headers
167
189
  },
@@ -172,8 +194,7 @@ const dataService = async ({
172
194
  log(`POST: ${url + route}`);
173
195
  log(data);
174
196
  return fetch('post', url + route, {
175
- headers: {
176
- ...defaultHeaders,
197
+ headers: { ...defaultHeaders,
177
198
  ...headers
178
199
  },
179
200
  json: data
@@ -182,16 +203,14 @@ const dataService = async ({
182
203
  put: (route, data, headers = {}) => {
183
204
  log(`PUT: ${url + route}`);
184
205
  return fetch('put', url + route, {
185
- headers: {
186
- ...defaultHeaders,
206
+ headers: { ...defaultHeaders,
187
207
  ...headers
188
208
  },
189
209
  json: data
190
210
  }).then(handleResponse);
191
211
  },
192
212
  get: (route, headers = {}, skipDefaultHeaders = false) => {
193
- const h = skipDefaultHeaders ? headers : {
194
- ...defaultHeaders,
213
+ const h = skipDefaultHeaders ? headers : { ...defaultHeaders,
195
214
  ...headers
196
215
  };
197
216
  log(`GET: ${url + route}`, h);
@@ -199,6 +218,7 @@ const dataService = async ({
199
218
  headers: h
200
219
  }).then(handleResponse);
201
220
  },
221
+
202
222
  /**
203
223
  * Get the entire list using pagination. Method is trying to define total number of items based on response header
204
224
  * and makes additional calls if needed to retrieve additional pages.
@@ -214,30 +234,36 @@ const dataService = async ({
214
234
  fullUrl.searchParams.set('pageSize', `${pageSize}`);
215
235
  log(`GET (with auto-pagination): ${fullUrl.href}`);
216
236
  const response = await fetch('get', fullUrl.toString(), {
217
- headers: {
218
- ...defaultHeaders,
237
+ headers: { ...defaultHeaders,
219
238
  ...headers
220
239
  }
221
240
  });
222
241
  const totalCountHeader = response.headers['x-axway-total-count'];
242
+
223
243
  if (totalCountHeader === null || totalCountHeader === undefined) {
224
244
  log(`GET (with auto-pagination), warning: cannot figure out 'total count' header, resolving response as-is`);
225
245
  return handleResponse(response);
226
246
  }
247
+
227
248
  log(`GET (with auto-pagination), 'total count' header found, count = ${totalCountHeader}, will fire additional GET calls if needed`);
228
249
  const totalPages = Math.max(Math.ceil(Number(totalCountHeader) / pageSize), 1);
229
250
  const allPages = new Array(totalPages);
230
251
  allPages[0] = handleResponse(response);
252
+
231
253
  if (totalPages > 1) {
232
254
  const limit = (0, _promiseLimit.default)(8); // Limits number of concurrrent HTTP requests.
255
+
233
256
  const otherPagesCalls = [];
234
257
  let pageDownloadCount = 1;
258
+
235
259
  const updateProgress = () => {
236
260
  if (progressListener && totalPages > 4) {
237
261
  progressListener(Math.floor(pageDownloadCount / totalPages * 100));
238
262
  }
239
263
  };
264
+
240
265
  updateProgress();
266
+
241
267
  for (let pageIndex = 1; pageIndex < totalPages; pageIndex++) {
242
268
  const thisPageIndex = pageIndex;
243
269
  fullUrl.searchParams.set('page', `${thisPageIndex + 1}`);
@@ -248,15 +274,16 @@ const dataService = async ({
248
274
  updateProgress();
249
275
  }));
250
276
  }
277
+
251
278
  await Promise.all(otherPagesCalls);
252
279
  }
280
+
253
281
  return (0, _flatten.default)(allPages);
254
282
  },
255
283
  delete: (route, headers = {}) => {
256
284
  log(`DELETE: ${url + route}`);
257
285
  return fetch('delete', url + route, {
258
- headers: {
259
- ...defaultHeaders,
286
+ headers: { ...defaultHeaders,
260
287
  ...headers
261
288
  }
262
289
  }).then(handleResponse);
@@ -288,4 +315,5 @@ const dataService = async ({
288
315
  }
289
316
  };
290
317
  };
318
+
291
319
  exports.dataService = dataService;
@@ -4,12 +4,15 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.handleErrors = void 0;
7
+
7
8
  var _cliKit = require("cli-kit");
9
+
8
10
  // TODO: used by legacy "proxies" command only, will be removed soon
9
11
  // https://jira.axway.com/browse/APIGOV-20818
10
12
  const handleErrors = (console, e, spinner) => {
11
13
  if (e.errors && Array.isArray(e.errors)) {
12
14
  const error = e.errors[0];
15
+
13
16
  if (spinner) {
14
17
  switch (error.status) {
15
18
  case 401:
@@ -19,23 +22,28 @@ const handleErrors = (console, e, spinner) => {
19
22
  console.info('Or if using a service account:');
20
23
  console.info((0, _cliKit.chalk)`{cyan axway auth login --client-id <Service Account Client ID> --secret-file <Private Key>}`);
21
24
  break;
25
+
22
26
  case 403:
23
27
  spinner.fail((0, _cliKit.chalk)`{red ${error.detail}}`);
24
28
  break;
29
+
25
30
  case 400:
26
31
  spinner.fail((0, _cliKit.chalk)`{red Error: ${error.detail || error.title}}`);
27
32
  if (error.source) console.log((0, _cliKit.chalk)`{gray Caused by: ${JSON.stringify(error.source)}}`);
28
33
  break;
34
+
29
35
  case 404:
30
36
  case 409:
31
37
  spinner.fail((0, _cliKit.chalk)`{red ${error.title}\n{blueBright ${error.detail}}}`);
32
38
  break;
39
+
33
40
  default:
34
41
  spinner.fail((0, _cliKit.chalk)`{red An error occurred}`);
35
42
  }
36
43
  } else {
37
44
  console.error(error);
38
45
  }
46
+
39
47
  process.exit(1);
40
48
  } else if (e instanceof Error) {
41
49
  let message = e.name === 'TimeoutError' ? `Couldn't connect to Amplify Central` : e.message;
@@ -43,4 +51,5 @@ const handleErrors = (console, e, spinner) => {
43
51
  process.exit(1);
44
52
  } else throw e;
45
53
  };
54
+
46
55
  exports.handleErrors = handleErrors;
@@ -5,16 +5,27 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.renderResponse = exports.parseAsYaml = exports.parseAsJson = void 0;
7
7
  exports.resolveTeamNames = resolveTeamNames;
8
+
8
9
  var _chalk = _interopRequireDefault(require("chalk"));
10
+
9
11
  var _dayjs = _interopRequireDefault(require("dayjs"));
12
+
10
13
  var _easyTable = _interopRequireDefault(require("easy-table"));
14
+
11
15
  var _jsYaml = require("js-yaml");
16
+
12
17
  var _get = _interopRequireDefault(require("lodash/get"));
18
+
13
19
  var _set = _interopRequireDefault(require("lodash/set"));
20
+
14
21
  var _CoreConfigController = require("./CoreConfigController");
22
+
15
23
  var _amplifyCliUtils = require("@axway/amplify-cli-utils");
24
+
16
25
  var _types = require("./types");
26
+
17
27
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28
+
18
29
  /**
19
30
  * HACK: removing "---" delimiter printing from the lib.
20
31
  * Currently this is not supported in library itself so have to override prototype methods.
@@ -22,15 +33,17 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
22
33
  _easyTable.default.prototype.pushDelimeter = function () {
23
34
  return this;
24
35
  };
25
-
26
36
  /**
27
37
  * Parse JSON object | array of objects as YAML
28
38
  * @param response request response payload
29
39
  * @param console current console
30
40
  * @returns parsed string with YAML objects representation
31
41
  */
42
+
43
+
32
44
  const parseAsYaml = response => {
33
45
  let result = '';
46
+
34
47
  if (Array.isArray(response)) {
35
48
  for (const i of response) {
36
49
  result += `\n---\n${(0, _jsYaml.dump)(i)}`;
@@ -38,9 +51,9 @@ const parseAsYaml = response => {
38
51
  } else {
39
52
  result = (0, _jsYaml.dump)(response);
40
53
  }
54
+
41
55
  return result;
42
56
  };
43
-
44
57
  /**
45
58
  * Parse JSON object | array of objects as simple text table,
46
59
  * NOTE: currently can build table only for "Environment" type.
@@ -49,14 +62,19 @@ const parseAsYaml = response => {
49
62
  * @param columns columns config from CommandLineInterface resource definition
50
63
  * @returns parsed string with table objects representation
51
64
  */
65
+
66
+
52
67
  exports.parseAsYaml = parseAsYaml;
68
+
53
69
  const parseAsTable = (response, columns) => {
54
70
  const data = Array.isArray(response) ? response : [response];
55
71
  const t = new _easyTable.default();
72
+
56
73
  for (const i of data) {
57
74
  for (const col of columns) {
58
75
  // jsonPath starts with '.' so using the substring
59
76
  let value = (0, _get.default)(i, col.jsonPath.substring(1));
77
+
60
78
  if (col.type === 'date') {
61
79
  value = (0, _dayjs.default)(value).fromNow();
62
80
  } else if (col.type === 'teamGuid' && !value) {
@@ -64,42 +82,52 @@ const parseAsTable = (response, columns) => {
64
82
  } else if (value && value.length > _types.MAX_TABLE_STRING_LENGTH + 3) {
65
83
  value = value.substring(0, _types.MAX_TABLE_STRING_LENGTH / 2) + '...' + value.substring(value.length - _types.MAX_TABLE_STRING_LENGTH / 2);
66
84
  }
85
+
67
86
  t.cell(col.name.toUpperCase(), value);
68
87
  }
88
+
69
89
  t.newRow();
70
90
  }
91
+
71
92
  return data.length ? `\n${t.toString()}` : '\nNo resources found.';
72
93
  };
73
-
74
94
  /**
75
95
  * Parse JSON object | array of objects as is but without any replacing like [object Object].
76
96
  * @param response request response payload
77
97
  * @param console current console
78
98
  * @returns parsed string with JSON objects representation
79
99
  */
80
- const parseAsJson = response => JSON.stringify(response, null, 4);
81
100
 
101
+
102
+ const parseAsJson = response => JSON.stringify(response, null, 4);
82
103
  /**
83
104
  * Util function to render JSON object | array of objects based on output type provided
84
105
  * @param response request response payload
85
106
  * @param output type of output to render (table (default) / yaml / json)
86
107
  * @param console current console
87
108
  */
109
+
110
+
88
111
  exports.parseAsJson = parseAsJson;
112
+
89
113
  const renderResponse = (console, response, output, columns) => {
90
114
  switch (output) {
91
115
  case _types.OutputTypes.yaml:
92
116
  console.log(parseAsYaml(response));
93
117
  break;
118
+
94
119
  case _types.OutputTypes.json:
95
120
  console.log(parseAsJson(response));
96
121
  break;
122
+
97
123
  default:
98
124
  // @ts-ignore TODO: fix types error once more types are used
99
125
  console.log(parseAsTable(response, columns));
100
126
  }
101
127
  };
128
+
102
129
  exports.renderResponse = renderResponse;
130
+
103
131
  /**
104
132
  * If a team guid column is being rendered, it resolves the team name and injects it into
105
133
  * the response payload.
@@ -112,9 +140,11 @@ async function resolveTeamNames({
112
140
  }) {
113
141
  // check that we even have a team guid column
114
142
  const column = columns === null || columns === void 0 ? void 0 : columns.find(col => col.type === 'teamGuid');
143
+
115
144
  if (!column || !_CoreConfigController.CoreConfigController.devOpsAccount) {
116
145
  return;
117
146
  }
147
+
118
148
  const jsonPath = column.jsonPath.substring(1);
119
149
  const results = Array.isArray(response) ? response : [response];
120
150
  const teamNames = {};
@@ -125,32 +155,34 @@ async function resolveTeamNames({
125
155
  sdk
126
156
  } = (0, _amplifyCliUtils.initSDK)({
127
157
  env: devOpsAccount.auth.env
128
- });
158
+ }); // build the team name lookup
129
159
 
130
- // build the team name lookup
131
160
  const {
132
161
  teams
133
162
  } = await sdk.team.list(devOpsAccount);
163
+
134
164
  for (const team of teams) {
135
165
  teamNames[team.guid] = team.name;
136
- }
166
+ } // create the new jsonPath and update the column
167
+
137
168
 
138
- // create the new jsonPath and update the column
139
169
  const targetJsonPath = jsonPath.split('.').slice(0, -1).join('.') + '.teamName';
140
- column.jsonPath = `.${targetJsonPath}`;
170
+ column.jsonPath = `.${targetJsonPath}`; // next loop over data and set the team name
141
171
 
142
- // next loop over data and set the team name
143
172
  for (let {
144
173
  data
145
174
  } of results) {
146
175
  if (!data || typeof data !== 'object') {
147
176
  continue;
148
177
  }
178
+
149
179
  if (!Array.isArray(data)) {
150
180
  data = [data];
151
181
  }
182
+
152
183
  for (const obj of data) {
153
184
  const value = (0, _get.default)(obj, jsonPath, null);
185
+
154
186
  if (value !== null) {
155
187
  (0, _set.default)(obj, targetJsonPath, value && teamNames[value] || value || '');
156
188
  }