@dynamicweb/cli 1.1.1 → 2.0.0-beta.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.
@@ -1,10 +1,10 @@
1
1
  import fetch from 'node-fetch';
2
2
  import path from 'path';
3
3
  import fs from 'fs';
4
- import { setupEnv, getAgent } from './env.js';
4
+ import { setupEnv, getAgent, createCommandError } from './env.js';
5
5
  import { setupUser } from './login.js';
6
6
 
7
- const exclude = ['_', '$0', 'command', 'list', 'json', 'verbose', 'v', 'host', 'protocol', 'apiKey', 'env', 'output']
7
+ const exclude = ['_', '$0', 'command', 'list', 'json', 'verbose', 'v', 'host', 'protocol', 'apiKey', 'env', 'output', 'auth', 'clientId', 'clientSecret', 'clientIdEnv', 'clientSecretEnv', 'oauth']
8
8
 
9
9
  export function commandCommand() {
10
10
  return {
@@ -33,18 +33,18 @@ export function commandCommand() {
33
33
  try {
34
34
  output.verboseLog(`Running command ${argv.command}`);
35
35
  await handleCommand(argv, output);
36
- output.finish();
37
36
  } catch (err) {
38
37
  output.fail(err);
38
+ process.exitCode = 1;
39
+ } finally {
39
40
  output.finish();
40
- process.exit(1);
41
41
  }
42
42
  }
43
43
  }
44
44
  }
45
45
 
46
46
  async function handleCommand(argv, output) {
47
- let env = await setupEnv(argv);
47
+ let env = await setupEnv(argv, output);
48
48
  let user = await setupUser(argv, env);
49
49
  if (argv.list) {
50
50
  const properties = await getProperties(env, user, argv.command);
@@ -58,18 +58,7 @@ async function handleCommand(argv, output) {
58
58
  }
59
59
 
60
60
  async function getProperties(env, user, command) {
61
- return `This option currently doesn't work`
62
- let res = await fetch(`${env.protocol}://${env.host}/Admin/Api/CommandByName?name=${command}`, {
63
- method: 'GET',
64
- headers: {
65
- 'Authorization': `Bearer ${user.apiKey}`
66
- },
67
- agent: getAgent(env.protocol)
68
- })
69
- if (res.ok) {
70
- let body = await res.json()
71
- return body.model.propertyNames
72
- }
61
+ throw createCommandError('The --list option is not currently implemented for commands.');
73
62
  }
74
63
 
75
64
  function getQueryParams(argv) {
@@ -148,12 +137,6 @@ function createCommandOutput(argv) {
148
137
  };
149
138
  }
150
139
 
151
- function createCommandError(message, status, details = null) {
152
- const error = new Error(message);
153
- error.status = status;
154
- error.details = details;
155
- return error;
156
- }
157
140
 
158
141
  async function parseJsonSafe(res) {
159
142
  try {
@@ -41,12 +41,27 @@ export function envCommand() {
41
41
  type: 'boolean',
42
42
  description: 'List all users in environment, uses positional [env] if used, otherwise current env'
43
43
  })
44
+ .option('output', {
45
+ choices: ['json'],
46
+ describe: 'Outputs a single JSON response for automation-friendly parsing'
47
+ })
44
48
  },
45
- handler: (argv) => handleEnv(argv)
49
+ handler: async (argv) => {
50
+ const output = createEnvOutput(argv);
51
+
52
+ try {
53
+ await handleEnv(argv, output);
54
+ } catch (err) {
55
+ output.fail(err);
56
+ process.exitCode = 1;
57
+ } finally {
58
+ output.finish();
59
+ }
60
+ }
46
61
  }
47
62
  }
48
63
 
49
- export async function setupEnv(argv) {
64
+ export async function setupEnv(argv, output = null) {
50
65
  let env = {};
51
66
  let askEnv = true;
52
67
 
@@ -62,13 +77,17 @@ export async function setupEnv(argv) {
62
77
 
63
78
  if (askEnv && getConfig().env) {
64
79
  env = getConfig().env[argv.env] || getConfig().env[getConfig()?.current?.env];
65
- if (!env.protocol) {
66
- console.log('Protocol for environment not set, defaulting to https');
80
+ if (env && !env.protocol) {
81
+ logMessage(argv, 'Protocol for environment not set, defaulting to https');
67
82
  env.protocol = 'https';
68
83
  }
69
84
  }
70
85
  else if (askEnv) {
71
- console.log('Current environment not set, please set it')
86
+ if (isJsonOutput(argv)) {
87
+ throw createCommandError('Current environment not set, please set it');
88
+ }
89
+
90
+ logMessage(argv, 'Current environment not set, please set it');
72
91
  await interactiveEnv(argv, {
73
92
  environment: {
74
93
  type: 'input'
@@ -76,20 +95,35 @@ export async function setupEnv(argv) {
76
95
  interactive: {
77
96
  default: true
78
97
  }
79
- })
98
+ }, output)
80
99
  env = getConfig().env[getConfig()?.current?.env];
81
100
  }
101
+
102
+ if (!env || Object.keys(env).length === 0) {
103
+ throw createCommandError('Unable to resolve the current environment.');
104
+ }
105
+
82
106
  return env;
83
107
  }
84
108
 
85
- async function handleEnv(argv) {
109
+ async function handleEnv(argv, output) {
86
110
  if (argv.users) {
87
- let env = argv.env || getConfig().current.env;
88
- console.log(`Users in environment ${env}: ${Object.keys(getConfig().env[env].users || {})}`);
111
+ const cfg = getConfig();
112
+ let env = argv.env || cfg.current?.env;
113
+ const envConfig = cfg.env?.[env];
114
+ if (!envConfig) {
115
+ throw createCommandError(`Environment '${env}' does not exist`, 404);
116
+ }
117
+ const users = Object.keys(envConfig.users || {});
118
+ output.addData({ environment: env, users });
119
+ output.log(`Users in environment ${env}: ${users}`);
89
120
  } else if (argv.env) {
90
- changeEnv(argv)
121
+ const result = await changeEnv(argv, output);
122
+ output.addData(result);
91
123
  } else if (argv.list) {
92
- console.log(`Existing environments: ${Object.keys(getConfig().env || {})}`)
124
+ const environments = Object.keys(getConfig().env || {});
125
+ output.addData({ environments });
126
+ output.log(`Existing environments: ${environments}`);
93
127
  } else {
94
128
  await interactiveEnv(argv, {
95
129
  environment: {
@@ -102,12 +136,12 @@ async function handleEnv(argv) {
102
136
  interactive: {
103
137
  default: true
104
138
  }
105
- })
139
+ }, output)
106
140
  }
107
141
  }
108
142
 
109
- export async function interactiveEnv(argv, options) {
110
- if (argv.verbose) console.info('Setting up new environment')
143
+ export async function interactiveEnv(argv, options, output) {
144
+ verboseLog(argv, 'Setting up new environment');
111
145
  const result = {};
112
146
  for (const [key, config] of Object.entries(options)) {
113
147
  if (key === 'interactive') continue;
@@ -122,8 +156,7 @@ export async function interactiveEnv(argv, options) {
122
156
  }
123
157
  getConfig().env = getConfig().env || {};
124
158
  if (!result.environment || !result.environment.trim()) {
125
- console.log('Environment name cannot be empty');
126
- return;
159
+ throw createCommandError('Environment name cannot be empty');
127
160
  }
128
161
  getConfig().env[result.environment] = getConfig().env[result.environment] || {};
129
162
  if (result.host) {
@@ -135,8 +168,7 @@ export async function interactiveEnv(argv, options) {
135
168
  getConfig().env[result.environment].protocol = hostSplit[0];
136
169
  getConfig().env[result.environment].host = hostSplit[1];
137
170
  } else {
138
- console.log(`Issues resolving host ${result.host}`);
139
- return;
171
+ throw createCommandError(`Issues resolving host ${result.host}`);
140
172
  }
141
173
  }
142
174
  if (result.environment) {
@@ -144,14 +176,34 @@ export async function interactiveEnv(argv, options) {
144
176
  getConfig().current.env = result.environment;
145
177
  }
146
178
  updateConfig();
147
- console.log(`Your current environment is now ${getConfig().current.env}`);
148
- console.log(`To change the host of your environment, use the command 'dw env'`)
179
+ logMessage(argv, `Your current environment is now ${getConfig().current.env}`);
180
+ logMessage(argv, `To change the host of your environment, use the command 'dw env'`);
181
+
182
+ const currentEnv = getConfig().env[result.environment];
183
+ const data = {
184
+ environment: result.environment,
185
+ protocol: currentEnv.protocol,
186
+ host: currentEnv.host || null,
187
+ current: getConfig().current.env
188
+ };
189
+
190
+ if (output) {
191
+ output.addData(data);
192
+ }
193
+
194
+ return data;
149
195
  }
150
196
 
151
- async function changeEnv(argv) {
152
- if (!Object.keys(getConfig().env).includes(argv.env)) {
153
- console.log(`The specified environment ${argv.env} doesn't exist, please create it`);
154
- await interactiveEnv(argv, {
197
+ async function changeEnv(argv, output) {
198
+ const environments = getConfig().env || {};
199
+
200
+ if (!Object.keys(environments).includes(argv.env)) {
201
+ if (isJsonOutput(argv)) {
202
+ throw createCommandError(`The specified environment ${argv.env} doesn't exist, please create it`, 404);
203
+ }
204
+
205
+ logMessage(argv, `The specified environment ${argv.env} doesn't exist, please create it`);
206
+ return await interactiveEnv(argv, {
155
207
  environment: {
156
208
  type: 'input',
157
209
  default: argv.env,
@@ -165,10 +217,75 @@ async function changeEnv(argv) {
165
217
  interactive: {
166
218
  default: true
167
219
  }
168
- })
220
+ }, output)
169
221
  } else {
170
222
  getConfig().current.env = argv.env;
171
223
  updateConfig();
172
- console.log(`Your current environment is now ${getConfig().current.env}`);
224
+ const data = {
225
+ environment: argv.env,
226
+ current: getConfig().current.env
227
+ };
228
+ logMessage(argv, `Your current environment is now ${getConfig().current.env}`);
229
+ return data;
230
+ }
231
+ }
232
+
233
+ export function isJsonOutput(argv) {
234
+ return argv?.output === 'json';
235
+ }
236
+
237
+ export function createCommandError(message, status = 1, details = null) {
238
+ const error = new Error(message);
239
+ error.status = status;
240
+ error.details = details;
241
+ return error;
242
+ }
243
+
244
+ function logMessage(argv, ...args) {
245
+ if (!isJsonOutput(argv)) {
246
+ console.log(...args);
173
247
  }
174
248
  }
249
+
250
+ function verboseLog(argv, ...args) {
251
+ if (argv?.verbose && !isJsonOutput(argv)) {
252
+ console.info(...args);
253
+ }
254
+ }
255
+
256
+ function createEnvOutput(argv) {
257
+ const response = {
258
+ ok: true,
259
+ command: 'env',
260
+ operation: argv.users ? 'users' : argv.list ? 'list' : argv.env ? 'select' : 'setup',
261
+ status: 200,
262
+ data: [],
263
+ errors: [],
264
+ meta: {}
265
+ };
266
+
267
+ return {
268
+ json: isJsonOutput(argv),
269
+ addData(entry) {
270
+ response.data.push(entry);
271
+ },
272
+ log(...args) {
273
+ if (!this.json) {
274
+ console.log(...args);
275
+ }
276
+ },
277
+ fail(err) {
278
+ response.ok = false;
279
+ response.status = err?.status || 1;
280
+ response.errors.push({
281
+ message: err?.message || 'Unknown env command error.',
282
+ details: err?.details ?? null
283
+ });
284
+ },
285
+ finish() {
286
+ if (this.json) {
287
+ console.log(JSON.stringify(response, null, 2));
288
+ }
289
+ }
290
+ };
291
+ }