@opscompass/opscompass-cli 1.0.47 → 1.3.1

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/lib/maskValues.js CHANGED
@@ -13,15 +13,16 @@
13
13
 
14
14
  "use strict";
15
15
 
16
- const fs = require("fs");
17
- const path = require("path");
18
- const { utilsModule: utils } = require("./utils");
19
- const { opscompassHome } = require("../environment/current"); // For compatibility with the OpsCompass CLI
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import Database from "better-sqlite3";
19
+ import { utilsModule as utils } from "./utils.js";
20
+ import { opscompassHome } from "../environment/current.js"; // For compatibility with the OpsCompass CLI
20
21
 
21
22
  /**
22
23
  * Function to execute operating system commands
23
24
  */
24
- const { exec } = require("child_process");
25
+ import { exec } from "child_process";
25
26
  function executeCommand(command) {
26
27
  return new Promise((resolve, reject) => {
27
28
  exec(command, (error, stdout, stderr) => {
@@ -99,7 +100,7 @@ function getKeyCommand(maskType) {
99
100
  const keyCommand = path.join(
100
101
  opscompassHome,
101
102
  "keystore",
102
- `${maskType}-lookup.sh`
103
+ `${maskType}-lookup.sh`,
103
104
  );
104
105
  try {
105
106
  // If keyCommand exists and is executable, use that
@@ -133,8 +134,6 @@ class MaskDb {
133
134
  ];
134
135
 
135
136
  constructor(dbFileName, company = global?.company || "unspecified-company") {
136
- const Database = require("better-sqlite3");
137
-
138
137
  this.company = company;
139
138
  this.dbFilePath = path.join(opscompassHome, "configs", company, dbFileName);
140
139
  // It is possible that this will be the first time we need that directory
@@ -221,7 +220,7 @@ class MaskDb {
221
220
  process.stdout.isTTY
222
221
  ? JSON.stringify(row, null, 2).replace(/^/gm, " ")
223
222
  : JSON.stringify(row),
224
- idx < arr.length - 1 ? "," : ""
223
+ idx < arr.length - 1 ? "," : "",
225
224
  );
226
225
  });
227
226
  console.log(" ]\n}\n");
@@ -307,7 +306,7 @@ function printHelp(errMsg) {
307
306
  console.log("Actions available for maskValues:\n");
308
307
  console.log(
309
308
  " dumpTable:",
310
- "dumps the mask table for the specified property"
309
+ "dumps the mask table for the specified property",
311
310
  );
312
311
  console.log(" lookup:", "gets a value from mask");
313
312
  console.log(" set:", "sets a value to mask");
@@ -316,7 +315,7 @@ function printHelp(errMsg) {
316
315
  " --type (",
317
316
  Object.keys(maskTypes).join(" | "),
318
317
  ")\t[required]\n",
319
- " property[=value]\t[required]\n"
318
+ " property[=value]\t[required]\n",
320
319
  );
321
320
  if (errMsg) {
322
321
  console.error("\nERROR:", errMsg);
@@ -416,7 +415,7 @@ async function lookupMask(maskType, args) {
416
415
  // console.log(`We need to lookup ${testMask[1]} using keystore:`, keyCmd);
417
416
  try {
418
417
  keystoreResponse = await executeCommand(
419
- `${keyCmd[maskType]} ${testMask[1]}`
418
+ `${keyCmd[maskType]} ${testMask[1]}`,
420
419
  );
421
420
  const lookupCreds = JSON.parse(keystoreResponse);
422
421
  console.log("lookupObject:", lookupCreds);
@@ -426,7 +425,7 @@ async function lookupMask(maskType, args) {
426
425
  console.log("lookup:", keystoreResponse.trimEnd());
427
426
  } else {
428
427
  return printHelp(
429
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}`
428
+ `Could not retrieve data for ${testMask[1]} from keystore:\n${err}`,
430
429
  );
431
430
  }
432
431
  }
@@ -478,7 +477,7 @@ async function getMask(maskType, args) {
478
477
  unmaskedValue = keystoreResponse.trimEnd();
479
478
  } else {
480
479
  console.error(
481
- `Could not retrieve data for ${testMask[1]} from keystore:\n${err}\n`
480
+ `Could not retrieve data for ${testMask[1]} from keystore:\n${err}\n`,
482
481
  );
483
482
  }
484
483
  }
@@ -495,7 +494,7 @@ async function getMask(maskType, args) {
495
494
  const row = maskDb.db
496
495
  .prepare(
497
496
  // This only seems to get the first row, not all rows, so we get the longest name match
498
- `SELECT name FROM mask WHERE value = ? ORDER BY name DESC`
497
+ `SELECT name FROM mask WHERE value = ? ORDER BY name DESC`,
499
498
  )
500
499
  .get(testMask[1]);
501
500
 
@@ -543,7 +542,7 @@ async function setMask(maskType, args) {
543
542
  const insert = maskDb.db.prepare(
544
543
  `INSERT INTO mask(name, value) VALUES(?, ?)
545
544
  ON CONFLICT(name)
546
- DO UPDATE SET value=excluded.value;`
545
+ DO UPDATE SET value=excluded.value;`,
547
546
  );
548
547
 
549
548
  let maskValue = undefined;
@@ -684,4 +683,5 @@ maskValues.maskTypes = maskTypes;
684
683
  maskValues.maskObjValues = maskObjValues;
685
684
  maskValues.unmaskObjValues = unmaskObjValues;
686
685
 
687
- module.exports = maskValues;
686
+ export default maskValues;
687
+ export { maskTypes, printHelp, maskObjValues, unmaskObjValues };
@@ -1,4 +1,4 @@
1
- const { readFile } = require("fs/promises");
1
+ import { readFile } from "fs/promises";
2
2
 
3
3
  /**
4
4
  * @typedef {object} ResourceMetric
@@ -12,7 +12,7 @@ const { readFile } = require("fs/promises");
12
12
  * Logs a problem with a line to stderr (console.error).
13
13
  * In the message, it converts the index from the 0-based
14
14
  * array index to a 1-based line number.
15
- *
15
+ *
16
16
  * @param problem {string} The problem with the line to log
17
17
  * @param index {number} The array index for the line
18
18
  */
@@ -27,14 +27,17 @@ function warnLineProblem(problem, index) {
27
27
  * @returns {string[]} The lines of the file
28
28
  */
29
29
  function splitOnLines(fileContent) {
30
- return fileContent.replace(/[\r\n]/g, '\n').replace(/[\r]/g, '\n').split('\n');
30
+ return fileContent
31
+ .replace(/[\r\n]/g, "\n")
32
+ .replace(/[\r]/g, "\n")
33
+ .split("\n");
31
34
  }
32
35
 
33
36
  /**
34
37
  * Determines if a line is valid: that it has at least 4 data elements,
35
38
  * the first element is a date, the second and third elements are present,
36
39
  * and the fourth element is a number.
37
- *
40
+ *
38
41
  * @param lineContent {string} The line to consider
39
42
  * @param index {number} The line number in the file
40
43
  * @returns {boolean} Whether the line content contains at least 3 commas
@@ -51,12 +54,15 @@ function hasValidData(lineContent, index) {
51
54
  return false;
52
55
  }
53
56
 
54
- const [ timeCandidate, counterCandidate, unitCandidate, valueCandidate ] = lineContent.split(',');
57
+ const [timeCandidate, counterCandidate, unitCandidate, valueCandidate] =
58
+ lineContent.split(",");
55
59
 
56
- const isTimeValid = (new Date(timeCandidate.trim()).toString() !== "Invalid Date");
60
+ const isTimeValid =
61
+ new Date(timeCandidate.trim()).toString() !== "Invalid Date";
57
62
  const isCounterValid = counterCandidate.trim() !== "";
58
63
  const isUnitValid = unitCandidate.trim() !== "";
59
- const isValueValid = valueCandidate.trim() !== "" && !isNaN(valueCandidate.trim());
64
+ const isValueValid =
65
+ valueCandidate.trim() !== "" && !isNaN(valueCandidate.trim());
60
66
 
61
67
  if (!isTimeValid) {
62
68
  warnLineProblem("Invalid time", index);
@@ -93,7 +99,7 @@ function hasContent(lineContent) {
93
99
  * @returns {ResourceMetric} The parsed resource metric
94
100
  */
95
101
  function parseLine(lineContent) {
96
- const [ time, counter, unit, value ] = lineContent.split(',');
102
+ const [time, counter, unit, value] = lineContent.split(",");
97
103
 
98
104
  return {
99
105
  time: new Date(time.trim()),
@@ -105,25 +111,25 @@ function parseLine(lineContent) {
105
111
 
106
112
  /**
107
113
  * Parses metrics from a given path after validating the file exists.
108
- *
114
+ *
109
115
  * Makes strong assumptions about the file being UTF-8-encoded and
110
116
  * following a limited CSV format with no header row or support for
111
117
  * escaping data with commas. It does support surrounding whitespace.
112
- *
118
+ *
113
119
  * Each row contains exactly the data elements in order:
114
- *
120
+ *
115
121
  * Metric Date, Metric Name, Metric Unit, Metric Value
116
- *
122
+ *
117
123
  * Metric Date is a JavaScript-parsable date.
118
124
  * Metric Name is the name of the metric (such as CPU).
119
125
  * Metric Unit is the unit of the metric (such as Percent).
120
126
  * Metric Value is a number.
121
- *
127
+ *
122
128
  * Any row with fewer than 4 data elements is skipped.
123
129
  * Any row with more than 4 data elements ignores all elements beyond the fourth.
124
130
  * Any row with an unparsable date or a non-numeric value is skipped with a warning printed.
125
131
  * The first row is treated as a data row.
126
- *
132
+ *
127
133
  * @param file {string} The path to the file
128
134
  * @returns { Promise<ResourceMetric[] | undefined> } The parsed metrics if they were parsable
129
135
  */
@@ -137,17 +143,15 @@ async function parseMetrics(file) {
137
143
  }
138
144
 
139
145
  const fileContent = fileData.toString();
140
- const fileLines = splitOnLines(fileContent).
146
+ const fileLines = splitOnLines(fileContent)
141
147
  // filter valid data (also warns with the line number)
142
- filter(hasValidData).
148
+ .filter(hasValidData)
143
149
  // filter away the blank lines
144
- filter(hasContent).
150
+ .filter(hasContent)
145
151
  // parse valid lines into expected objects
146
- map(parseLine);
152
+ .map(parseLine);
147
153
 
148
154
  return fileLines;
149
155
  }
150
156
 
151
- module.exports = {
152
- parseMetrics,
153
- };
157
+ export { parseMetrics };
package/lib/pgpTools.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // Module for PGP tools
2
2
 
3
- const openpgp = require("openpgp");
4
- const fs = require("fs");
5
- const axios = require("axios");
3
+ import * as openpgp from "openpgp";
4
+ import fs from "fs";
5
+ import axios from "axios";
6
6
 
7
7
  // publicKey object is used to verify the signature
8
8
  let publicKey = undefined;
@@ -32,7 +32,7 @@ async function Verify(scriptDownloadInfo) {
32
32
  try {
33
33
  const response = await axios.get(
34
34
  "https://keys.openpgp.org/pks/lookup?op=get&options=mr&search=" +
35
- gpgSigner
35
+ gpgSigner,
36
36
  );
37
37
  publicKeyArmored = response?.data;
38
38
  } catch (error) {
@@ -43,7 +43,7 @@ async function Verify(scriptDownloadInfo) {
43
43
  if (!publicKeyArmored) {
44
44
  console.error(
45
45
  "Validation error retrieving public key for: %s",
46
- gpgSigner
46
+ gpgSigner,
47
47
  );
48
48
  return false;
49
49
  }
@@ -67,7 +67,7 @@ async function Verify(scriptDownloadInfo) {
67
67
  } catch (err) {
68
68
  console.error(
69
69
  "Validation error reading file signature:\n",
70
- scriptDownloadInfo?.gpgSignature
70
+ scriptDownloadInfo?.gpgSignature,
71
71
  );
72
72
  console.error("ERROR:", JSON.stringify(err, null, 2));
73
73
  return false;
@@ -89,7 +89,7 @@ async function Verify(scriptDownloadInfo) {
89
89
  }
90
90
  console.log(
91
91
  "Archive file digitally signed by:\n %s",
92
- publicKey?.users[0]?.userID?.userID || gpgSigner
92
+ publicKey?.users[0]?.userID?.userID || gpgSigner,
93
93
  );
94
94
  return true;
95
95
  } else {
@@ -98,6 +98,4 @@ async function Verify(scriptDownloadInfo) {
98
98
  }
99
99
  }
100
100
 
101
- module.exports = {
102
- Verify,
103
- };
101
+ export { Verify };
package/lib/utils.js CHANGED
@@ -7,19 +7,15 @@
7
7
  * @exports utils
8
8
  *
9
9
  */
10
- const crypto = require("crypto");
11
- const fs = require("fs");
12
- const path = require("path");
10
+ import crypto from "crypto";
11
+ import fs from "fs";
12
+ import path from "path";
13
13
 
14
- const {
15
- opscompassHome,
16
- decoder,
17
- cliCommand,
18
- } = require("../environment/current");
19
- const defaultsPath = path.join(opscompassHome, "defaults.json");
14
+ import { opscompassHome, decoder, cliCommand } from "../environment/current.js";
15
+ import { resourceTypes, encryptAttrs } from "./consts.js";
16
+ import findRemoveSync from "find-remove";
20
17
 
21
- const { resourceTypes, encryptAttrs } = require("./consts");
22
- const findRemoveSync = require("find-remove");
18
+ const defaultsPath = path.join(opscompassHome, "defaults.json");
23
19
 
24
20
  const HOBKEY = Buffer.from(`${decoder}=`, "base64").toString();
25
21
  const hashPrefix = "oc$hash:"; // Prefix for encrypted values
@@ -30,7 +26,7 @@ const obfuscatedRegex = /^oc\$(hash|mask)/; // Regex for encrypted or masked val
30
26
  function hasNullOrUndefined(obj, count = Object.keys(obj).length) {
31
27
  if (count !== Object.keys(obj).length) return false;
32
28
  return Object.values(obj).some(
33
- (value) => value === null || value === undefined
29
+ (value) => value === null || value === undefined,
34
30
  );
35
31
  }
36
32
 
@@ -118,7 +114,7 @@ function getConfigFilePath(args = []) {
118
114
  if (!fs.existsSync(defaultsPath)) {
119
115
  console.error(
120
116
  `\nWARNING: %s not found,\n to create it, run: \`${cliCommand} defaults ...\``,
121
- defaultsPath
117
+ defaultsPath,
122
118
  );
123
119
  }
124
120
 
@@ -143,7 +139,7 @@ function getConfigFilePath(args = []) {
143
139
  ) {
144
140
  explicitFilePath = path.join(
145
141
  explicitFilePath,
146
- `${global.monitoringConfig}-dgConfig.json`
142
+ `${global.monitoringConfig}-dgConfig.json`,
147
143
  );
148
144
  }
149
145
  }
@@ -162,7 +158,7 @@ function getConfigFilePath(args = []) {
162
158
  // If we have defaults and company is not set, flag an error
163
159
  if (!global.company) {
164
160
  console.error(
165
- "\nERROR: Company is not set. Please use --company <company-slug>."
161
+ "\nERROR: Company is not set. Please use --company <company-slug>.",
166
162
  );
167
163
  }
168
164
 
@@ -202,7 +198,7 @@ function getConfigFilePath(args = []) {
202
198
  cfgPath,
203
199
  global.company, // This is the company slug as opposed to name
204
200
  cfgFile.CUST_TOKEN,
205
- `${cfgFile.configurationId || 0}-${cfgName}`
201
+ `${cfgFile.configurationId || 0}-${cfgName}`,
206
202
  );
207
203
  } catch {
208
204
  return;
@@ -235,7 +231,7 @@ function getConfigFilePath(args = []) {
235
231
  fileObj = JSON.parse(fileData);
236
232
  } catch (error) {
237
233
  console.error(
238
- `Error reading file: ${cfgFile.filePath} - ${error.message}`
234
+ `Error reading file: ${cfgFile.filePath} - ${error.message}`,
239
235
  );
240
236
  }
241
237
  if (fileObj) {
@@ -281,7 +277,7 @@ async function readConfigFile(args) {
281
277
 
282
278
  decryptValues(cfgFile);
283
279
  // Also unmask the cfg file here - in case there are masked values
284
- const { unmaskObjValues } = require("./maskValues");
280
+ const { unmaskObjValues } = await import("./maskValues.js");
285
281
  await unmaskObjValues(cfgFile);
286
282
 
287
283
  return cfgFile;
@@ -727,4 +723,4 @@ const utilsModule = {
727
723
  sha256sum,
728
724
  };
729
725
 
730
- module.exports = { utilsModule };
726
+ export { utilsModule };
package/login.js CHANGED
@@ -1,14 +1,20 @@
1
- const crypto = require("crypto");
2
- const open = require("open");
3
- const http = require("http");
4
- const { storeCredentials } = require("./credentials");
5
- const { redeemDeviceCode, getDeviceCode, redeemAuthorizationCode, generateAuthorizeUrl } = require("./oauth");
1
+ import crypto from "crypto";
2
+ import open from "open";
3
+ import http from "http";
4
+ import { storeCredentials } from "./credentials.js";
5
+ import {
6
+ redeemDeviceCode,
7
+ getDeviceCode,
8
+ redeemAuthorizationCode,
9
+ generateAuthorizeUrl,
10
+ } from "./oauth.js";
6
11
 
7
12
  function base64UrlEncode(data) {
8
- return data.toString("base64")
9
- .replace(/\+/g, '-')
10
- .replace(/\//g, '_')
11
- .replace(/=/g, '')
13
+ return data
14
+ .toString("base64")
15
+ .replace(/\+/g, "-")
16
+ .replace(/\//g, "_")
17
+ .replace(/=/g, "");
12
18
  }
13
19
 
14
20
  function randomBytesBase64UrlEncoded(bytes) {
@@ -31,14 +37,21 @@ async function checkForToken(deviceCode, interval, timeToExpire) {
31
37
  console.log(e.data.error_description);
32
38
  break;
33
39
  case "expired_token":
34
- console.log("The device was not authorized in time. Run `opscompass login --use-device-code` again.");
40
+ console.log(
41
+ "The device was not authorized in time. Run `opscompass login --use-device-code` again.",
42
+ );
35
43
  break;
36
44
  case "authorization_pending":
37
45
  const newTimeToExpire = timeToExpire - interval;
38
46
  if (newTimeToExpire > 0) {
39
- setTimeout(() => checkForToken(deviceCode, interval, newTimeToExpire), interval * 1000);
47
+ setTimeout(
48
+ () => checkForToken(deviceCode, interval, newTimeToExpire),
49
+ interval * 1000,
50
+ );
40
51
  } else {
41
- console.log("The device was not authorized in time. Run `opscompass login --use-device-code` again.");
52
+ console.log(
53
+ "The device was not authorized in time. Run `opscompass login --use-device-code` again.",
54
+ );
42
55
  }
43
56
  break;
44
57
  }
@@ -51,18 +64,32 @@ async function deviceCodeFlow() {
51
64
 
52
65
  const deviceCodeData = deviceCodeResponse.data;
53
66
  if (deviceCodeData) {
54
- console.log("Log in to OpsCompass by loading the following URL into your external browser")
67
+ console.log(
68
+ "Log in to OpsCompass by loading the following URL into your external browser",
69
+ );
55
70
  console.log();
56
71
  console.log(deviceCodeData.verification_uri_complete);
57
72
  console.log();
58
- console.log("Need to type the URL manually? You can visit and provide the device code.");
73
+ console.log(
74
+ "Need to type the URL manually? You can visit and provide the device code.",
75
+ );
59
76
  console.log();
60
77
  console.log(deviceCodeData.verification_uri);
61
78
  console.log();
62
- console.log("Provide or verify this device code in the activation process:");
79
+ console.log(
80
+ "Provide or verify this device code in the activation process:",
81
+ );
63
82
  console.log();
64
83
  console.log(deviceCodeData.user_code);
65
- setTimeout(() => checkForToken(deviceCodeData.device_code, deviceCodeData.interval, deviceCodeData.expires_in - deviceCodeData.interval), deviceCodeData.interval * 1000);
84
+ setTimeout(
85
+ () =>
86
+ checkForToken(
87
+ deviceCodeData.device_code,
88
+ deviceCodeData.interval,
89
+ deviceCodeData.expires_in - deviceCodeData.interval,
90
+ ),
91
+ deviceCodeData.interval * 1000,
92
+ );
66
93
  }
67
94
  } catch (e) {
68
95
  console.error(e);
@@ -72,36 +99,55 @@ async function deviceCodeFlow() {
72
99
  async function printHelp() {
73
100
  console.log("Logging in to OpsCompass");
74
101
  console.log();
75
- console.log("By default, `opscompass login` will open the system's default browser to");
76
- console.log("complete the login process. You log in to OpsCompass in the browser with the");
77
- console.log("credentials you use to log into the OpsCompass portal. We use that identity to");
78
- console.log("access OpsCompass's APIs. You have access to the same data through the APIs");
102
+ console.log(
103
+ "By default, `opscompass login` will open the system's default browser to",
104
+ );
105
+ console.log(
106
+ "complete the login process. You log in to OpsCompass in the browser with the",
107
+ );
108
+ console.log(
109
+ "credentials you use to log into the OpsCompass portal. We use that identity to",
110
+ );
111
+ console.log(
112
+ "access OpsCompass's APIs. You have access to the same data through the APIs",
113
+ );
79
114
  console.log("that you do through the portal.");
80
115
  console.log();
81
- console.log("If this device does not have access to an interactive browser (for instance,");
82
- console.log("a Docker container or a \"headless\" virtual machine), you can run:");
116
+ console.log(
117
+ "If this device does not have access to an interactive browser (for instance,",
118
+ );
119
+ console.log(
120
+ 'a Docker container or a "headless" virtual machine), you can run:',
121
+ );
83
122
  console.log();
84
123
  console.log("opscompass login --use-device-code");
85
124
  console.log();
86
- console.log("It will print a URL and a code which you can use to authorize this device using");
87
- console.log("a browser on another device, such as a laptop or mobile device.");
125
+ console.log(
126
+ "It will print a URL and a code which you can use to authorize this device using",
127
+ );
128
+ console.log(
129
+ "a browser on another device, such as a laptop or mobile device.",
130
+ );
88
131
  }
89
132
 
90
133
  let loginModule = async (...args) => {
91
- if (args?.some(arg => "help" === arg.toLowerCase())) return printHelp();
92
- if (args?.some(arg => "--use-device-code" === arg.toLowerCase())) return deviceCodeFlow();
134
+ if (args?.some((arg) => "help" === arg.toLowerCase())) return printHelp();
135
+ if (args?.some((arg) => "--use-device-code" === arg.toLowerCase()))
136
+ return deviceCodeFlow();
93
137
 
94
138
  console.log("Launching the native browser.");
95
- console.log("If no browser is available or a browser can't be launched, cancel this command with ^C");
139
+ console.log(
140
+ "If no browser is available or a browser can't be launched, cancel this command with ^C",
141
+ );
96
142
  console.log("and run the command `opscompass login --use-device-code`.");
97
143
 
98
- // code_verifier: 32 bytes of CRNG data encoded in url-safe base64, without padding
144
+ // code_verifier: 32 bytes of CRNG data encoded in url-safe base64, without padding
99
145
  const code_verifier = randomBytesBase64UrlEncoded(32);
100
146
 
101
147
  // code_challenge: the sha256 hash of the code_verifier
102
- const code_challenge = base64UrlEncode(crypto.createHash('sha256')
103
- .update(code_verifier)
104
- .digest());
148
+ const code_challenge = base64UrlEncode(
149
+ crypto.createHash("sha256").update(code_verifier).digest(),
150
+ );
105
151
 
106
152
  // csrfState: 32 more CRNG bytes used to verify the tokens sent into the response url
107
153
  // actually are in response to this request
@@ -124,12 +170,16 @@ let loginModule = async (...args) => {
124
170
  await storeCredentials(authResult.data);
125
171
  console.log("You're logged into OpsCompass!");
126
172
  }
127
-
128
- res.writeHead(200, {"Content-Type": "text/html"});
129
- res.end("<html><head><title>Logging in...</title></head><body><h1>Logging in...</h1><p>The OpsCompass CLI should now be logged in.</p><p>You can close this window.</p></body></html>");
173
+
174
+ res.writeHead(200, { "Content-Type": "text/html" });
175
+ res.end(
176
+ "<html><head><title>Logging in...</title></head><body><h1>Logging in...</h1><p>The OpsCompass CLI should now be logged in.</p><p>You can close this window.</p></body></html>",
177
+ );
130
178
  } else {
131
- res.writeHead(200, {"Content-Type": "text/html"});
132
- res.end("<html><head><title>Problems...</title></head><body><h1>Problems logging in</h1><p>Please try running `opscompass login` again. If it doesn't work, try running `opscompass login --use-device-code` instead.</p></body></html>");
179
+ res.writeHead(200, { "Content-Type": "text/html" });
180
+ res.end(
181
+ "<html><head><title>Problems...</title></head><body><h1>Problems logging in</h1><p>Please try running `opscompass login` again. If it doesn't work, try running `opscompass login --use-device-code` instead.</p></body></html>",
182
+ );
133
183
  }
134
184
 
135
185
  // only allow one request...
@@ -137,11 +187,11 @@ let loginModule = async (...args) => {
137
187
  });
138
188
 
139
189
  server.listen(8400);
140
- } catch {
141
- }
190
+ } catch {}
142
191
  };
143
192
 
144
193
  loginModule.requiresLogin = false;
145
- loginModule.description = "Authorize the CLI using your OpsCompass credentials.";
194
+ loginModule.description =
195
+ "Authorize the CLI using your OpsCompass credentials.";
146
196
 
147
- module.exports = loginModule;
197
+ export default loginModule;
@@ -1,13 +1,12 @@
1
- const { getOpsCompassClient } = require("../opscompass.js");
1
+ import { getOpsCompassClient } from "../opscompass.js";
2
2
 
3
3
  async function listAccounts(args) {
4
-
5
4
  for (let i = 0; i < args.length - 1; i++) {
6
5
  switch (args[i].toLowerCase()) {
7
6
  case "--company":
8
7
  callParams.company = args[++i];
9
8
  break;
10
- }
9
+ }
11
10
  }
12
11
 
13
12
  const client = await getOpsCompassClient();
@@ -18,40 +17,47 @@ async function listAccounts(args) {
18
17
 
19
18
  async function listCompanies() {
20
19
  const client = await getOpsCompassClient();
21
- const company = await client.accounts.listCompanies();
20
+ const companyList = await client.accounts.listCompanies();
22
21
 
23
- console.log(JSON.stringify(company, null, 2));
22
+ console.log(JSON.stringify(companyList, null, 2));
24
23
  }
25
24
 
26
25
  async function printHelp() {
27
26
  console.log("Actions available for accounts:");
28
27
  console.log();
29
- console.log("list-companies", "Lists all of the companies associated with your user.");
28
+ console.log(
29
+ "list-companies",
30
+ "Lists all of the companies associated with your user.",
31
+ );
30
32
  console.log("Parameters:");
31
33
  console.log("None");
32
34
  console.log();
33
- console.log("list-accounts", "Lists all of the accounts associated with the given company.");
35
+ console.log(
36
+ "list-accounts",
37
+ "Lists all of the accounts associated with the given company.",
38
+ );
34
39
  console.log("Parameters:");
35
40
  console.log("--company [company_id]");
36
41
  console.log();
37
42
  }
38
43
 
39
- const accountsModule = (action, ...args) => {
40
- switch (action?.toLowerCase() ?? "") {
41
- case "list-companies":
42
- return listCompanies();
43
- case "list-accounts":
44
- return listAccounts(args);
45
- case "help":
46
- case "":
47
- return printHelp();
48
- default:
49
- console.log("Unknown command:", action);
50
- return printHelp();
51
- }
52
- };
53
-
54
- accountsModule.requiresLogin = true;
55
- accountsModule.description = "Provides access to details about Accounts in OpsCompass.";
56
-
57
- module.exports = accountsModule;
44
+ const accountsModule = (action, ...args) => {
45
+ switch (action?.toLowerCase() ?? "") {
46
+ case "list-companies":
47
+ return listCompanies();
48
+ case "list-accounts":
49
+ return listAccounts(args);
50
+ case "help":
51
+ case "":
52
+ return printHelp();
53
+ default:
54
+ console.log("Unknown command:", action);
55
+ return printHelp();
56
+ }
57
+ };
58
+
59
+ accountsModule.requiresLogin = true;
60
+ accountsModule.description =
61
+ "Provides access to details about Accounts in OpsCompass.";
62
+
63
+ export default accountsModule;