contensis-cli 1.0.0-beta.8 → 1.0.0-beta.81

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 (81) hide show
  1. package/README.md +1146 -78
  2. package/dist/commands/connect.js +3 -3
  3. package/dist/commands/connect.js.map +2 -2
  4. package/dist/commands/create.js +45 -10
  5. package/dist/commands/create.js.map +2 -2
  6. package/dist/commands/diff.js +57 -0
  7. package/dist/commands/diff.js.map +7 -0
  8. package/dist/commands/execute.js +103 -0
  9. package/dist/commands/execute.js.map +7 -0
  10. package/dist/commands/get.js +107 -18
  11. package/dist/commands/get.js.map +2 -2
  12. package/dist/commands/globalOptions.js +22 -17
  13. package/dist/commands/globalOptions.js.map +2 -2
  14. package/dist/commands/import.js +46 -11
  15. package/dist/commands/import.js.map +2 -2
  16. package/dist/commands/index.js +16 -2
  17. package/dist/commands/index.js.map +2 -2
  18. package/dist/commands/list.js +53 -10
  19. package/dist/commands/list.js.map +2 -2
  20. package/dist/commands/login.js +3 -3
  21. package/dist/commands/login.js.map +2 -2
  22. package/dist/commands/push.js +9 -5
  23. package/dist/commands/push.js.map +2 -2
  24. package/dist/commands/remove.js +51 -8
  25. package/dist/commands/remove.js.map +2 -2
  26. package/dist/commands/set.js +139 -12
  27. package/dist/commands/set.js.map +2 -2
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +2 -2
  30. package/dist/localisation/en-GB.js +193 -49
  31. package/dist/localisation/en-GB.js.map +2 -2
  32. package/dist/providers/CredentialProvider.js +36 -7
  33. package/dist/providers/CredentialProvider.js.map +3 -3
  34. package/dist/providers/SessionCacheProvider.js +21 -1
  35. package/dist/providers/SessionCacheProvider.js.map +2 -2
  36. package/dist/providers/file-provider.js +8 -4
  37. package/dist/providers/file-provider.js.map +3 -3
  38. package/dist/services/ContensisCliService.js +1092 -410
  39. package/dist/services/ContensisCliService.js.map +3 -3
  40. package/dist/shell.js +48 -14
  41. package/dist/shell.js.map +3 -3
  42. package/dist/util/console.printer.js +171 -55
  43. package/dist/util/console.printer.js.map +2 -2
  44. package/dist/util/diff.js +39 -0
  45. package/dist/util/diff.js.map +7 -0
  46. package/dist/util/index.js +8 -2
  47. package/dist/util/index.js.map +3 -3
  48. package/dist/util/logger.js +61 -29
  49. package/dist/util/logger.js.map +3 -3
  50. package/dist/util/timers.js +49 -0
  51. package/dist/util/timers.js.map +7 -0
  52. package/dist/version.js +1 -1
  53. package/dist/version.js.map +1 -1
  54. package/esbuild.config.js +3 -1
  55. package/package.json +2 -2
  56. package/src/commands/connect.ts +3 -2
  57. package/src/commands/create.ts +61 -8
  58. package/src/commands/diff.ts +41 -0
  59. package/src/commands/execute.ts +117 -0
  60. package/src/commands/get.ts +150 -14
  61. package/src/commands/globalOptions.ts +18 -17
  62. package/src/commands/import.ts +57 -7
  63. package/src/commands/index.ts +16 -1
  64. package/src/commands/list.ts +85 -11
  65. package/src/commands/login.ts +3 -2
  66. package/src/commands/push.ts +10 -3
  67. package/src/commands/remove.ts +66 -4
  68. package/src/commands/set.ts +189 -9
  69. package/src/index.ts +1 -4
  70. package/src/localisation/en-GB.ts +269 -66
  71. package/src/providers/CredentialProvider.ts +39 -6
  72. package/src/providers/SessionCacheProvider.ts +29 -2
  73. package/src/providers/file-provider.ts +12 -4
  74. package/src/services/ContensisCliService.ts +1384 -484
  75. package/src/shell.ts +52 -15
  76. package/src/util/console.printer.ts +240 -78
  77. package/src/util/diff.ts +17 -0
  78. package/src/util/index.ts +16 -7
  79. package/src/util/logger.ts +111 -31
  80. package/src/util/timers.ts +24 -0
  81. package/src/version.ts +1 -1
@@ -33,6 +33,7 @@ var import_path = __toESM(require("path"));
33
33
  var import_node_fetch = __toESM(require("node-fetch"));
34
34
  var import_inquirer = __toESM(require("inquirer"));
35
35
  var import_await_to_js = __toESM(require("await-to-js"));
36
+ var import_chalk = __toESM(require("chalk"));
36
37
  var import_util = require("../util");
37
38
  var import_SessionCacheProvider = __toESM(require("../providers/SessionCacheProvider"));
38
39
  var import_ContensisAuthService = __toESM(require("./ContensisAuthService"));
@@ -43,37 +44,57 @@ var import_migratortron = require("migratortron");
43
44
  var import_csv = require("../util/csv.formatter");
44
45
  var import_xml = require("../util/xml.formatter");
45
46
  var import_json = require("../util/json.formatter");
47
+ var import_diff = require("../util/diff");
48
+ var import_timers = require("../util/timers");
46
49
  var import_console = require("../util/console.printer");
47
50
  var import_file_provider = require("../providers/file-provider");
51
+ let insecurePasswordWarningShown = false;
48
52
  class ContensisCli {
49
53
  static quit = (error) => {
50
54
  process.removeAllListeners("exit");
51
55
  const exitCode = error ? 1 : 0;
52
- console.info(`
53
- Exiting contensis-cli with exit code: ${exitCode}
54
- `);
55
56
  process.exit(exitCode);
56
57
  };
57
- cache;
58
+ command;
59
+ format;
60
+ output;
61
+ session;
58
62
  contensis;
59
63
  contensisOpts;
60
- contentTypes;
61
- components;
62
- currentEnv;
63
64
  currentProject;
64
- env;
65
- sourceEnv;
65
+ sourceAlias;
66
66
  targetEnv;
67
67
  urls;
68
- command;
69
- format;
70
- output;
71
68
  log = import_logger.Logger;
72
69
  messages = import_en_GB.LogMessages;
73
- session;
74
70
  verb;
75
71
  noun;
76
72
  thirdArg;
73
+ get cache() {
74
+ return this.session.Get();
75
+ }
76
+ get currentEnv() {
77
+ return this.cache.currentEnvironment || "";
78
+ }
79
+ set currentEnv(currentEnvironment) {
80
+ this.session.Update({ currentEnvironment });
81
+ }
82
+ get env() {
83
+ const currentEnvironment = this.currentEnv;
84
+ const environments = this.cache.environments || {};
85
+ if (!currentEnvironment)
86
+ return {};
87
+ else if (!!environments[currentEnvironment])
88
+ return environments[currentEnvironment];
89
+ else {
90
+ return {
91
+ history: [],
92
+ lastUserId: "",
93
+ projects: [],
94
+ versionStatus: "latest"
95
+ };
96
+ }
97
+ }
77
98
  constructor(args, outputOpts, contensisOpts = {}) {
78
99
  const [exe, script, verb = "", noun = "", ...restArgs] = args;
79
100
  this.verb = verb == null ? void 0 : verb.toLowerCase();
@@ -81,24 +102,12 @@ Exiting contensis-cli with exit code: ${exitCode}
81
102
  this.thirdArg = restArgs == null ? void 0 : restArgs[0];
82
103
  const commandText = `${this.verb} ${this.noun} ${restArgs ? restArgs.join(" ") : ""}`.trim();
83
104
  this.session = new import_SessionCacheProvider.default();
84
- this.cache = this.session.Get();
85
105
  this.contensisOpts = contensisOpts;
86
106
  this.format = outputOpts == null ? void 0 : outputOpts.format;
87
107
  this.output = (outputOpts == null ? void 0 : outputOpts.output) && import_path.default.join(process.cwd(), outputOpts.output);
88
- const currentEnvironment = (outputOpts == null ? void 0 : outputOpts.alias) || this.cache.currentEnvironment || "";
108
+ const currentEnvironment = (outputOpts == null ? void 0 : outputOpts.alias) || this.currentEnv;
89
109
  const environments = this.cache.environments || {};
90
- if (!currentEnvironment)
91
- this.env = {};
92
- else if (!!environments[currentEnvironment])
93
- this.env = environments[currentEnvironment];
94
- else {
95
- this.env = {
96
- history: [],
97
- lastUserId: "",
98
- projects: [],
99
- versionStatus: "latest"
100
- };
101
- }
110
+ this.currentEnv = currentEnvironment;
102
111
  const env = this.env;
103
112
  if (outputOpts == null ? void 0 : outputOpts.projectId)
104
113
  env.currentProject = outputOpts.projectId;
@@ -110,9 +119,8 @@ Exiting contensis-cli with exit code: ${exitCode}
110
119
  env.lastUserId = outputOpts.clientId;
111
120
  if (outputOpts == null ? void 0 : outputOpts.sharedSecret)
112
121
  env.passwordFallback = outputOpts.sharedSecret;
113
- this.currentEnv = currentEnvironment;
114
122
  this.currentProject = (env == null ? void 0 : env.currentProject) || "null";
115
- this.sourceEnv = (outputOpts == null ? void 0 : outputOpts.sourceEnv) || currentEnvironment;
123
+ this.sourceAlias = (outputOpts == null ? void 0 : outputOpts.sourceAlias) || currentEnvironment;
116
124
  if (currentEnvironment) {
117
125
  this.urls = (0, import_util.url)(currentEnvironment, (env == null ? void 0 : env.currentProject) || "website");
118
126
  }
@@ -124,7 +132,7 @@ Exiting contensis-cli with exit code: ${exitCode}
124
132
  if (currentEnvironment) {
125
133
  env.history = [this.command];
126
134
  if (commandText) {
127
- environments[currentEnvironment] = this.env;
135
+ environments[currentEnvironment] = env;
128
136
  this.session.Update({
129
137
  currentEnvironment,
130
138
  environments,
@@ -149,34 +157,20 @@ Exiting contensis-cli with exit code: ${exitCode}
149
157
  };
150
158
  Connect = async (environment) => {
151
159
  var _a;
152
- const { cache, log, messages, session } = this;
160
+ const { log, messages, session } = this;
153
161
  if (environment) {
154
- const envCache = cache.environments[environment];
155
- if (!envCache)
156
- cache.environments[environment] = {
157
- versionStatus: "published",
158
- history: [],
159
- lastUserId: "",
160
- projects: [],
161
- ...!this.currentEnv ? this.env : {}
162
- };
163
- this.env = cache.environments[environment];
164
162
  this.currentEnv = environment;
165
163
  this.urls = (0, import_util.url)(environment, "website");
166
164
  const [fetchErr, response] = await (0, import_await_to_js.default)((0, import_node_fetch.default)(this.urls.cms));
167
165
  if (response && (response == null ? void 0 : response.status) < 400) {
168
166
  log.success(messages.connect.connected(environment));
167
+ session.UpdateEnv(this.env, environment);
169
168
  if ((_a = this.env) == null ? void 0 : _a.lastUserId) {
170
- await this.ConnectContensis();
171
169
  await this.PrintProjects();
172
170
  } else {
173
171
  log.warning(messages.projects.noList());
174
172
  log.help(messages.connect.tip());
175
173
  }
176
- session.Update({
177
- currentEnvironment: environment,
178
- environments: cache.environments
179
- });
180
174
  } else {
181
175
  log.error(
182
176
  messages.connect.unreachable(this.urls.cms, (response == null ? void 0 : response.status) || 0)
@@ -188,93 +182,80 @@ Exiting contensis-cli with exit code: ${exitCode}
188
182
  };
189
183
  ConnectContensis = async ({ commit = false } = {}) => {
190
184
  var _a, _b, _c;
191
- const { contensisOpts, currentEnv, env, log, messages } = this;
192
- const userId = env == null ? void 0 : env.lastUserId;
193
- const isGuidId = userId && (0, import_util.isUuid)(userId);
194
- if (currentEnv && userId) {
195
- const [credentialError, credentials] = await new import_CredentialProvider.default(
196
- {
185
+ if (!this.contensis) {
186
+ const { contensisOpts, currentEnv, env, log, messages } = this;
187
+ const userId = env == null ? void 0 : env.lastUserId;
188
+ const isGuidId = userId && (0, import_util.isUuid)(userId);
189
+ if (currentEnv && userId) {
190
+ const credentials = await this.GetCredentials(
197
191
  userId,
198
- alias: currentEnv
199
- },
200
- env.passwordFallback
201
- ).Init();
202
- if (credentialError && !credentials.current) {
203
- log.error(credentialError);
204
- return;
205
- }
206
- const cachedPassword = (_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.password;
207
- if (cachedPassword) {
208
- this.contensis = new import_migratortron.ContensisMigrationService(
209
- {
210
- ...contensisOpts,
211
- source: {
212
- url: ((_b = this.urls) == null ? void 0 : _b.cms) || "",
213
- username: !isGuidId ? userId : void 0,
214
- password: !isGuidId ? cachedPassword : void 0,
215
- clientId: isGuidId ? userId : void 0,
216
- sharedSecret: isGuidId ? cachedPassword : void 0,
217
- project: (env == null ? void 0 : env.currentProject) || "",
218
- assetHostname: (_c = this.urls) == null ? void 0 : _c.previewWeb
219
- },
220
- concurrency: typeof contensisOpts.concurrency !== "undefined" ? contensisOpts.concurrency : 3,
221
- outputProgress: true
222
- },
223
- !commit
192
+ env.passwordFallback
224
193
  );
194
+ const cachedPassword = (_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.password;
195
+ if (cachedPassword) {
196
+ this.contensis = new import_migratortron.ContensisMigrationService(
197
+ {
198
+ ...contensisOpts,
199
+ source: {
200
+ url: ((_b = this.urls) == null ? void 0 : _b.cms) || "",
201
+ username: !isGuidId ? userId : void 0,
202
+ password: !isGuidId ? cachedPassword : void 0,
203
+ clientId: isGuidId ? userId : void 0,
204
+ sharedSecret: isGuidId ? cachedPassword : void 0,
205
+ project: (env == null ? void 0 : env.currentProject) || "",
206
+ assetHostname: (_c = this.urls) == null ? void 0 : _c.previewWeb
207
+ },
208
+ concurrency: typeof contensisOpts.concurrency !== "undefined" ? contensisOpts.concurrency : 3,
209
+ outputProgress: true
210
+ },
211
+ !commit
212
+ );
213
+ }
214
+ } else {
215
+ if (!currentEnv)
216
+ log.help(messages.connect.help());
217
+ if (!userId)
218
+ log.help(messages.connect.tip());
225
219
  }
226
- } else {
227
- if (!currentEnv)
228
- log.help(messages.connect.help());
229
- if (!userId)
230
- log.help(messages.connect.tip());
231
220
  }
221
+ return this.contensis;
232
222
  };
233
223
  ConnectContensisImport = async ({
234
- commit,
235
- source,
236
- fileData,
237
- fileDataType
224
+ commit = false,
225
+ fromFile,
226
+ importDataType
238
227
  }) => {
239
228
  var _a, _b, _c, _d, _e, _f;
240
- const { contensisOpts, currentEnv, env, log, messages, sourceEnv } = this;
229
+ const source = fromFile ? "file" : "contensis";
230
+ const fileData = fromFile ? (0, import_file_provider.readJsonFile)(fromFile) || [] : [];
231
+ if (typeof fileData === "string")
232
+ throw new Error(`Import file format must be of type JSON`);
233
+ const { contensisOpts, currentEnv, env, log, messages, sourceAlias } = this;
241
234
  const environments = this.cache.environments || {};
242
- const sourceEnvironment = environments[sourceEnv || ""] || {};
235
+ const sourceEnvironment = environments[sourceAlias || ""] || {};
243
236
  const sourceCms = "source" in contensisOpts && contensisOpts.source || {};
244
237
  const sourceUserId = sourceCms.clientId || sourceCms.username || sourceEnvironment.lastUserId;
245
238
  const sourceProjectId = sourceCms.project || sourceEnvironment.currentProject || "website";
246
239
  const isSourceGuidId = sourceUserId && (0, import_util.isUuid)(sourceUserId);
247
- const sourceUrls = (0, import_util.url)(sourceEnv || "", sourceProjectId);
240
+ const sourceUrls = (0, import_util.url)(sourceAlias || "", sourceProjectId);
248
241
  const sourcePassword = sourceCms.sharedSecret || sourceCms.password || sourceEnvironment.passwordFallback;
249
242
  const targetUserId = env == null ? void 0 : env.lastUserId;
250
243
  const isTargetGuidId = targetUserId && (0, import_util.isUuid)(targetUserId);
251
244
  if (sourceUserId && currentEnv && targetUserId) {
252
- const [sourceCredentialError, sourceCredentials] = await new import_CredentialProvider.default(
253
- {
254
- userId: sourceUserId,
255
- alias: currentEnv
256
- },
257
- sourcePassword
258
- ).Init();
259
- if (sourceCredentialError && !sourceCredentials.current) {
260
- (0, import_logger.logError)(sourceCredentialError);
261
- return;
262
- }
245
+ const sourceCredentials = await this.GetCredentials(
246
+ sourceUserId,
247
+ sourcePassword,
248
+ sourceAlias,
249
+ false
250
+ );
263
251
  const cachedSourcePassword = (_a = sourceCredentials == null ? void 0 : sourceCredentials.current) == null ? void 0 : _a.password;
264
- const [targetCredentialError, targetCredentials] = await new import_CredentialProvider.default(
265
- {
266
- userId: targetUserId,
267
- alias: currentEnv
268
- },
252
+ const targetCredentials = await this.GetCredentials(
253
+ targetUserId,
269
254
  env.passwordFallback
270
- ).Init();
271
- if (targetCredentialError && !targetCredentials.current) {
272
- log.error(targetCredentialError);
273
- return;
274
- }
255
+ );
275
256
  const cachedTargetPassword = (_b = targetCredentials == null ? void 0 : targetCredentials.current) == null ? void 0 : _b.password;
276
257
  if (cachedSourcePassword && cachedTargetPassword) {
277
- if (source === "file" || source === "input") {
258
+ if (source === "file" || importDataType === "user-input") {
278
259
  this.contensis = new import_migratortron.ContensisMigrationService(
279
260
  {
280
261
  concurrency: 3,
@@ -289,12 +270,11 @@ Exiting contensis-cli with exit code: ${exitCode}
289
270
  targetProjects: [env.currentProject || ""],
290
271
  assetHostname: (_d = this.urls) == null ? void 0 : _d.previewWeb
291
272
  },
292
- ...fileDataType ? { [fileDataType]: fileData } : {}
273
+ ...importDataType ? { [importDataType]: fileData } : {}
293
274
  },
294
275
  !commit
295
276
  );
296
- }
297
- if (source === "contensis") {
277
+ } else if (source === "contensis") {
298
278
  this.contensis = new import_migratortron.ContensisMigrationService(
299
279
  {
300
280
  concurrency: 3,
@@ -329,82 +309,104 @@ Exiting contensis-cli with exit code: ${exitCode}
329
309
  if (!targetUserId)
330
310
  log.help(messages.connect.tip());
331
311
  }
312
+ return this.contensis;
313
+ };
314
+ GetCredentials = async (userId, password, currentEnv = this.currentEnv, saveCurrentEnv = true) => {
315
+ const { log, messages } = this;
316
+ if (userId) {
317
+ const [credentialError, credentials] = await new import_CredentialProvider.default(
318
+ { userId, alias: currentEnv },
319
+ password
320
+ ).Init();
321
+ if (credentialError && !credentials.current) {
322
+ log.error(credentialError);
323
+ return;
324
+ }
325
+ if (credentials.remarks.secure !== true) {
326
+ if (!insecurePasswordWarningShown) {
327
+ log.warning(messages.login.insecurePassword());
328
+ insecurePasswordWarningShown = true;
329
+ }
330
+ } else {
331
+ const env = this.cache.environments[currentEnv];
332
+ env.passwordFallback = void 0;
333
+ this.session.UpdateEnv(env, currentEnv, saveCurrentEnv);
334
+ }
335
+ return credentials;
336
+ }
332
337
  };
333
338
  Login = async (userId, {
334
339
  password = (0, import_util.isPassword)(this.env.passwordFallback),
335
340
  promptPassword = true,
336
341
  sharedSecret = (0, import_util.isSharedSecret)(this.env.passwordFallback),
337
- silent = false
338
- }) => {
342
+ silent = false,
343
+ attempt = 1
344
+ } = {}) => {
339
345
  var _a, _b, _c, _d;
340
- let inputPassword = password;
346
+ let inputPassword = password || sharedSecret;
341
347
  const { log, messages } = this;
342
348
  if (userId) {
343
- const { cache, currentEnv, env } = this;
349
+ const { currentEnv, env } = this;
344
350
  if (currentEnv) {
345
- const [credentialError, credentials] = await new import_CredentialProvider.default(
346
- { userId, alias: currentEnv },
347
- inputPassword || sharedSecret
348
- ).Init();
349
- if (credentialError && !credentials.current) {
350
- log.error(credentialError);
351
- return;
352
- }
353
- if (credentials.remarks.secure !== true)
354
- log.warning(messages.login.insecurePassword());
355
- const cachedPassword = (0, import_util.isPassword)((_a = credentials == null ? void 0 : credentials.current) == null ? void 0 : _a.password);
356
- const cachedSecret = (0, import_util.isSharedSecret)((_b = credentials == null ? void 0 : credentials.current) == null ? void 0 : _b.password);
357
- if (!sharedSecret && !inputPassword && !cachedPassword && !cachedSecret && promptPassword) {
358
- ({ inputPassword } = await import_inquirer.default.prompt([
359
- {
360
- type: "password",
361
- message: messages.login.passwordPrompt(currentEnv, userId),
362
- name: "inputPassword",
363
- mask: "*",
364
- prefix: void 0
365
- }
366
- ]));
367
- }
368
- if (sharedSecret || cachedSecret || inputPassword || cachedPassword) {
369
- const authService = new import_ContensisAuthService.default({
370
- username: userId,
371
- password: inputPassword || cachedPassword,
372
- projectId: (env == null ? void 0 : env.currentProject) || "website",
373
- rootUrl: ((_c = this.urls) == null ? void 0 : _c.cms) || "",
374
- clientId: userId,
375
- clientSecret: sharedSecret || cachedSecret
376
- });
377
- const [authError, bearerToken] = await (0, import_await_to_js.default)(authService.BearerToken());
378
- if (bearerToken) {
379
- env.authToken = bearerToken;
380
- env.lastUserId = userId;
381
- env.passwordFallback = credentials.remarks.secure !== true ? (_d = credentials.current) == null ? void 0 : _d.password : void 0;
382
- if (!silent) {
383
- import_logger.Logger.success(messages.login.success(currentEnv, userId));
384
- await this.PrintProjects();
385
- }
386
- if (inputPassword)
387
- await credentials.Save(inputPassword);
388
- if (sharedSecret)
389
- await credentials.Save(sharedSecret);
390
- } else if (authError) {
391
- import_logger.Logger.error(authError.toString());
392
- env.authToken = "";
393
- env.lastUserId = "";
394
- env.passwordFallback = void 0;
395
- if ((cachedPassword || cachedSecret) && credentials.remarks.secure) {
396
- await credentials.Delete();
397
- return await this.Login(userId, { password, sharedSecret });
398
- } else {
399
- throw new Error(messages.login.failed(currentEnv, userId));
351
+ const credentials = await this.GetCredentials(userId, inputPassword);
352
+ if (credentials) {
353
+ const cachedPassword = (0, import_util.isPassword)((_a = credentials.current) == null ? void 0 : _a.password);
354
+ const cachedSecret = (0, import_util.isSharedSecret)((_b = credentials.current) == null ? void 0 : _b.password);
355
+ if (!cachedPassword && !cachedSecret && promptPassword) {
356
+ ({ inputPassword } = await import_inquirer.default.prompt([
357
+ {
358
+ type: "password",
359
+ message: messages.login.passwordPrompt(currentEnv, userId),
360
+ name: "inputPassword",
361
+ mask: "*",
362
+ prefix: void 0
363
+ }
364
+ ]));
365
+ }
366
+ if (inputPassword || cachedPassword || cachedSecret) {
367
+ const authService = new import_ContensisAuthService.default({
368
+ username: userId,
369
+ password: inputPassword || cachedPassword,
370
+ projectId: (env == null ? void 0 : env.currentProject) || "website",
371
+ rootUrl: ((_c = this.urls) == null ? void 0 : _c.cms) || "",
372
+ clientId: userId,
373
+ clientSecret: sharedSecret || cachedSecret
374
+ });
375
+ const [authError, bearerToken] = await (0, import_await_to_js.default)(
376
+ authService.BearerToken()
377
+ );
378
+ if (bearerToken) {
379
+ env.authToken = bearerToken;
380
+ env.lastUserId = userId;
381
+ env.passwordFallback = credentials.remarks.secure !== true ? (_d = credentials.current) == null ? void 0 : _d.password : void 0;
382
+ this.session.UpdateEnv(env);
383
+ if (inputPassword)
384
+ await credentials.Save(inputPassword);
385
+ if (sharedSecret)
386
+ await credentials.Save(sharedSecret);
387
+ if (!silent) {
388
+ import_logger.Logger.success(messages.login.success(currentEnv, userId));
389
+ await this.PrintProjects();
390
+ }
391
+ } else if (authError) {
392
+ import_logger.Logger.error(authError.toString());
393
+ env.authToken = "";
394
+ env.lastUserId = "";
395
+ env.passwordFallback = void 0;
396
+ this.session.UpdateEnv(env);
397
+ if ((cachedPassword || cachedSecret) && credentials.remarks.secure) {
398
+ await credentials.Delete();
399
+ return await this.Login(userId, { password, sharedSecret });
400
+ } else {
401
+ throw new Error(messages.login.failed(currentEnv, userId));
402
+ }
400
403
  }
404
+ return env.authToken;
405
+ } else {
406
+ import_logger.Logger.error(messages.login.passwordPrompt());
407
+ if (attempt < 2)
408
+ return await this.Login(userId, { attempt: attempt + 1 });
401
409
  }
402
- this.session.Update({
403
- environments: cache.environments
404
- });
405
- return env.authToken;
406
- } else {
407
- import_logger.Logger.error(messages.login.passwordPrompt(currentEnv, userId));
408
410
  }
409
411
  } else {
410
412
  import_logger.Logger.error(messages.login.noEnv());
@@ -413,37 +415,100 @@ Exiting contensis-cli with exit code: ${exitCode}
413
415
  import_logger.Logger.error(messages.login.noUserId());
414
416
  }
415
417
  };
418
+ PrintContensisVersion = async () => {
419
+ const { log, messages } = this;
420
+ const contensis = await this.ConnectContensis();
421
+ if (contensis) {
422
+ const [projectsErr, projects] = await (0, import_await_to_js.default)(
423
+ contensis.projects.GetSourceProjects()
424
+ );
425
+ if (Array.isArray(projects)) {
426
+ this.HandleFormattingAndOutput(
427
+ contensis.contensisVersion,
428
+ () => log.raw(log.highlightText(contensis.contensisVersion))
429
+ );
430
+ }
431
+ if (projectsErr) {
432
+ log.error(messages.projects.noList());
433
+ log.error(projectsErr.message);
434
+ }
435
+ }
436
+ };
437
+ PrintBearerToken = async () => {
438
+ const { log, messages } = this;
439
+ const contensis = await this.ConnectContensis();
440
+ if (contensis) {
441
+ const [error, token] = await (0, import_await_to_js.default)(
442
+ contensis.content.sourceRepo.repo.BearerToken()
443
+ );
444
+ if (token) {
445
+ this.HandleFormattingAndOutput(
446
+ token,
447
+ () => log.raw(log.highlightText(token))
448
+ );
449
+ }
450
+ if (error) {
451
+ log.error(messages.projects.noList());
452
+ log.error(error.message);
453
+ }
454
+ }
455
+ };
416
456
  PrintProjects = async () => {
417
- const { cache, currentEnv, currentProject, log, messages, session } = this;
418
- if (!this.contensis)
419
- await this.ConnectContensis();
420
- if (this.contensis) {
457
+ const { currentProject, log, messages, session } = this;
458
+ const contensis = await this.ConnectContensis();
459
+ if (contensis) {
421
460
  const [projectsErr, projects] = await (0, import_await_to_js.default)(
422
- this.contensis.projects.GetSourceProjects()
461
+ contensis.projects.GetSourceProjects()
423
462
  );
424
463
  if (Array.isArray(projects)) {
425
- const currentVals = cache.environments[currentEnv] || {};
426
464
  const nextCurrentProject = currentProject && currentProject !== "null" ? currentProject : projects.some((p) => p.id === "website") ? "website" : void 0;
427
- cache.environments[currentEnv] = {
428
- ...currentVals,
465
+ session.UpdateEnv({
429
466
  projects: projects.map((p) => p.id),
430
467
  currentProject: nextCurrentProject
431
- };
468
+ });
432
469
  log.success(messages.projects.list());
470
+ log.raw("");
433
471
  this.HandleFormattingAndOutput(projects, () => {
434
- for (const project of projects) {
472
+ for (const project of projects.sort(
473
+ (a, b) => a.id.localeCompare(b.id)
474
+ )) {
475
+ let color;
476
+ try {
477
+ color = import_chalk.default.keyword(project.color);
478
+ } catch (ex) {
479
+ color = import_chalk.default.white;
480
+ }
435
481
  console.log(
436
- ` - ${nextCurrentProject === project.id ? "* " : ""}[${project.primaryLanguage}] ${project.id}`
482
+ `${nextCurrentProject === project.id ? `>> ${log.boldText(color(project.id))}` : ` ${color(project.id)}`} ${log.infoText(
483
+ `[${project.supportedLanguages.map(
484
+ (l) => l === project.primaryLanguage ? `*${log.boldText(l)}` : l
485
+ ).join(" ")}]`
486
+ )}`
437
487
  );
438
488
  }
439
489
  });
440
- session.Update({
441
- environments: cache.environments
442
- });
443
- if (nextCurrentProject) {
444
- this.env = cache.environments[currentEnv];
445
- this.SetProject(nextCurrentProject);
446
- }
490
+ if (!this.SetProject(nextCurrentProject))
491
+ log.warning(messages.projects.tip());
492
+ }
493
+ if (projectsErr) {
494
+ log.error(messages.projects.noList());
495
+ log.error(projectsErr.message);
496
+ }
497
+ }
498
+ };
499
+ PrintProject = async (projectId = this.currentProject) => {
500
+ const { log, messages, session } = this;
501
+ const contensis = await this.ConnectContensis();
502
+ if (contensis) {
503
+ const [projectsErr, projects] = await (0, import_await_to_js.default)(
504
+ contensis.projects.GetSourceProjects()
505
+ );
506
+ const foundProject = projects == null ? void 0 : projects.find(
507
+ (p) => p.id.toLowerCase() === projectId.toLowerCase()
508
+ );
509
+ if (foundProject) {
510
+ log.raw("");
511
+ this.HandleFormattingAndOutput(foundProject, log.object);
447
512
  }
448
513
  if (projectsErr) {
449
514
  log.error(messages.projects.noList());
@@ -451,8 +516,8 @@ Exiting contensis-cli with exit code: ${exitCode}
451
516
  }
452
517
  }
453
518
  };
454
- SetProject = async (projectId = "") => {
455
- const { cache, env, log, messages, session } = this;
519
+ SetProject = (projectId = "website") => {
520
+ const { env, log, messages, session } = this;
456
521
  let nextProjectId;
457
522
  if ((env == null ? void 0 : env.projects.length) > 0 && (env == null ? void 0 : env.lastUserId)) {
458
523
  nextProjectId = env.projects.find(
@@ -460,10 +525,9 @@ Exiting contensis-cli with exit code: ${exitCode}
460
525
  );
461
526
  if (nextProjectId) {
462
527
  env.currentProject = nextProjectId;
463
- session.Update({
464
- environments: cache.environments
465
- });
528
+ session.UpdateEnv(env);
466
529
  log.success(messages.projects.set(projectId));
530
+ log.raw("");
467
531
  } else {
468
532
  log.error(messages.projects.failedSet(projectId));
469
533
  }
@@ -473,8 +537,8 @@ Exiting contensis-cli with exit code: ${exitCode}
473
537
  }
474
538
  return nextProjectId;
475
539
  };
476
- SetVersion = async (versionStatus) => {
477
- const { cache, env, log, messages, session } = this;
540
+ SetVersion = (versionStatus) => {
541
+ const { env, log, messages, session } = this;
478
542
  if (!["latest", "published"].includes(versionStatus)) {
479
543
  log.error(messages.version.invalid(versionStatus));
480
544
  return false;
@@ -484,10 +548,7 @@ Exiting contensis-cli with exit code: ${exitCode}
484
548
  return false;
485
549
  }
486
550
  if ((env == null ? void 0 : env.projects.length) > 0 && (env == null ? void 0 : env.lastUserId)) {
487
- env.versionStatus = versionStatus;
488
- session.Update({
489
- environments: cache.environments
490
- });
551
+ session.UpdateEnv({ versionStatus });
491
552
  log.success(messages.version.set(this.currentEnv, versionStatus));
492
553
  return true;
493
554
  } else {
@@ -496,26 +557,11 @@ Exiting contensis-cli with exit code: ${exitCode}
496
557
  return false;
497
558
  }
498
559
  };
499
- HydrateContensis = async () => {
500
- const { log } = this;
501
- if (!this.contensis)
502
- await this.ConnectContensis();
503
- if (this.contensis) {
504
- const [contensisErr, models] = await (0, import_await_to_js.default)(
505
- this.contensis.models.HydrateContensisRepositories()
506
- );
507
- if (contensisErr) {
508
- log.error(contensisErr.message);
509
- return contensisErr;
510
- }
511
- }
512
- };
513
560
  PrintApiKeys = async () => {
514
561
  const { currentEnv, log, messages } = this;
515
- if (!this.contensis)
516
- await this.ConnectContensis();
517
- if (this.contensis) {
518
- const [keysErr, apiKeys] = await this.contensis.apiKeys.GetKeys();
562
+ const contensis = await this.ConnectContensis();
563
+ if (contensis) {
564
+ const [keysErr, apiKeys] = await contensis.apiKeys.GetKeys();
519
565
  if (Array.isArray(apiKeys)) {
520
566
  log.success(messages.keys.list(currentEnv));
521
567
  this.HandleFormattingAndOutput(apiKeys, () => {
@@ -543,22 +589,23 @@ Exiting contensis-cli with exit code: ${exitCode}
543
589
  };
544
590
  CreateApiKey = async (name, description) => {
545
591
  const { currentEnv, log, messages } = this;
546
- if (!this.contensis)
547
- await this.ConnectContensis();
548
- if (this.contensis) {
549
- const [err, key] = await this.contensis.apiKeys.CreateKey(
550
- name,
551
- description
552
- );
592
+ const contensis = await this.ConnectContensis();
593
+ if (contensis) {
594
+ const [err, key] = await contensis.apiKeys.CreateKey(name, description);
553
595
  if (key) {
554
596
  log.success(messages.keys.created(currentEnv, name));
555
597
  console.log(
556
- ` - ${key.name}${key.description ? ` (${key.description})` : ""} [${key.dateModified.toString().substring(0, 10)} ${key.modifiedBy}]`
598
+ ` - ${import_chalk.default.bold(key.name)} [${key.dateModified.toString().substring(0, 10)} ${key.modifiedBy}]`
599
+ );
600
+ if (key.description)
601
+ console.log(` ${log.infoText(key.description)}`);
602
+ console.log(` ${import_chalk.default.bold.grey`id`}: ${key.id}`);
603
+ console.log(
604
+ ` ${import_chalk.default.bold.grey`sharedSecret`}: ${key.sharedSecret}`
557
605
  );
558
- console.log(` - id: ${key.id}`);
559
- console.log(` - sharedSecret: ${key.sharedSecret}`);
606
+ console.log("");
607
+ log.help(messages.keys.tip());
560
608
  }
561
- console.log("");
562
609
  if (err) {
563
610
  log.error(messages.keys.failedCreate(currentEnv, name), err);
564
611
  }
@@ -566,10 +613,9 @@ Exiting contensis-cli with exit code: ${exitCode}
566
613
  };
567
614
  RemoveApiKey = async (id) => {
568
615
  const { currentEnv, log, messages } = this;
569
- if (!this.contensis)
570
- await this.ConnectContensis({ commit: true });
571
- if (this.contensis) {
572
- const [err, key] = await this.contensis.apiKeys.RemoveKey(id);
616
+ const contensis = await this.ConnectContensis({ commit: true });
617
+ if (contensis) {
618
+ const [err, key] = await contensis.apiKeys.RemoveKey(id);
573
619
  if (!err) {
574
620
  log.success(messages.keys.removed(currentEnv, id));
575
621
  console.log("");
@@ -578,25 +624,356 @@ Exiting contensis-cli with exit code: ${exitCode}
578
624
  }
579
625
  }
580
626
  };
581
- GetContentTypes = async () => {
627
+ PrintRoles = async () => {
628
+ const { currentEnv, log, messages } = this;
629
+ const contensis = await this.ConnectContensis();
630
+ if (contensis) {
631
+ const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
632
+ if (Array.isArray(roles)) {
633
+ log.success(messages.roles.list(currentEnv));
634
+ if (!roles.length)
635
+ log.help(messages.roles.noneExist());
636
+ this.HandleFormattingAndOutput(roles, () => {
637
+ var _a, _b, _c, _d, _e;
638
+ for (const {
639
+ id,
640
+ name,
641
+ description,
642
+ enabled,
643
+ assignments,
644
+ permissions
645
+ } of roles) {
646
+ const color = enabled ? (s) => s : log.infoText;
647
+ console.log(color(` - ${import_chalk.default.bold(name)} ${log.infoText(id)}`));
648
+ if (description)
649
+ console.log(log.infoText(` ${description}`));
650
+ if (enabled === false)
651
+ console.log(` ${import_chalk.default.bold.grey("enabled")}: false`);
652
+ if ((_a = assignments.groups) == null ? void 0 : _a.length)
653
+ console.log(
654
+ ` ${import_chalk.default.bold.grey("groups")}: ${assignments.groups.join(
655
+ ", "
656
+ )}`
657
+ );
658
+ if ((_b = assignments.users) == null ? void 0 : _b.length)
659
+ console.log(
660
+ ` ${import_chalk.default.bold.grey("users")}: ${assignments.users.join(
661
+ ", "
662
+ )}`
663
+ );
664
+ if ((_c = assignments.apiKeys) == null ? void 0 : _c.length)
665
+ console.log(
666
+ ` ${import_chalk.default.bold.grey("keys")}: ${assignments.apiKeys.join(
667
+ ", "
668
+ )}`
669
+ );
670
+ if ((_d = permissions.entries) == null ? void 0 : _d.length) {
671
+ console.log(` ${import_chalk.default.bold.grey("entries")}:`);
672
+ for (const p of permissions.entries)
673
+ console.log(
674
+ ` ${p.id}: ${log.infoText(
675
+ p.actions.length > 2 ? p.actions.length : p.actions.join(", ")
676
+ )}`
677
+ );
678
+ }
679
+ if ((_e = permissions.contentTypes) == null ? void 0 : _e.length)
680
+ console.log(
681
+ ` ${import_chalk.default.bold.grey(
682
+ "contentTypes"
683
+ )}: ${permissions.contentTypes.map(
684
+ (p) => `${p.id} [${p.actions.join(",")}] ${p.languages.join(
685
+ " "
686
+ )}`
687
+ ).join(", ")}`
688
+ );
689
+ }
690
+ });
691
+ }
692
+ if (rolesErr) {
693
+ log.error(messages.roles.noList(currentEnv));
694
+ log.error((0, import_json.jsonFormatter)(rolesErr));
695
+ }
696
+ }
697
+ };
698
+ PrintRole = async (roleNameOrId) => {
699
+ const { currentEnv, log, messages } = this;
700
+ const contensis = await this.ConnectContensis();
701
+ if (contensis) {
702
+ const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
703
+ if (Array.isArray(roles)) {
704
+ log.success(messages.roles.list(currentEnv));
705
+ const role = roles.find(
706
+ (r) => r.id === roleNameOrId || r.name.toLowerCase() === roleNameOrId.toLowerCase()
707
+ ) || roles.find(
708
+ (r) => r.name.toLowerCase().includes(roleNameOrId.toLowerCase())
709
+ );
710
+ if (role)
711
+ this.HandleFormattingAndOutput(role, log.object);
712
+ else
713
+ log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
714
+ }
715
+ if (rolesErr) {
716
+ log.error(messages.roles.noList(currentEnv));
717
+ log.error((0, import_json.jsonFormatter)(rolesErr));
718
+ }
719
+ }
720
+ };
721
+ CreateRole = async (role) => {
722
+ const { currentEnv, log, messages } = this;
723
+ const contensis = await this.ConnectContensis();
724
+ if (contensis) {
725
+ const [err, created] = await contensis.roles.CreateRole(role);
726
+ if (created) {
727
+ log.success(
728
+ messages.roles.created(currentEnv, role.id || role.name || "")
729
+ );
730
+ this.HandleFormattingAndOutput(created, log.object);
731
+ log.help(messages.roles.tip());
732
+ return role.id;
733
+ }
734
+ if (err) {
735
+ log.error(
736
+ messages.roles.failedCreate(currentEnv, role.id || role.name || ""),
737
+ err
738
+ );
739
+ }
740
+ }
741
+ };
742
+ UpdateRole = async (roleNameOrId, role) => {
743
+ const { currentEnv, log, messages } = this;
744
+ const contensis = await this.ConnectContensis();
745
+ if (contensis) {
746
+ const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
747
+ if (Array.isArray(roles)) {
748
+ log.success(messages.roles.list(currentEnv));
749
+ const existingRole = roles.find(
750
+ (r) => r.id === roleNameOrId || r.name.toLowerCase() === roleNameOrId.toLowerCase()
751
+ );
752
+ if (existingRole) {
753
+ log.info(messages.roles.setPayload());
754
+ log.object(role);
755
+ log.raw(``);
756
+ const [updateErr, updated] = await contensis.roles.UpdateRole(
757
+ existingRole.id,
758
+ role
759
+ );
760
+ if (updateErr)
761
+ log.error(messages.roles.failedSet(currentEnv, roleNameOrId));
762
+ else {
763
+ log.success(messages.roles.set());
764
+ this.HandleFormattingAndOutput(updated, log.object);
765
+ }
766
+ } else {
767
+ log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
768
+ }
769
+ }
770
+ if (rolesErr) {
771
+ log.error(messages.roles.noList(currentEnv));
772
+ log.error((0, import_json.jsonFormatter)(rolesErr));
773
+ }
774
+ }
775
+ };
776
+ RemoveRole = async (roleNameOrId) => {
777
+ const { currentEnv, log, messages } = this;
778
+ const contensis = await this.ConnectContensis();
779
+ if (contensis) {
780
+ const [rolesErr, roles] = await (0, import_await_to_js.default)(contensis.roles.GetRoles());
781
+ if (Array.isArray(roles)) {
782
+ log.success(messages.roles.list(currentEnv));
783
+ const existingRole = roles.find(
784
+ (r) => r.id === roleNameOrId || r.name.toLowerCase() === roleNameOrId.toLowerCase()
785
+ );
786
+ if (existingRole) {
787
+ const [deleteErr] = await contensis.roles.RemoveRole(existingRole.id);
788
+ if (deleteErr)
789
+ log.error(messages.roles.failedRemove(currentEnv, roleNameOrId));
790
+ else
791
+ log.success(messages.roles.removed(currentEnv, roleNameOrId));
792
+ } else {
793
+ log.error(messages.roles.failedGet(currentEnv, roleNameOrId));
794
+ }
795
+ }
796
+ if (rolesErr) {
797
+ log.error(messages.roles.noList(currentEnv));
798
+ log.error((0, import_json.jsonFormatter)(rolesErr));
799
+ }
800
+ }
801
+ };
802
+ CreateProject = async (project) => {
803
+ const { currentEnv, log, messages } = this;
804
+ const contensis = await this.ConnectContensis();
805
+ if (contensis) {
806
+ const [err, created] = await contensis.projects.CreateProject(project);
807
+ if (created) {
808
+ log.success(messages.projects.created(currentEnv, project.id));
809
+ this.HandleFormattingAndOutput(created, () => {
810
+ this.SetProject(project.id);
811
+ this.PrintProjects();
812
+ });
813
+ return project.id;
814
+ }
815
+ if (err) {
816
+ log.error(messages.projects.failedCreate(currentEnv, project.id), err);
817
+ }
818
+ }
819
+ };
820
+ UpdateProject = async (project) => {
821
+ const { currentEnv, currentProject, log, messages } = this;
822
+ const contensis = await this.ConnectContensis();
823
+ if (contensis) {
824
+ const [err, updated] = await contensis.projects.UpdateProject({
825
+ id: currentProject,
826
+ ...project
827
+ });
828
+ if (updated) {
829
+ log.success(messages.projects.updated(currentEnv, currentProject));
830
+ this.HandleFormattingAndOutput(updated, log.object);
831
+ return updated.id;
832
+ }
833
+ if (err) {
834
+ log.error(
835
+ messages.projects.failedUpdate(currentEnv, currentProject),
836
+ err
837
+ );
838
+ }
839
+ }
840
+ };
841
+ PrintContentModels = async (modelIds = []) => {
842
+ const { currentProject, log, messages } = this;
843
+ const contensis = await this.ConnectContensis();
844
+ if (contensis) {
845
+ const models = await contensis.models.contentModels();
846
+ const contentTypes = await contensis.models.contentTypes();
847
+ const components = await contensis.models.components();
848
+ const returnModels = (modelIds == null ? void 0 : modelIds.length) ? models == null ? void 0 : models.filter(
849
+ (m) => modelIds.some((id) => id.toLowerCase() === m.id.toLowerCase())
850
+ ) : void 0;
851
+ const contentTypeIds = Array.from(
852
+ /* @__PURE__ */ new Set([
853
+ ...(returnModels || models || []).map((m) => m.id),
854
+ ...(returnModels || models || []).map((m) => {
855
+ var _a, _b;
856
+ return ((_b = (_a = m.dependencies) == null ? void 0 : _a.contentTypes) == null ? void 0 : _b.map((c) => c[0])) || [];
857
+ }).flat()
858
+ ])
859
+ );
860
+ const componentIds = Array.from(
861
+ new Set(
862
+ (returnModels || models || []).map((m) => {
863
+ var _a, _b;
864
+ return ((_b = (_a = m.dependencies) == null ? void 0 : _a.components) == null ? void 0 : _b.map((c) => c[0])) || [];
865
+ }).flat()
866
+ )
867
+ );
868
+ const contentModelBackup = [
869
+ ...contentTypes.filter(
870
+ (c) => contentTypeIds.map((i) => i.toLowerCase()).includes(c.id.toLowerCase())
871
+ ),
872
+ ...components.filter(
873
+ (c) => componentIds.map((i) => i.toLowerCase()).includes(c.id.toLowerCase())
874
+ )
875
+ ];
876
+ if (Array.isArray(returnModels)) {
877
+ log.success(messages.models.list(currentProject));
878
+ this.HandleFormattingAndOutput(contentModelBackup, () => {
879
+ for (const model of returnModels) {
880
+ log.raw("");
881
+ log.object(model);
882
+ }
883
+ log.raw("");
884
+ });
885
+ } else {
886
+ log.success(
887
+ messages.models.get(currentProject, (models == null ? void 0 : models.length.toString()) || "0")
888
+ );
889
+ log.raw("");
890
+ if (models == null ? void 0 : models.length) {
891
+ this.HandleFormattingAndOutput(contentModelBackup, () => {
892
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
893
+ for (const model of models) {
894
+ const components2 = ((_a = model.components) == null ? void 0 : _a.length) || 0;
895
+ const contentTypes2 = ((_b = model.contentTypes) == null ? void 0 : _b.length) || 0;
896
+ const dependencies = (((_d = (_c = model.dependencies) == null ? void 0 : _c.components) == null ? void 0 : _d.length) || 0) + (((_f = (_e = model.dependencies) == null ? void 0 : _e.contentTypes) == null ? void 0 : _f.length) || 0);
897
+ const dependencyOf = (((_h = (_g = model.dependencyOf) == null ? void 0 : _g.components) == null ? void 0 : _h.length) || 0) + (((_j = (_i = model.dependencyOf) == null ? void 0 : _i.contentTypes) == null ? void 0 : _j.length) || 0);
898
+ const hasAny = components2 + contentTypes2 + dependencies + dependencyOf;
899
+ log.raw(
900
+ ` - ${log.highlightText(log.boldText(model.id))} ${hasAny ? log.infoText(
901
+ `{ ${components2 ? `components: ${components2}, ` : ""}${contentTypes2 ? `contentTypes: ${contentTypes2}, ` : ""}${dependencies ? `references: ${dependencies}, ` : ""}${dependencyOf ? `required by: ${dependencyOf}` : ""} }`
902
+ ) : ""}`
903
+ );
904
+ }
905
+ log.raw("");
906
+ });
907
+ }
908
+ }
909
+ }
910
+ };
911
+ ImportContentModels = async ({
912
+ commit,
913
+ fromFile
914
+ }) => {
582
915
  const { currentProject, log, messages } = this;
583
- let err;
584
- if (!this.contensis)
585
- err = await this.HydrateContensis();
586
- if (err)
587
- log.error(messages.contenttypes.noList(currentProject));
588
- if (this.contensis) {
589
- this.contentTypes = this.contensis.models.contentTypes();
590
- this.components = this.contensis.models.components();
916
+ const fileData = fromFile ? (0, import_file_provider.readJsonFile)(fromFile) || [] : [];
917
+ if (typeof fileData === "string")
918
+ throw new Error(`Import file format must be of type JSON`);
919
+ const contensis = await this.ConnectContensisImport({
920
+ commit,
921
+ fromFile,
922
+ importDataType: "models"
923
+ });
924
+ if (contensis) {
925
+ log.line();
926
+ if (contensis.isPreview) {
927
+ console.log(log.successText(` -- IMPORT PREVIEW -- `));
928
+ } else {
929
+ console.log(log.warningText(` *** COMMITTING IMPORT *** `));
930
+ }
931
+ const [migrateErr, result] = await contensis.MigrateContentModels();
932
+ if (migrateErr)
933
+ (0, import_logger.logError)(migrateErr);
934
+ else
935
+ this.HandleFormattingAndOutput(result, () => {
936
+ if (!commit) {
937
+ log.raw(log.boldText(`
938
+ Content types:`));
939
+ if (!result.contentTypes)
940
+ log.info(`- None returned
941
+ `);
942
+ else
943
+ (0, import_console.printModelMigrationAnalysis)(this, result.contentTypes);
944
+ log.raw(log.boldText(`
945
+ Components:`));
946
+ if (!result.components)
947
+ log.info(`- None returned
948
+ `);
949
+ else
950
+ (0, import_console.printModelMigrationAnalysis)(this, result.components);
951
+ } else {
952
+ const migrateResult = result;
953
+ log.raw(log.boldText(`
954
+ Content types:`));
955
+ (0, import_console.printModelMigrationResult)(
956
+ this,
957
+ migrateResult[currentProject].contentTypes
958
+ );
959
+ log.raw(log.boldText(`
960
+ Components:`));
961
+ (0, import_console.printModelMigrationResult)(
962
+ this,
963
+ migrateResult[currentProject].components
964
+ );
965
+ }
966
+ });
591
967
  } else {
592
- log.warning(messages.contenttypes.noList(currentProject));
968
+ log.warning(messages.models.noList(currentProject));
969
+ log.help(messages.connect.tip());
593
970
  }
594
971
  };
595
972
  PrintContentTypes = async () => {
596
973
  const { currentProject, log, messages } = this;
597
- await this.GetContentTypes();
598
- if (this.contensis) {
599
- const { contentTypes } = this;
974
+ const contensis = await this.ConnectContensis();
975
+ if (contensis) {
976
+ const contentTypes = await contensis.models.contentTypes();
600
977
  if (Array.isArray(contentTypes)) {
601
978
  log.success(messages.contenttypes.list(currentProject));
602
979
  this.HandleFormattingAndOutput(contentTypes, () => {
@@ -613,9 +990,9 @@ Exiting contensis-cli with exit code: ${exitCode}
613
990
  };
614
991
  PrintContentType = async (contentTypeId) => {
615
992
  const { currentProject, log, messages } = this;
616
- await this.GetContentTypes();
617
- if (this.contensis) {
618
- const { contentTypes } = this;
993
+ const contensis = await this.ConnectContensis();
994
+ if (contensis) {
995
+ const contentTypes = await contensis.models.contentTypes();
619
996
  if (Array.isArray(contentTypes)) {
620
997
  const contentType = contentTypes.find(
621
998
  (c) => c.id.toLowerCase() === contentTypeId.toLowerCase()
@@ -635,15 +1012,12 @@ Exiting contensis-cli with exit code: ${exitCode}
635
1012
  };
636
1013
  RemoveContentTypes = async (contentTypeIds, commit = false) => {
637
1014
  const { currentProject, log, messages } = this;
638
- if (!this.contensis)
639
- await this.ConnectContensisImport({
640
- source: "input",
641
- commit
642
- });
643
- if (this.contensis) {
644
- const [err, result] = await this.contensis.DeleteContentTypes(
645
- contentTypeIds
646
- );
1015
+ const contensis = await this.ConnectContensisImport({
1016
+ commit,
1017
+ importDataType: "user-input"
1018
+ });
1019
+ if (contensis) {
1020
+ const [err, result] = await contensis.DeleteContentTypes(contentTypeIds);
647
1021
  if (err) {
648
1022
  log.error(
649
1023
  messages.contenttypes.failedRemove(
@@ -657,7 +1031,7 @@ Exiting contensis-cli with exit code: ${exitCode}
657
1031
  messages.contenttypes.removed(
658
1032
  currentProject,
659
1033
  contentTypeIds.join('", "'),
660
- !this.contensis.isPreview
1034
+ !contensis.isPreview
661
1035
  )
662
1036
  );
663
1037
  this.HandleFormattingAndOutput(
@@ -677,15 +1051,15 @@ Exiting contensis-cli with exit code: ${exitCode}
677
1051
  throw new Error(`Import file format must be of type JSON`);
678
1052
  if (!Array.isArray(fileData))
679
1053
  fileData = [fileData];
680
- await this.ConnectContensisImport({
1054
+ const contensis = await this.ConnectContensisImport({
681
1055
  commit,
682
- source: fromFile ? "file" : "contensis"
1056
+ importDataType: fromFile ? "user-input" : void 0
683
1057
  });
684
- if (this.contensis) {
1058
+ if (contensis) {
685
1059
  for (const contentType of fileData) {
686
1060
  contentType.projectId = currentProject;
687
1061
  delete contentType.uuid;
688
- const [err, created, createStatus] = await this.contensis.models.targetRepos[currentProject].repo.UpsertContentType(false, contentType);
1062
+ const [err, created, createStatus] = await contensis.models.targetRepos[currentProject].repo.UpsertContentType(false, contentType);
689
1063
  if (err)
690
1064
  log.error(err.message, err);
691
1065
  if (createStatus) {
@@ -702,11 +1076,54 @@ Exiting contensis-cli with exit code: ${exitCode}
702
1076
  }
703
1077
  }
704
1078
  };
1079
+ DiffModels = async ({
1080
+ fromFile
1081
+ }, modelIds = []) => {
1082
+ const { log } = this;
1083
+ let fileData = fromFile ? (0, import_file_provider.readJsonFile)(fromFile) || [] : [];
1084
+ if (typeof fileData === "string")
1085
+ throw new Error(`Import file format must be of type JSON`);
1086
+ if (!Array.isArray(fileData))
1087
+ fileData = [fileData];
1088
+ const contensis = await this.ConnectContensisImport({
1089
+ fromFile,
1090
+ importDataType: "models"
1091
+ });
1092
+ if (contensis) {
1093
+ const [err, result] = await (0, import_await_to_js.default)(
1094
+ contensis.models.Diff(fileData.length ? fileData : modelIds)
1095
+ );
1096
+ if (err)
1097
+ log.error(err.message, err);
1098
+ if (result)
1099
+ this.HandleFormattingAndOutput(result, () => {
1100
+ var _a;
1101
+ log.success(
1102
+ `Queried models ${log.infoText(
1103
+ `"${(_a = result.query.modelIds) == null ? void 0 : _a.join(", ")}"`
1104
+ )}
1105
+ `
1106
+ );
1107
+ log.raw(log.boldText(`Content types:`));
1108
+ if (!result.contentTypes)
1109
+ log.info(`- None returned
1110
+ `);
1111
+ else
1112
+ (0, import_console.printModelMigrationAnalysis)(this, result.contentTypes);
1113
+ log.raw(log.boldText(`Components:`));
1114
+ if (!result.components)
1115
+ log.info(`- None returned
1116
+ `);
1117
+ else
1118
+ (0, import_console.printModelMigrationAnalysis)(this, result.components);
1119
+ });
1120
+ }
1121
+ };
705
1122
  PrintComponents = async () => {
706
1123
  const { currentProject, log, messages } = this;
707
- await this.GetContentTypes();
708
- if (this.contensis) {
709
- const { components } = this;
1124
+ const contensis = await this.ConnectContensis();
1125
+ if (contensis) {
1126
+ const components = await contensis.models.components();
710
1127
  if (Array.isArray(components)) {
711
1128
  log.success(messages.components.list(currentProject));
712
1129
  this.HandleFormattingAndOutput(components, () => {
@@ -723,9 +1140,9 @@ Exiting contensis-cli with exit code: ${exitCode}
723
1140
  };
724
1141
  PrintComponent = async (componentId) => {
725
1142
  const { currentProject, log, messages } = this;
726
- await this.GetContentTypes();
727
- if (this.contensis) {
728
- const { components } = this;
1143
+ const contensis = await this.ConnectContensis();
1144
+ if (contensis) {
1145
+ const components = await contensis.models.components();
729
1146
  if (Array.isArray(components)) {
730
1147
  const component = components.find(
731
1148
  (c) => c.id.toLowerCase() === componentId.toLowerCase()
@@ -741,13 +1158,12 @@ Exiting contensis-cli with exit code: ${exitCode}
741
1158
  };
742
1159
  RemoveComponents = async (componentIds, commit = false) => {
743
1160
  const { currentProject, log, messages } = this;
744
- if (!this.contensis)
745
- await this.ConnectContensisImport({
746
- source: "input",
747
- commit
748
- });
749
- if (this.contensis) {
750
- const [err, result] = await this.contensis.DeleteContentTypes(
1161
+ const contensis = await this.ConnectContensisImport({
1162
+ commit,
1163
+ importDataType: "user-input"
1164
+ });
1165
+ if (contensis) {
1166
+ const [err, result] = await contensis.DeleteContentTypes(
751
1167
  void 0,
752
1168
  componentIds
753
1169
  );
@@ -764,7 +1180,7 @@ Exiting contensis-cli with exit code: ${exitCode}
764
1180
  messages.components.removed(
765
1181
  currentProject,
766
1182
  componentIds.join('", "'),
767
- !this.contensis.isPreview
1183
+ !contensis.isPreview
768
1184
  )
769
1185
  );
770
1186
  this.HandleFormattingAndOutput(
@@ -784,15 +1200,15 @@ Exiting contensis-cli with exit code: ${exitCode}
784
1200
  throw new Error(`Import file format must be of type JSON`);
785
1201
  if (!Array.isArray(fileData))
786
1202
  fileData = [fileData];
787
- await this.ConnectContensisImport({
1203
+ const contensis = await this.ConnectContensisImport({
788
1204
  commit,
789
- source: fromFile ? "file" : "contensis"
1205
+ importDataType: fromFile ? "user-input" : void 0
790
1206
  });
791
- if (this.contensis) {
1207
+ if (contensis) {
792
1208
  for (const component of fileData) {
793
1209
  component.projectId = currentProject;
794
1210
  delete component.uuid;
795
- const [err, created, createStatus] = await this.contensis.models.targetRepos[currentProject].repo.UpsertComponent(false, component);
1211
+ const [err, created, createStatus] = await contensis.models.targetRepos[currentProject].repo.UpsertComponent(false, component);
796
1212
  if (err)
797
1213
  log.error(err.message, err);
798
1214
  if (createStatus) {
@@ -809,33 +1225,37 @@ Exiting contensis-cli with exit code: ${exitCode}
809
1225
  }
810
1226
  }
811
1227
  };
812
- RemoveEntry = async (id, commit = false) => {
813
- var _a, _b, _c;
814
- const { currentEnv, log, messages } = this;
815
- if (!this.contensis)
816
- await this.ConnectContensisImport({
817
- source: "input",
818
- commit
819
- });
820
- if (this.contensis) {
821
- if (this.contensis.isPreview) {
1228
+ RemoveEntries = async (commit = false) => {
1229
+ var _a;
1230
+ const { currentEnv, currentProject, log, messages } = this;
1231
+ const contensis = await this.ConnectContensisImport({
1232
+ commit,
1233
+ importDataType: "user-input"
1234
+ });
1235
+ if (contensis) {
1236
+ if (contensis.isPreview) {
822
1237
  console.log(log.successText(` -- PREVIEW -- `));
823
1238
  } else {
824
1239
  console.log(log.warningText(` *** COMMITTING DELETE *** `));
825
1240
  }
826
- const [err, result] = await this.contensis.DeleteEntries();
1241
+ const [err, result] = await contensis.DeleteEntries();
827
1242
  if (result)
828
1243
  this.HandleFormattingAndOutput(result, () => {
829
- (0, import_console.printMigrateResult)(this, result, { action: "delete" });
1244
+ (0, import_console.printMigrateResult)(this, result, {
1245
+ action: "delete",
1246
+ showAllEntries: true
1247
+ });
830
1248
  });
831
- if (!err && (!commit && ((_a = Object.values(result.entriesToMigrate)) == null ? void 0 : _a[0].totalCount) > 0 || commit && ((_b = result.migrateResult) == null ? void 0 : _b.deleted))) {
832
- log.success(messages.entries.removed(currentEnv, id, commit));
833
- if (!commit)
1249
+ if (!err && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && ((_a = result.migrateResult) == null ? void 0 : _a.deleted))) {
1250
+ log.success(messages.entries.removed(currentEnv, commit));
1251
+ if (!commit) {
1252
+ log.raw(``);
834
1253
  log.help(messages.entries.commitTip());
1254
+ }
835
1255
  } else {
836
- log.error(messages.entries.failedRemove(currentEnv, id), err);
837
- if (!((_c = Object.values(result.entriesToMigrate)) == null ? void 0 : _c[0].totalCount))
838
- log.help(messages.entries.notFound(id));
1256
+ log.error(messages.entries.failedRemove(currentEnv), err);
1257
+ if (!result.entriesToMigrate[currentProject].totalCount)
1258
+ log.help(messages.entries.notFound(currentEnv));
839
1259
  }
840
1260
  }
841
1261
  };
@@ -843,90 +1263,145 @@ Exiting contensis-cli with exit code: ${exitCode}
843
1263
  withDependents = false
844
1264
  }) => {
845
1265
  const { currentProject, log, messages } = this;
846
- await this.ConnectContensis();
847
- if (this.contensis) {
1266
+ const contensis = await this.ConnectContensis();
1267
+ if (contensis) {
848
1268
  log.line();
849
- const entries = await this.contensis.GetEntries({ withDependents });
1269
+ const entries = await contensis.GetEntries({ withDependents });
850
1270
  this.HandleFormattingAndOutput(
851
1271
  entries,
852
1272
  () => {
853
- var _a, _b;
1273
+ var _a;
854
1274
  return (0, import_migratortron.logEntriesTable)(
855
1275
  entries,
856
1276
  currentProject,
857
- (_b = (_a = this.contensis) == null ? void 0 : _a.payload.query) == null ? void 0 : _b.fields
1277
+ (_a = contensis.payload.query) == null ? void 0 : _a.fields
858
1278
  );
859
1279
  }
860
1280
  );
861
1281
  } else {
862
- log.warning(messages.contenttypes.noList(currentProject));
1282
+ log.warning(messages.models.noList(currentProject));
863
1283
  log.help(messages.connect.tip());
864
1284
  }
865
1285
  };
866
1286
  ImportEntries = async ({
867
1287
  commit,
868
- fromFile
1288
+ fromFile,
1289
+ logOutput
869
1290
  }) => {
870
- const { currentProject, log, messages } = this;
871
- const fileData = fromFile ? (0, import_file_provider.readJsonFile)(fromFile) || [] : [];
872
- if (typeof fileData === "string")
873
- throw new Error(`Import file format must be of type JSON`);
874
- await this.ConnectContensisImport({
1291
+ var _a, _b, _c, _d, _e;
1292
+ const { currentEnv, currentProject, log, messages } = this;
1293
+ const contensis = await this.ConnectContensisImport({
875
1294
  commit,
876
- source: fromFile ? "file" : "contensis",
877
- fileData,
878
- fileDataType: "entries"
1295
+ fromFile,
1296
+ importDataType: "entries"
879
1297
  });
880
- if (this.contensis) {
1298
+ if (contensis) {
881
1299
  log.line();
882
- if (this.contensis.isPreview) {
1300
+ if (contensis.isPreview) {
883
1301
  console.log(log.successText(` -- IMPORT PREVIEW -- `));
884
1302
  } else {
885
1303
  console.log(log.warningText(` *** COMMITTING IMPORT *** `));
886
1304
  }
887
- const [migrateErr, migrateResult] = await this.contensis.MigrateEntries();
888
- if (migrateErr)
889
- (0, import_logger.logError)(migrateErr);
1305
+ const [err, result] = await contensis.MigrateEntries();
1306
+ if (err)
1307
+ (0, import_logger.logError)(err);
890
1308
  else
891
- this.HandleFormattingAndOutput(migrateResult, () => {
892
- (0, import_console.printMigrateResult)(this, migrateResult);
1309
+ this.HandleFormattingAndOutput(result, () => {
1310
+ (0, import_console.printMigrateResult)(this, result, {
1311
+ showAllEntries: logOutput === "all",
1312
+ showChangedEntries: logOutput === "changes"
1313
+ });
893
1314
  });
1315
+ if (!err && !((_a = result.errors) == null ? void 0 : _a.length) && (!commit && result.entriesToMigrate[currentProject].totalCount || commit && (((_b = result.migrateResult) == null ? void 0 : _b.created) || ((_c = result.migrateResult) == null ? void 0 : _c.updated)))) {
1316
+ log.success(
1317
+ messages.entries.imported(
1318
+ currentEnv,
1319
+ commit,
1320
+ commit ? (((_d = result.migrateResult) == null ? void 0 : _d.created) || 0) + (((_e = result.migrateResult) == null ? void 0 : _e.updated) || 0) : result.entriesToMigrate[currentProject].totalCount
1321
+ )
1322
+ );
1323
+ if (!commit) {
1324
+ log.raw(``);
1325
+ log.help(messages.entries.commitTip());
1326
+ }
1327
+ } else {
1328
+ log.error(messages.entries.failedImport(currentEnv), err);
1329
+ if (!result.entriesToMigrate[currentProject].totalCount)
1330
+ log.help(messages.entries.notFound(currentEnv));
1331
+ }
894
1332
  } else {
895
- log.warning(messages.contenttypes.noList(currentProject));
1333
+ log.warning(messages.models.noList(currentProject));
896
1334
  log.help(messages.connect.tip());
897
1335
  }
898
1336
  };
899
- PrintWebhookSubscriptions = async (subscriptionIds, name) => {
1337
+ PrintWebhookSubscriptions = async (subscriptionIdsOrNames) => {
900
1338
  const { currentEnv, log, messages } = this;
901
- if (!this.contensis)
902
- await this.ConnectContensis();
903
- if (this.contensis) {
904
- const [webhooksErr, webhooks] = await this.contensis.subscriptions.webhooks.GetSubscriptions();
905
- const filteredResults = typeof name === "string" ? webhooks.filter(
906
- (w) => {
907
- var _a;
908
- return (_a = w.name) == null ? void 0 : _a.toLowerCase().includes(name.toLowerCase());
909
- }
910
- ) : Array.isArray(subscriptionIds) ? webhooks.filter((w) => subscriptionIds == null ? void 0 : subscriptionIds.some((id) => id === w.id)) : webhooks;
911
- if (Array.isArray(filteredResults)) {
912
- this.HandleFormattingAndOutput(filteredResults, () => {
913
- log.success(messages.webhooks.list(currentEnv));
914
- for (const {
915
- id,
916
- description,
917
- method,
918
- name: name2,
919
- version,
920
- url: url2
921
- } of filteredResults) {
922
- console.log(
923
- ` - ${name2}${description ? ` (${description})` : ""} [${version.modified.toString().substring(0, 10)} ${version.modifiedBy}]`
924
- );
925
- console.log(` ${id}`);
926
- console.log(` [${method}] ${url2}`);
1339
+ const contensis = await this.ConnectContensis();
1340
+ if (contensis) {
1341
+ const [webhooksErr, webhooks] = await contensis.subscriptions.webhooks.GetSubscriptions();
1342
+ const filteredResults = (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.length) ? webhooks == null ? void 0 : webhooks.filter(
1343
+ (w) => (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.some(
1344
+ (idname) => {
1345
+ var _a;
1346
+ return (_a = w.name) == null ? void 0 : _a.toLowerCase().includes(idname.toLowerCase());
927
1347
  }
928
- console.log("");
929
- });
1348
+ )) || (subscriptionIdsOrNames == null ? void 0 : subscriptionIdsOrNames.some(
1349
+ (id) => id.toLowerCase() === w.id.toLowerCase()
1350
+ ))
1351
+ ) : webhooks;
1352
+ if (Array.isArray(filteredResults)) {
1353
+ log.success(messages.webhooks.list(currentEnv));
1354
+ if (!(webhooks == null ? void 0 : webhooks.length))
1355
+ log.warning(messages.webhooks.noneExist());
1356
+ else {
1357
+ this.HandleFormattingAndOutput(filteredResults, () => {
1358
+ for (const {
1359
+ id,
1360
+ description,
1361
+ method,
1362
+ name,
1363
+ version,
1364
+ url: url2,
1365
+ enabled,
1366
+ topics,
1367
+ templates,
1368
+ headers
1369
+ } of filteredResults) {
1370
+ console.log(
1371
+ log.infoText(
1372
+ ` ${import_chalk.default.bold.white`- ${name}`} ${id} [${(version.modified || version.created).toString().substring(0, 10)} ${version.modifiedBy || version.createdBy}]`
1373
+ )
1374
+ );
1375
+ if (description)
1376
+ console.log(log.infoText` ${description}`);
1377
+ console.log(` ${log.infoText`[${method}]`} ${url2}`);
1378
+ if (headers && Object.keys(headers).length) {
1379
+ console.log(` ${log.infoText`headers`}:`);
1380
+ for (const [key, { value, secret }] of Object.entries(headers))
1381
+ console.log(
1382
+ ` ${import_chalk.default.bold.gray(key)}: ${secret ? "\u{1F910}" : value}`
1383
+ );
1384
+ }
1385
+ if (topics == null ? void 0 : topics.length)
1386
+ if ((topics == null ? void 0 : topics.length) === 1)
1387
+ console.log(
1388
+ ` ${log.infoText`topics`}: ${topics.map((t) => JSON.stringify(t)).join(" ").replaceAll('"', "").replaceAll(",", " ").replaceAll("{", "").replaceAll("}", "")}`
1389
+ );
1390
+ else {
1391
+ console.log(` ${log.infoText`topics`}:`);
1392
+ log.objectRecurse(topics, 1, " ");
1393
+ }
1394
+ if (templates && Object.keys(templates).length)
1395
+ console.log(
1396
+ ` ${log.infoText`templates`}: ${Object.keys(
1397
+ templates
1398
+ ).join(" ")}`
1399
+ );
1400
+ if (enabled === false)
1401
+ console.log(` ${log.infoText`enabled`}: ${enabled}`);
1402
+ }
1403
+ });
1404
+ }
930
1405
  }
931
1406
  if (webhooksErr) {
932
1407
  log.error(messages.webhooks.noList(currentEnv));
@@ -935,14 +1410,13 @@ Exiting contensis-cli with exit code: ${exitCode}
935
1410
  }
936
1411
  };
937
1412
  PrintBlocks = async () => {
938
- const { currentEnv, log, messages } = this;
939
- if (!this.contensis)
940
- await this.ConnectContensis();
941
- if (this.contensis) {
942
- const [err, blocks] = await this.contensis.blocks.GetBlocks();
1413
+ const { currentEnv, env, log, messages } = this;
1414
+ const contensis = await this.ConnectContensis();
1415
+ if (contensis) {
1416
+ const [err, blocks] = await contensis.blocks.GetBlocks();
943
1417
  if (Array.isArray(blocks)) {
944
1418
  this.HandleFormattingAndOutput(blocks, () => {
945
- log.success(messages.blocks.list(currentEnv));
1419
+ log.success(messages.blocks.list(currentEnv, env.currentProject));
946
1420
  for (const {
947
1421
  id,
948
1422
  description,
@@ -969,10 +1443,9 @@ Exiting contensis-cli with exit code: ${exitCode}
969
1443
  };
970
1444
  PrintBlockVersions = async (blockId, branch, version) => {
971
1445
  const { currentEnv, env, log, messages } = this;
972
- if (!this.contensis)
973
- await this.ConnectContensis();
974
- if (this.contensis) {
975
- const [err, blocks] = await this.contensis.blocks.GetBlockVersions(
1446
+ const contensis = await this.ConnectContensis();
1447
+ if (contensis) {
1448
+ const [err, blocks] = await contensis.blocks.GetBlockVersions(
976
1449
  blockId,
977
1450
  branch,
978
1451
  version
@@ -980,7 +1453,7 @@ Exiting contensis-cli with exit code: ${exitCode}
980
1453
  if (blocks) {
981
1454
  this.HandleFormattingAndOutput(blocks, () => {
982
1455
  log.success(
983
- messages.blocks.get(`${currentEnv}:${env.currentProject}`)
1456
+ messages.blocks.get(blockId, currentEnv, env.currentProject)
984
1457
  );
985
1458
  for (const block of blocks)
986
1459
  (0, import_console.printBlockVersion)(
@@ -1003,17 +1476,18 @@ Exiting contensis-cli with exit code: ${exitCode}
1003
1476
  };
1004
1477
  PushBlock = async (block) => {
1005
1478
  const { currentEnv, env, log, messages } = this;
1006
- messages.blocks.tryPush(
1007
- block.id,
1008
- block.source.branch,
1009
- currentEnv,
1010
- env.currentProject
1479
+ log.info(
1480
+ messages.blocks.tryPush(
1481
+ block.id,
1482
+ block.source.branch,
1483
+ currentEnv,
1484
+ env.currentProject
1485
+ )
1011
1486
  );
1012
1487
  console.log((0, import_json.jsonFormatter)(block));
1013
- if (!this.contensis)
1014
- await this.ConnectContensis();
1015
- if (this.contensis) {
1016
- const [err, blockVersion] = await this.contensis.blocks.PushBlockVersion(
1488
+ const contensis = await this.ConnectContensis();
1489
+ if (contensis) {
1490
+ const [err, blockVersion] = await contensis.blocks.PushBlockVersion(
1017
1491
  block
1018
1492
  );
1019
1493
  if (!err) {
@@ -1025,7 +1499,6 @@ Exiting contensis-cli with exit code: ${exitCode}
1025
1499
  env.currentProject
1026
1500
  )
1027
1501
  );
1028
- console.log((0, import_json.jsonFormatter)(blockVersion));
1029
1502
  }
1030
1503
  if (blockVersion) {
1031
1504
  this.HandleFormattingAndOutput(blockVersion, () => {
@@ -1036,66 +1509,275 @@ Exiting contensis-cli with exit code: ${exitCode}
1036
1509
  throw new Error(
1037
1510
  messages.blocks.failedPush(block.id, currentEnv, env.currentProject)
1038
1511
  );
1512
+ } else {
1513
+ throw new Error(
1514
+ messages.blocks.failedPush(block.id, currentEnv, env.currentProject)
1515
+ );
1039
1516
  }
1040
1517
  };
1041
- PrintBlockLogs = async (blockId, branch, version, dataCenter) => {
1042
- const { currentEnv, log, messages } = this;
1043
- if (!this.contensis)
1044
- await this.ConnectContensis();
1045
- if (this.contensis) {
1046
- const [err, blockLogs] = await this.contensis.blocks.GetBlockLogs({
1518
+ GetLatestBlockVersion = async (blockId, branch = "default") => {
1519
+ var _a;
1520
+ const { contensis, log, messages } = this;
1521
+ const [getErr, blockVersions] = await (contensis == null ? void 0 : contensis.blocks.GetBlockVersions(blockId, branch)) || [];
1522
+ if (getErr) {
1523
+ return [getErr, void 0];
1524
+ }
1525
+ let blockVersionNo = "latest";
1526
+ try {
1527
+ blockVersionNo = `${(_a = blockVersions == null ? void 0 : blockVersions[0]) == null ? void 0 : _a.version.versionNo}`;
1528
+ if (!Number.isNaN(blockVersionNo) && Number(blockVersionNo) > 0)
1529
+ return [null, blockVersionNo];
1530
+ else
1531
+ throw new Error(`'${blockVersionNo}' is not a valid version number`);
1532
+ } catch (parseVersionEx) {
1533
+ log.info(
1534
+ `Request for blockId: ${blockId}, branch: ${branch}, version: latest`
1535
+ );
1536
+ log.info(
1537
+ `Get block versions response was: ${(0, import_util.tryStringify)(blockVersions)}`
1538
+ );
1539
+ log.error(messages.blocks.failedParsingVersion());
1540
+ return [parseVersionEx, void 0];
1541
+ }
1542
+ };
1543
+ ExecuteBlockAction = async (action, blockId, version = "latest") => {
1544
+ const { currentEnv, env, log, messages } = this;
1545
+ const contensis = await this.ConnectContensis();
1546
+ if (contensis) {
1547
+ let actionOnBlockVersion = version;
1548
+ if (action === "release" && version === "latest") {
1549
+ const [getErr, blockVersion2] = await this.GetLatestBlockVersion(
1550
+ blockId
1551
+ );
1552
+ if (getErr) {
1553
+ throw new Error(
1554
+ `${messages.blocks.noList(
1555
+ currentEnv,
1556
+ env.currentProject
1557
+ )} (${getErr})`
1558
+ );
1559
+ } else if (blockVersion2) {
1560
+ actionOnBlockVersion = blockVersion2;
1561
+ }
1562
+ }
1563
+ const [err, blockVersion] = await contensis.blocks.BlockAction(
1564
+ blockId,
1565
+ action,
1566
+ actionOnBlockVersion
1567
+ );
1568
+ if (blockVersion) {
1569
+ this.HandleFormattingAndOutput(blockVersion, () => {
1570
+ log.success(
1571
+ messages.blocks.actionComplete(
1572
+ action,
1573
+ blockId,
1574
+ currentEnv,
1575
+ env.currentProject
1576
+ )
1577
+ );
1578
+ (0, import_console.printBlockVersion)(this, blockVersion);
1579
+ });
1580
+ }
1581
+ if (err) {
1582
+ log.error((0, import_json.jsonFormatter)(err));
1583
+ throw new Error(
1584
+ messages.blocks.actionFailed(
1585
+ action,
1586
+ blockId,
1587
+ currentEnv,
1588
+ env.currentProject
1589
+ )
1590
+ );
1591
+ }
1592
+ }
1593
+ };
1594
+ PrintBlockLogs = async (blockId, branch, version, dataCenter, follow = false) => {
1595
+ const { currentEnv, env, log, messages } = this;
1596
+ const contensis = await this.ConnectContensis();
1597
+ if (contensis) {
1598
+ log.success(
1599
+ messages.blocks.getLogs(blockId, branch, currentEnv, env.currentProject)
1600
+ );
1601
+ const [err, blockLogs] = await contensis.blocks.GetBlockLogs({
1047
1602
  blockId,
1048
1603
  branchId: branch,
1049
1604
  version,
1050
1605
  dataCenter
1051
1606
  });
1052
- if (blockLogs) {
1053
- this.HandleFormattingAndOutput(blockLogs, () => {
1054
- log.success(messages.blocks.list(currentEnv));
1607
+ if (err) {
1608
+ log.error(
1609
+ messages.blocks.failedGetLogs(blockId, currentEnv, env.currentProject)
1610
+ );
1611
+ log.error((0, import_json.jsonFormatter)(err));
1612
+ } else if (blockLogs) {
1613
+ const removeTrailingNewline = (logs) => logs.endsWith("\n") ? logs.slice(0, logs.length - 1) : logs;
1614
+ const renderLogs = removeTrailingNewline(blockLogs);
1615
+ this.HandleFormattingAndOutput(renderLogs, () => {
1055
1616
  console.log(
1056
- ` - ${blockId} ${branch} ${Number(version) ? `v${version}` : version} [${dataCenter}]`
1617
+ ` - ${blockId} ${branch} ${Number(version) ? `v${version}` : version} ${dataCenter ? `[${dataCenter}]` : ""}`
1057
1618
  );
1058
1619
  log.line();
1059
- console.log(log.infoText(blockLogs));
1060
- log.line();
1620
+ console.log(log.infoText(renderLogs));
1621
+ });
1622
+ let following = follow;
1623
+ let alreadyShown = blockLogs;
1624
+ let needsNewLine = false;
1625
+ let counter = 0;
1626
+ const listeners = process.listeners("SIGINT");
1627
+ process.removeAllListeners("SIGINT");
1628
+ process.on("SIGINT", () => {
1629
+ import_logger.Logger.warning(
1630
+ messages.blocks.stopFollow(blockId, currentEnv, env.currentProject)
1631
+ );
1632
+ stopFollowing();
1633
+ });
1634
+ let delay = (0, import_timers.promiseDelay)(5 * 1e3, null);
1635
+ const stopFollowing = () => {
1636
+ following = false;
1637
+ delay.cancel();
1638
+ process.removeAllListeners("SIGINT");
1639
+ for (const listener of listeners)
1640
+ process.addListener("SIGINT", listener);
1641
+ };
1642
+ while (following) {
1643
+ if (counter++ > 300) {
1644
+ import_logger.Logger.warning(
1645
+ messages.blocks.timeoutFollow(
1646
+ blockId,
1647
+ currentEnv,
1648
+ env.currentProject
1649
+ )
1650
+ );
1651
+ stopFollowing();
1652
+ }
1653
+ await delay.wait();
1654
+ const [lastErr, lastLogs] = following ? await contensis.blocks.GetBlockLogs({
1655
+ blockId,
1656
+ branchId: branch,
1657
+ version,
1658
+ dataCenter
1659
+ }) : [null, null];
1660
+ if (lastLogs) {
1661
+ const difference = (0, import_diff.diffLogStrings)(lastLogs, alreadyShown);
1662
+ if (difference) {
1663
+ if (needsNewLine) {
1664
+ console.log("");
1665
+ }
1666
+ const render = removeTrailingNewline(difference);
1667
+ console.log(log.infoText(render));
1668
+ alreadyShown += `${render}
1669
+ `;
1670
+ needsNewLine = false;
1671
+ } else {
1672
+ process.stdout.write(".");
1673
+ needsNewLine = true;
1674
+ }
1675
+ } else if (lastErr) {
1676
+ process.stdout.write("x");
1677
+ needsNewLine = true;
1678
+ }
1679
+ }
1680
+ }
1681
+ }
1682
+ };
1683
+ PrintProxies = async (proxyId) => {
1684
+ const { currentEnv, env, log, messages } = this;
1685
+ const contensis = await this.ConnectContensis();
1686
+ if (contensis) {
1687
+ const [err, proxies] = await contensis.proxies.GetProxies(proxyId);
1688
+ if (Array.isArray(proxies)) {
1689
+ this.HandleFormattingAndOutput(proxies, () => {
1690
+ log.success(messages.proxies.list(currentEnv, env.currentProject));
1691
+ for (const { id, name, description, endpoints, version } of proxies) {
1692
+ console.log(
1693
+ ` - ${name} [${version.versionNo}] ${id} ${log.infoText`${description}`}`
1694
+ );
1695
+ for (const [language, endpoint] of Object.entries(endpoints))
1696
+ console.log(
1697
+ ` - ${log.infoText`language: ${language}
1698
+ server: ${endpoint.server}
1699
+ headers.host: ${endpoint.headers.host}
1700
+ ssl: ${endpoint.ssl}`}`
1701
+ );
1702
+ }
1061
1703
  });
1062
1704
  }
1063
1705
  if (err) {
1064
- log.error(messages.blocks.noList(currentEnv));
1706
+ log.error(messages.proxies.noList(currentEnv, env.currentProject));
1707
+ log.error((0, import_json.jsonFormatter)(err));
1708
+ }
1709
+ }
1710
+ };
1711
+ PrintRenderers = async (rendererId) => {
1712
+ const { currentEnv, env, log, messages } = this;
1713
+ const contensis = await this.ConnectContensis();
1714
+ if (contensis) {
1715
+ const [err, renderers] = await contensis.renderers.GetRenderers(
1716
+ rendererId
1717
+ );
1718
+ if (Array.isArray(renderers)) {
1719
+ this.HandleFormattingAndOutput(renderers, () => {
1720
+ log.success(messages.renderers.list(currentEnv, env.currentProject));
1721
+ for (const {
1722
+ id,
1723
+ description,
1724
+ assignedContentTypes,
1725
+ rules,
1726
+ version
1727
+ } of renderers) {
1728
+ console.log(
1729
+ ` - ${id} [${version.versionNo}] ${log.infoText`${description}`}`
1730
+ );
1731
+ if (assignedContentTypes == null ? void 0 : assignedContentTypes.length)
1732
+ console.log(
1733
+ log.infoText` assignedContentTypes: ${assignedContentTypes.join(
1734
+ ", "
1735
+ )}`
1736
+ );
1737
+ for (const rule of rules)
1738
+ if (rule.return)
1739
+ console.log(
1740
+ log.infoText` ${rule.return.endpointId ? "endpointId" : "blockId"}: ${rule.return.endpointId || rule.return.blockId}`
1741
+ );
1742
+ }
1743
+ });
1744
+ }
1745
+ if (err) {
1746
+ log.error(messages.renderers.noList(currentEnv, env.currentProject));
1065
1747
  log.error((0, import_json.jsonFormatter)(err));
1066
1748
  }
1067
1749
  }
1068
1750
  };
1069
1751
  HandleFormattingAndOutput = (obj, logFn) => {
1070
1752
  const { format, log, messages, output } = this;
1753
+ if (!format) {
1754
+ logFn(obj);
1755
+ } else if (format === "csv") {
1756
+ log.raw("");
1757
+ log.raw(log.infoText((0, import_csv.csvFormatter)(obj)));
1758
+ } else if (format === "xml") {
1759
+ log.raw("");
1760
+ log.raw(log.infoText((0, import_xml.xmlFormatter)(obj)));
1761
+ } else if (format === "json") {
1762
+ log.raw("");
1763
+ log.raw(log.infoText((0, import_json.jsonFormatter)(obj)));
1764
+ }
1765
+ log.raw("");
1071
1766
  if (output) {
1072
1767
  let writeString = "";
1768
+ const isText = !(0, import_util.tryParse)(obj) && typeof obj === "string";
1073
1769
  if (format === "csv") {
1074
1770
  writeString = (0, import_csv.csvFormatter)(obj);
1075
1771
  } else if (format === "xml") {
1076
1772
  writeString = (0, import_xml.xmlFormatter)(obj);
1077
1773
  } else
1078
- writeString = (0, import_json.jsonFormatter)(obj);
1774
+ writeString = isText ? obj : (0, import_json.jsonFormatter)(obj);
1079
1775
  if (writeString) {
1080
1776
  import_fs.default.writeFileSync(output, writeString);
1081
- log.success(messages.app.fileOutput(format, output));
1777
+ log.success(messages.app.fileOutput(isText ? "text" : format, output));
1082
1778
  } else {
1083
1779
  log.info(messages.app.noFileOutput());
1084
1780
  }
1085
- } else {
1086
- if (!format) {
1087
- logFn(obj);
1088
- } else if (format === "csv") {
1089
- log.raw("");
1090
- log.raw(log.infoText((0, import_csv.csvFormatter)(obj)));
1091
- } else if (format === "xml") {
1092
- log.raw("");
1093
- log.raw(log.infoText((0, import_xml.xmlFormatter)(obj)));
1094
- } else if (format === "json") {
1095
- log.raw("");
1096
- log.raw(log.infoText((0, import_json.jsonFormatter)(obj)));
1097
- }
1098
- log.raw("");
1099
1781
  }
1100
1782
  };
1101
1783
  }