@contentstack/cli-utilities 2.0.0-beta.3 → 2.0.0-beta.5

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.
@@ -23,7 +23,10 @@ declare class AuthHandler {
23
23
  private allAuthConfigItems;
24
24
  private oauthHandler;
25
25
  private managementAPIClient;
26
+ /** True while an OAuth access-token refresh is running (for logging/diagnostics; correctness uses `oauthRefreshInFlight`). */
26
27
  private isRefreshingToken;
28
+ /** Serialize OAuth refresh so concurrent API calls await the same refresh instead of proceeding with a stale token. */
29
+ private oauthRefreshInFlight;
27
30
  private cmaHost;
28
31
  set host(contentStackHost: any);
29
32
  constructor();
@@ -45,8 +48,8 @@ declare class AuthHandler {
45
48
  getAuthorisationType(): Promise<any>;
46
49
  isAuthorisationTypeBasic(): Promise<boolean>;
47
50
  isAuthorisationTypeOAuth(): Promise<boolean>;
48
- checkExpiryAndRefresh: (force?: boolean) => Promise<void | object>;
49
- compareOAuthExpiry(force?: boolean): Promise<void | object>;
51
+ checkExpiryAndRefresh: (force?: boolean) => Promise<void>;
52
+ compareOAuthExpiry(force?: boolean): Promise<void>;
50
53
  restoreOAuthConfig(): void;
51
54
  }
52
55
  declare const _default: AuthHandler;
@@ -22,7 +22,10 @@ class AuthHandler {
22
22
  this.cmaHost = this.getCmaHost();
23
23
  }
24
24
  constructor() {
25
+ /** True while an OAuth access-token refresh is running (for logging/diagnostics; correctness uses `oauthRefreshInFlight`). */
25
26
  this.isRefreshingToken = false; // Flag to track if a refresh operation is in progress
27
+ /** Serialize OAuth refresh so concurrent API calls await the same refresh instead of proceeding with a stale token. */
28
+ this.oauthRefreshInFlight = null;
26
29
  this.checkExpiryAndRefresh = (force = false) => this.compareOAuthExpiry(force);
27
30
  this.OAuthAppId = process.env.OAUTH_APP_ID || '6400aa06db64de001a31c8a9';
28
31
  this.OAuthClientId = process.env.OAUTH_CLIENT_ID || 'Ie0FEfTzlfAHL4xM';
@@ -329,44 +332,41 @@ class AuthHandler {
329
332
  return config_handler_1.default.get(this.authorisationTypeKeyName) === this.authorisationTypeOAUTHValue ? true : false;
330
333
  }
331
334
  async compareOAuthExpiry(force = false) {
332
- // Avoid recursive refresh operations
333
- if (this.isRefreshingToken) {
334
- cli_ux_1.default.print('Refresh operation already in progress');
335
- return Promise.resolve();
336
- }
337
335
  const oauthDateTime = config_handler_1.default.get(this.oauthDateTimeKeyName);
338
336
  const authorisationType = config_handler_1.default.get(this.authorisationTypeKeyName);
339
337
  if (oauthDateTime && authorisationType === this.authorisationTypeOAUTHValue) {
340
338
  const now = new Date();
341
339
  const oauthDate = new Date(oauthDateTime);
342
- const oauthValidUpto = new Date();
343
- oauthValidUpto.setTime(oauthDate.getTime() + 59 * 60 * 1000);
344
- if (force) {
345
- cli_ux_1.default.print('Forcing token refresh...');
346
- return this.refreshToken();
340
+ const oauthValidUpto = new Date(oauthDate.getTime() + 59 * 60 * 1000);
341
+ const tokenExpired = oauthValidUpto <= now;
342
+ const shouldRefresh = force || tokenExpired;
343
+ if (!shouldRefresh) {
344
+ return Promise.resolve();
347
345
  }
348
- else {
349
- if (oauthValidUpto > now) {
350
- return Promise.resolve();
351
- }
352
- else {
353
- cli_ux_1.default.print('Token expired, refreshing the token');
354
- // Set the flag before refreshing the token
355
- this.isRefreshingToken = true;
356
- try {
357
- await this.refreshToken();
358
- }
359
- catch (error) {
360
- cli_ux_1.default.error('Error refreshing token');
361
- throw error;
346
+ if (this.oauthRefreshInFlight) {
347
+ return this.oauthRefreshInFlight;
348
+ }
349
+ this.isRefreshingToken = true;
350
+ this.oauthRefreshInFlight = (async () => {
351
+ try {
352
+ if (force) {
353
+ cli_ux_1.default.print('Forcing token refresh...');
362
354
  }
363
- finally {
364
- // Reset the flag after refresh operation is completed
365
- this.isRefreshingToken = false;
355
+ else {
356
+ cli_ux_1.default.print('Token expired, refreshing the token');
366
357
  }
367
- return Promise.resolve();
358
+ await this.refreshToken();
368
359
  }
369
- }
360
+ catch (error) {
361
+ cli_ux_1.default.error('Error refreshing token');
362
+ throw error;
363
+ }
364
+ finally {
365
+ this.isRefreshingToken = false;
366
+ this.oauthRefreshInFlight = null;
367
+ }
368
+ })();
369
+ return this.oauthRefreshInFlight;
370
370
  }
371
371
  else {
372
372
  cli_ux_1.default.print('No OAuth configuration set.');
package/lib/chalk.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export type ChalkInstance = typeof import('chalk').default;
2
+ /**
3
+ * Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage.
4
+ */
5
+ export declare function loadChalk(): Promise<ChalkInstance>;
6
+ /**
7
+ * Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook).
8
+ */
9
+ export declare function getChalk(): ChalkInstance;
package/lib/chalk.js ADDED
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loadChalk = loadChalk;
37
+ exports.getChalk = getChalk;
38
+ /**
39
+ * Chalk 5 is ESM-only. We load it via dynamic import and cache for use in CommonJS.
40
+ */
41
+ let chalkInstance = null;
42
+ /**
43
+ * Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage.
44
+ */
45
+ async function loadChalk() {
46
+ if (!chalkInstance) {
47
+ const chalkModule = await Promise.resolve().then(() => __importStar(require('chalk')));
48
+ chalkInstance = chalkModule.default;
49
+ }
50
+ return chalkInstance;
51
+ }
52
+ /**
53
+ * Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook).
54
+ */
55
+ function getChalk() {
56
+ if (!chalkInstance) {
57
+ throw new Error('Chalk not loaded. Ensure loadChalk() is called during init (e.g. in utils-init hook).');
58
+ }
59
+ return chalkInstance;
60
+ }
package/lib/cli-ux.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Command = exports.Args = exports.Flags = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
5
+ const chalk_1 = require("./chalk");
6
6
  const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
7
7
  const core_1 = require("@oclif/core");
8
8
  Object.defineProperty(exports, "Args", { enumerable: true, get: function () { return core_1.Args; } });
@@ -27,7 +27,8 @@ class CLIInterface {
27
27
  }
28
28
  print(message, opts) {
29
29
  if (opts) {
30
- let chalkFn = chalk_1.default;
30
+ const chalk = (0, chalk_1.getChalk)();
31
+ let chalkFn = chalk;
31
32
  if (opts.color)
32
33
  chalkFn = chalkFn[opts.color];
33
34
  if (opts.bold)
@@ -38,10 +39,10 @@ class CLIInterface {
38
39
  core_1.ux.stdout(message_handler_1.default.parse(message));
39
40
  }
40
41
  success(message) {
41
- core_1.ux.stdout(chalk_1.default.green(message_handler_1.default.parse(message)));
42
+ core_1.ux.stdout((0, chalk_1.getChalk)().green(message_handler_1.default.parse(message)));
42
43
  }
43
44
  error(message, ...params) {
44
- core_1.ux.stdout(chalk_1.default.red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
45
+ core_1.ux.stdout((0, chalk_1.getChalk)().red(message_handler_1.default.parse(message) + (params && params.length > 0 ? ': ' : '')), ...params);
45
46
  }
46
47
  loader(message = '') {
47
48
  if (!this.loading) {
@@ -5,7 +5,7 @@ const conf_1 = tslib_1.__importDefault(require("conf"));
5
5
  const has_1 = tslib_1.__importDefault(require("lodash/has"));
6
6
  const uuid_1 = require("uuid");
7
7
  const fs_1 = require("fs");
8
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
8
+ const chalk_1 = require("./chalk");
9
9
  const _1 = require(".");
10
10
  const ENC_KEY = process.env.ENC_KEY || 'encryptionKey';
11
11
  const ENCRYPT_CONF = (0, has_1.default)(process.env, 'ENCRYPT_CONF') ? process.env.ENCRYPT_CONF === 'true' : true;
@@ -77,7 +77,7 @@ class Config {
77
77
  }
78
78
  safeDeleteConfigIfInvalid(configFilePath) {
79
79
  if ((0, fs_1.existsSync)(configFilePath) && !this.isConfigFileValid(configFilePath)) {
80
- console.warn(chalk_1.default.yellow(`Warning: Detected corrupted config at ${configFilePath}. Removing...`));
80
+ console.warn((0, chalk_1.getChalk)().yellow(`Warning: Detected corrupted config at ${configFilePath}. Removing...`));
81
81
  (0, fs_1.unlinkSync)(configFilePath);
82
82
  }
83
83
  }
@@ -137,7 +137,7 @@ class Config {
137
137
  this.getEncryptedConfig(oldConfigData, true);
138
138
  }
139
139
  catch (_error) {
140
- _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
140
+ _1.cliux.print((0, chalk_1.getChalk)().red('Error: Config file is corrupted'));
141
141
  _1.cliux.print(_error);
142
142
  process.exit(1);
143
143
  }
@@ -188,7 +188,7 @@ class Config {
188
188
  }
189
189
  catch (__error) {
190
190
  // console.trace(error.message)
191
- _1.cliux.print(chalk_1.default.red('Error: Config file is corrupted'));
191
+ _1.cliux.print((0, chalk_1.getChalk)().red('Error: Config file is corrupted'));
192
192
  _1.cliux.print(_error);
193
193
  process.exit(1);
194
194
  }
@@ -2,6 +2,6 @@
2
2
  * Reads all content type schema files from a directory
3
3
  * @param dirPath - Path to content types directory
4
4
  * @param ignoredFiles - Files to ignore (defaults to schema.json, .DS_Store, __master.json, __priority.json)
5
- * @returns Array of content type schemas
5
+ * @returns Array of content type schemas (empty if the path is missing or has no eligible files)
6
6
  */
7
- export declare function readContentTypeSchemas(dirPath: string, ignoredFiles?: string[]): Record<string, unknown>[] | null;
7
+ export declare function readContentTypeSchemas(dirPath: string, ignoredFiles?: string[]): Record<string, unknown>[];
@@ -1,19 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.readContentTypeSchemas = readContentTypeSchemas;
4
+ const node_fs_1 = require("node:fs");
4
5
  const node_path_1 = require("node:path");
5
- const fs_utility_1 = require("./fs-utility");
6
6
  /**
7
7
  * Reads all content type schema files from a directory
8
8
  * @param dirPath - Path to content types directory
9
9
  * @param ignoredFiles - Files to ignore (defaults to schema.json, .DS_Store, __master.json, __priority.json)
10
- * @returns Array of content type schemas
10
+ * @returns Array of content type schemas (empty if the path is missing or has no eligible files)
11
11
  */
12
12
  function readContentTypeSchemas(dirPath, ignoredFiles = ['schema.json', '.DS_Store', '__master.json', '__priority.json', 'field_rules_uid.json']) {
13
- const fsUtil = new fs_utility_1.FsUtility();
14
- const files = fsUtil.readdir(dirPath);
13
+ if (!(0, node_fs_1.existsSync)(dirPath)) {
14
+ return [];
15
+ }
16
+ const files = (0, node_fs_1.readdirSync)(dirPath);
15
17
  if (!files || files.length === 0) {
16
- return null;
18
+ return [];
17
19
  }
18
20
  const contentTypes = [];
19
21
  for (const file of files) {
@@ -27,7 +29,8 @@ function readContentTypeSchemas(dirPath, ignoredFiles = ['schema.json', '.DS_Sto
27
29
  }
28
30
  try {
29
31
  const filePath = (0, node_path_1.resolve)(dirPath, file);
30
- const contentType = fsUtil.readFile(filePath);
32
+ const raw = (0, node_fs_1.readFileSync)(filePath, 'utf8');
33
+ const contentType = JSON.parse(raw);
31
34
  if (contentType) {
32
35
  contentTypes.push(contentType);
33
36
  }
package/lib/index.d.ts CHANGED
@@ -24,6 +24,8 @@ export { App, AppData, Installation, marketplaceSDKClient, MarketplaceSDKInitiat
24
24
  export { Args, CommandHelp, Config, Errors, Flags, loadHelpClass, Help, HelpBase, HelpSection, HelpSectionRenderer, HelpSectionKeyValueTable, Hook, Interfaces, Parser, Plugin, run, toStandardizedId, toConfiguredId, settings, Settings, flush, ux, execute, } from '@oclif/core';
25
25
  export { FlagInput, ArgInput, FlagDefinition } from '@oclif/core/lib/interfaces/parser';
26
26
  export { default as TablePrompt } from './inquirer-table-prompt';
27
+ export { loadChalk, getChalk } from './chalk';
28
+ export type { ChalkInstance } from './chalk';
27
29
  export { Logger };
28
30
  export { default as authenticationHandler } from './authentication-handler';
29
31
  export { v2Logger as log, cliErrorHandler, handleAndLogError, getLogPath, getSessionLogPath } from './logger/log';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DefaultProgressStrategy = exports.CustomProgressStrategy = exports.ProgressStrategyRegistry = exports.PrimaryProcessStrategy = exports.SummaryManager = exports.CLIProgressManager = exports.getSessionLogPath = exports.getLogPath = exports.handleAndLogError = exports.cliErrorHandler = exports.log = exports.authenticationHandler = exports.Logger = exports.TablePrompt = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.marketplaceSDKInitiator = exports.MarketplaceSDKInitiator = exports.marketplaceSDKClient = exports.CLITable = exports.createLogContext = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.LoggerService = void 0;
3
+ exports.DefaultProgressStrategy = exports.CustomProgressStrategy = exports.ProgressStrategyRegistry = exports.PrimaryProcessStrategy = exports.SummaryManager = exports.CLIProgressManager = exports.getSessionLogPath = exports.getLogPath = exports.handleAndLogError = exports.cliErrorHandler = exports.log = exports.authenticationHandler = exports.Logger = exports.getChalk = exports.loadChalk = exports.TablePrompt = exports.execute = exports.ux = exports.flush = exports.settings = exports.toConfiguredId = exports.toStandardizedId = exports.Plugin = exports.Parser = exports.Interfaces = exports.HelpBase = exports.Help = exports.loadHelpClass = exports.Flags = exports.Errors = exports.Config = exports.CommandHelp = exports.Args = exports.marketplaceSDKInitiator = exports.MarketplaceSDKInitiator = exports.marketplaceSDKClient = exports.CLITable = exports.createLogContext = exports.Command = exports.flags = exports.args = exports.NodeCrypto = exports.managementSDKInitiator = exports.managementSDKClient = exports.configHandler = exports.authHandler = exports.messageHandler = exports.CLIError = exports.cliux = exports.LoggerService = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const logger_1 = tslib_1.__importDefault(require("./logger"));
6
6
  exports.Logger = logger_1.default;
@@ -64,6 +64,9 @@ Object.defineProperty(exports, "ux", { enumerable: true, get: function () { retu
64
64
  Object.defineProperty(exports, "execute", { enumerable: true, get: function () { return core_1.execute; } });
65
65
  var inquirer_table_prompt_1 = require("./inquirer-table-prompt");
66
66
  Object.defineProperty(exports, "TablePrompt", { enumerable: true, get: function () { return tslib_1.__importDefault(inquirer_table_prompt_1).default; } });
67
+ var chalk_1 = require("./chalk");
68
+ Object.defineProperty(exports, "loadChalk", { enumerable: true, get: function () { return chalk_1.loadChalk; } });
69
+ Object.defineProperty(exports, "getChalk", { enumerable: true, get: function () { return chalk_1.getChalk; } });
67
70
  var authentication_handler_1 = require("./authentication-handler");
68
71
  Object.defineProperty(exports, "authenticationHandler", { enumerable: true, get: function () { return tslib_1.__importDefault(authentication_handler_1).default; } });
69
72
  var log_1 = require("./logger/log");
@@ -5,7 +5,7 @@
5
5
  * inquirer 12 legacy adapter: constructor(question, rl, answers) + run() returns Promise.
6
6
  */
7
7
  const tslib_1 = require("tslib");
8
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
8
+ const chalk_1 = require("./chalk");
9
9
  const figures_1 = tslib_1.__importDefault(require("figures"));
10
10
  const cli_cursor_1 = tslib_1.__importDefault(require("cli-cursor"));
11
11
  const cli_table_1 = tslib_1.__importDefault(require("cli-table"));
@@ -142,13 +142,13 @@ class TablePrompt {
142
142
  if (!this.spaceKeyPressed) {
143
143
  msg +=
144
144
  ' (Press ' +
145
- chalk_1.default.cyan.bold('<space>') +
145
+ (0, chalk_1.getChalk)().cyan.bold('<space>') +
146
146
  ' to select, ' +
147
- chalk_1.default.cyan.bold('<Up/Down>') +
147
+ (0, chalk_1.getChalk)().cyan.bold('<Up/Down>') +
148
148
  ' rows, ' +
149
- chalk_1.default.cyan.bold('<Left/Right>') +
149
+ (0, chalk_1.getChalk)().cyan.bold('<Left/Right>') +
150
150
  ' columns, ' +
151
- chalk_1.default.cyan.bold('<Enter>') +
151
+ (0, chalk_1.getChalk)().cyan.bold('<Enter>') +
152
152
  ' to confirm)';
153
153
  }
154
154
  return msg;
@@ -156,7 +156,7 @@ class TablePrompt {
156
156
  render() {
157
157
  const [firstIndex, lastIndex] = this.paginate();
158
158
  const table = new cli_table_1.default({
159
- head: [chalk_1.default.reset.dim(`${firstIndex + 1}-${lastIndex + 1} of ${this.rows.length}`)].concat(this.columns.map((c) => chalk_1.default.reset.bold(pluckName(c)))),
159
+ head: [(0, chalk_1.getChalk)().reset.dim(`${firstIndex + 1}-${lastIndex + 1} of ${this.rows.length}`)].concat(this.columns.map((c) => (0, chalk_1.getChalk)().reset.bold(pluckName(c)))),
160
160
  });
161
161
  for (let rowIndex = firstIndex; rowIndex <= lastIndex; rowIndex++) {
162
162
  const row = this.rows[rowIndex];
@@ -168,7 +168,7 @@ class TablePrompt {
168
168
  const cellValue = getValue(this.columns[colIndex]) === this.values[rowIndex] ? figures_1.default.radioOn : figures_1.default.radioOff;
169
169
  columnValues.push(`${isSelected ? '[' : ' '} ${cellValue} ${isSelected ? ']' : ' '}`);
170
170
  }
171
- const chalkModifier = this.status !== 'answered' && this.pointer === rowIndex ? chalk_1.default.reset.bold.cyan : chalk_1.default.reset;
171
+ const chalkModifier = this.status !== 'answered' && this.pointer === rowIndex ? (0, chalk_1.getChalk)().reset.bold.cyan : (0, chalk_1.getChalk)().reset;
172
172
  table.push({ [chalkModifier(pluckName(row))]: columnValues });
173
173
  }
174
174
  const message = this.getMessage() + '\n\n' + table.toString();
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
4
+ const chalk_1 = require("../chalk");
5
5
  const ora_1 = tslib_1.__importDefault(require("ora"));
6
6
  const cli_progress_1 = tslib_1.__importDefault(require("cli-progress"));
7
7
  const summary_manager_1 = tslib_1.__importDefault(require("./summary-manager"));
@@ -46,11 +46,11 @@ class CLIProgressManager {
46
46
  return;
47
47
  const safeBranchName = branchName || 'main';
48
48
  const branchInfo = headerTitle || `${safeBranchName === null || safeBranchName === void 0 ? void 0 : safeBranchName.toUpperCase()} CONTENT`;
49
- console.log('\n' + chalk_1.default.bold('='.repeat(80)));
49
+ console.log('\n' + (0, chalk_1.getChalk)().bold('='.repeat(80)));
50
50
  if (branchInfo) {
51
- console.log(chalk_1.default.bold.white(` ${branchInfo}`));
51
+ console.log((0, chalk_1.getChalk)().bold.white(` ${branchInfo}`));
52
52
  }
53
- console.log(chalk_1.default.bold('='.repeat(80)) + '\n');
53
+ console.log((0, chalk_1.getChalk)().bold('='.repeat(80)) + '\n');
54
54
  }
55
55
  /**
56
56
  * Print the final summary for all modules using strategies.
@@ -240,20 +240,20 @@ class CLIProgressManager {
240
240
  this.multiBar = new cli_progress_1.default.MultiBar({
241
241
  clearOnComplete: false,
242
242
  hideCursor: true,
243
- format: ' {label} |' + chalk_1.default.cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
243
+ format: ' {label} |' + (0, chalk_1.getChalk)().cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
244
244
  barCompleteChar: '\u2588',
245
245
  barIncompleteChar: '\u2591',
246
246
  }, cli_progress_1.default.Presets.shades_classic);
247
247
  if (!this.showConsoleLogs) {
248
- console.log(chalk_1.default.bold.cyan(`\n${this.moduleName}:`));
248
+ console.log((0, chalk_1.getChalk)().bold.cyan(`\n${this.moduleName}:`));
249
249
  }
250
250
  }
251
251
  else if (this.total > 0) {
252
252
  if (!this.showConsoleLogs) {
253
- console.log(chalk_1.default.bold.cyan(`\n${this.moduleName}:`));
253
+ console.log((0, chalk_1.getChalk)().bold.cyan(`\n${this.moduleName}:`));
254
254
  }
255
255
  this.progressBar = new cli_progress_1.default.SingleBar({
256
- format: ' {label} |' + chalk_1.default.cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
256
+ format: ' {label} |' + (0, chalk_1.getChalk)().cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
257
257
  barCompleteChar: '\u2588',
258
258
  barIncompleteChar: '\u2591',
259
259
  hideCursor: true,
@@ -261,13 +261,13 @@ class CLIProgressManager {
261
261
  const formattedName = this.formatModuleName(this.moduleName);
262
262
  const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
263
263
  this.progressBar.start(this.total, 0, {
264
- label: chalk_1.default.gray(` └─ ${displayName}`.padEnd(25)),
265
- status: chalk_1.default.gray('Starting...'),
264
+ label: (0, chalk_1.getChalk)().gray(` └─ ${displayName}`.padEnd(25)),
265
+ status: (0, chalk_1.getChalk)().gray('Starting...'),
266
266
  percentage: ' 0',
267
267
  });
268
268
  }
269
269
  else {
270
- this.spinner = (0, ora_1.default)(`${chalk_1.default.bold(this.moduleName)}: Processing...`).start();
270
+ this.spinner = (0, ora_1.default)(`${(0, chalk_1.getChalk)().bold(this.moduleName)}: Processing...`).start();
271
271
  }
272
272
  }
273
273
  /**
@@ -289,8 +289,8 @@ class CLIProgressManager {
289
289
  const displayName = this.formatProcessName(processName);
290
290
  const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
291
291
  process.progressBar = this.multiBar.create(total, 0, {
292
- label: chalk_1.default.gray(indentedLabel),
293
- status: chalk_1.default.gray('Pending'),
292
+ label: (0, chalk_1.getChalk)().gray(indentedLabel),
293
+ status: (0, chalk_1.getChalk)().gray('Pending'),
294
294
  percentage: ' 0',
295
295
  });
296
296
  }
@@ -326,8 +326,8 @@ class CLIProgressManager {
326
326
  const displayName = this.formatProcessName(processName);
327
327
  const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
328
328
  process.progressBar.update(0, {
329
- label: chalk_1.default.yellow(indentedLabel),
330
- status: chalk_1.default.yellow('Processing'),
329
+ label: (0, chalk_1.getChalk)().yellow(indentedLabel),
330
+ status: (0, chalk_1.getChalk)().yellow('Processing'),
331
331
  percentage: ' 0',
332
332
  });
333
333
  }
@@ -356,12 +356,12 @@ class CLIProgressManager {
356
356
  const percentage = Math.round((totalProcessed / process.total) * 100);
357
357
  const formattedPercentage = this.formatPercentage(percentage);
358
358
  const statusText = success
359
- ? chalk_1.default.green(`✓ Complete (${process.successCount}/${process.current})`)
360
- : chalk_1.default.red(`✗ Failed (${process.successCount}/${process.current})`);
359
+ ? (0, chalk_1.getChalk)().green(`✓ Complete (${process.successCount}/${process.current})`)
360
+ : (0, chalk_1.getChalk)().red(`✗ Failed (${process.successCount}/${process.current})`);
361
361
  const displayName = this.formatProcessName(processName);
362
362
  const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
363
363
  process.progressBar.update(process.total, {
364
- label: success ? chalk_1.default.green(indentedLabel) : chalk_1.default.red(indentedLabel),
364
+ label: success ? (0, chalk_1.getChalk)().green(indentedLabel) : (0, chalk_1.getChalk)().red(indentedLabel),
365
365
  status: statusText,
366
366
  percentage: formattedPercentage,
367
367
  });
@@ -382,8 +382,8 @@ class CLIProgressManager {
382
382
  const displayName = this.formatProcessName(processName);
383
383
  const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
384
384
  process.progressBar.update(process.current, {
385
- label: chalk_1.default.yellow(indentedLabel),
386
- status: chalk_1.default.yellow(message),
385
+ label: (0, chalk_1.getChalk)().yellow(indentedLabel),
386
+ status: (0, chalk_1.getChalk)().yellow(message),
387
387
  percentage: formattedPercentage,
388
388
  });
389
389
  }
@@ -394,13 +394,13 @@ class CLIProgressManager {
394
394
  const formattedName = this.formatModuleName(this.moduleName);
395
395
  const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
396
396
  this.progressBar.update(this.progressBar.getProgress() * this.total, {
397
- label: chalk_1.default.yellow(` └─ ${displayName}`.padEnd(25)),
398
- status: chalk_1.default.yellow(message),
397
+ label: (0, chalk_1.getChalk)().yellow(` └─ ${displayName}`.padEnd(25)),
398
+ status: (0, chalk_1.getChalk)().yellow(message),
399
399
  percentage: formattedPercentage,
400
400
  });
401
401
  }
402
402
  else if (this.spinner) {
403
- this.spinner.text = `${chalk_1.default.bold(this.moduleName)}: ${message}`;
403
+ this.spinner.text = `${(0, chalk_1.getChalk)().bold(this.moduleName)}: ${message}`;
404
404
  }
405
405
  }
406
406
  return this;
@@ -444,8 +444,8 @@ class CLIProgressManager {
444
444
  const displayName = this.formatProcessName(targetProcess);
445
445
  const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
446
446
  process.progressBar.increment(1, {
447
- label: chalk_1.default.cyan(indentedLabel),
448
- status: chalk_1.default.cyan(statusText),
447
+ label: (0, chalk_1.getChalk)().cyan(indentedLabel),
448
+ status: (0, chalk_1.getChalk)().cyan(statusText),
449
449
  percentage: formattedPercentage,
450
450
  });
451
451
  }
@@ -461,10 +461,14 @@ class CLIProgressManager {
461
461
  // Show completion status when finished, otherwise show running count
462
462
  const statusText = totalProcessed >= this.total
463
463
  ? this.failureCount === 0
464
- ? chalk_1.default.green(`✓ Complete (${this.successCount}/${totalProcessed})`)
465
- : chalk_1.default.yellow(`✓ Complete (${this.successCount}/${totalProcessed})`)
466
- : chalk_1.default.cyan(`${this.successCount}✓ ${this.failureCount}✗`);
467
- const labelColor = totalProcessed >= this.total ? (this.failureCount === 0 ? chalk_1.default.green : chalk_1.default.yellow) : chalk_1.default.cyan;
464
+ ? (0, chalk_1.getChalk)().green(`✓ Complete (${this.successCount}/${totalProcessed})`)
465
+ : (0, chalk_1.getChalk)().yellow(`✓ Complete (${this.successCount}/${totalProcessed})`)
466
+ : (0, chalk_1.getChalk)().cyan(`${this.successCount}✓ ${this.failureCount}✗`);
467
+ const labelColor = totalProcessed >= this.total
468
+ ? this.failureCount === 0
469
+ ? (0, chalk_1.getChalk)().green
470
+ : (0, chalk_1.getChalk)().yellow
471
+ : (0, chalk_1.getChalk)().cyan;
468
472
  const formattedName = this.formatModuleName(this.moduleName);
469
473
  const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
470
474
  this.progressBar.increment(1, {
@@ -475,7 +479,7 @@ class CLIProgressManager {
475
479
  }
476
480
  else if (this.spinner) {
477
481
  const total = this.successCount + this.failureCount;
478
- this.spinner.text = `${chalk_1.default.bold(this.moduleName)}: ${total} items (${this.successCount}✓ ${this.failureCount}✗)`;
482
+ this.spinner.text = `${(0, chalk_1.getChalk)().bold(this.moduleName)}: ${total} items (${this.successCount}✓ ${this.failureCount}✗)`;
479
483
  }
480
484
  }
481
485
  }
@@ -520,13 +524,13 @@ class CLIProgressManager {
520
524
  }
521
525
  if (!this.enableNestedProgress) {
522
526
  // Simple summary for single progress
523
- this.log('\n' + chalk_1.default.bold(`${this.moduleName} Summary:`));
524
- this.log(`✓ Success: ${chalk_1.default.green(this.successCount)}`);
525
- this.log(`✗ Failures: ${chalk_1.default.red(this.failureCount)}`);
527
+ this.log('\n' + (0, chalk_1.getChalk)().bold(`${this.moduleName} Summary:`));
528
+ this.log(`✓ Success: ${(0, chalk_1.getChalk)().green(this.successCount)}`);
529
+ this.log(`✗ Failures: ${(0, chalk_1.getChalk)().red(this.failureCount)}`);
526
530
  return;
527
531
  }
528
532
  // Detailed summary for nested progress
529
- this.log('\n' + chalk_1.default.bold(`${this.moduleName} Detailed Summary:`));
533
+ this.log('\n' + (0, chalk_1.getChalk)().bold(`${this.moduleName} Detailed Summary:`));
530
534
  for (const [processName, process] of this.processes) {
531
535
  const status = process.status === 'completed'
532
536
  ? '✓'
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const chalk_1 = tslib_1.__importDefault(require("chalk"));
3
+ const chalk_1 = require("../chalk");
5
4
  class SummaryManager {
6
5
  constructor({ operationName, context }) {
7
6
  this.modules = new Map();
@@ -83,16 +82,16 @@ class SummaryManager {
83
82
  const totalItems = Array.from(this.modules.values()).reduce((sum, m) => sum + m.successCount + m.failureCount, 0);
84
83
  const totalSuccess = Array.from(this.modules.values()).reduce((sum, m) => sum + m.successCount, 0);
85
84
  const totalFailures = Array.from(this.modules.values()).reduce((sum, m) => sum + m.failureCount, 0);
86
- console.log('\n' + chalk_1.default.bold('='.repeat(80)));
87
- console.log(chalk_1.default.bold(`${this.operationName} SUMMARY`));
88
- console.log('\n' + chalk_1.default.bold('Overall Statistics:'));
89
- console.log(` Total ${this.operationName} Time: ${chalk_1.default.cyan(this.formatDuration(totalDuration))}`);
90
- console.log(` Modules Processed: ${chalk_1.default.cyan(completedModules)}/${chalk_1.default.cyan(totalModules)}`);
91
- console.log(` Items Processed: ${chalk_1.default.green(totalSuccess)} success, ${chalk_1.default.red(totalFailures)} failed of ${chalk_1.default.cyan(totalItems)} total`);
92
- console.log(` Success Rate: ${chalk_1.default.cyan(this.calculateSuccessRate(totalSuccess, totalItems))}%`);
85
+ console.log('\n' + (0, chalk_1.getChalk)().bold('='.repeat(80)));
86
+ console.log((0, chalk_1.getChalk)().bold(`${this.operationName} SUMMARY`));
87
+ console.log('\n' + (0, chalk_1.getChalk)().bold('Overall Statistics:'));
88
+ console.log(` Total ${this.operationName} Time: ${(0, chalk_1.getChalk)().cyan(this.formatDuration(totalDuration))}`);
89
+ console.log(` Modules Processed: ${(0, chalk_1.getChalk)().cyan(completedModules)}/${(0, chalk_1.getChalk)().cyan(totalModules)}`);
90
+ console.log(` Items Processed: ${(0, chalk_1.getChalk)().green(totalSuccess)} success, ${(0, chalk_1.getChalk)().red(totalFailures)} failed of ${(0, chalk_1.getChalk)().cyan(totalItems)} total`);
91
+ console.log(` Success Rate: ${(0, chalk_1.getChalk)().cyan(this.calculateSuccessRate(totalSuccess, totalItems))}%`);
93
92
  // Module Details
94
- console.log('\n' + chalk_1.default.bold('Module Details:'));
95
- console.log(chalk_1.default.gray('-'.repeat(80)));
93
+ console.log('\n' + (0, chalk_1.getChalk)().bold('Module Details:'));
94
+ console.log((0, chalk_1.getChalk)().gray('-'.repeat(80)));
96
95
  Array.from(this.modules.values()).forEach((module) => {
97
96
  const status = this.getStatusIcon(module.status);
98
97
  const totalCount = module.successCount + module.failureCount;
@@ -104,18 +103,18 @@ class SummaryManager {
104
103
  `${duration.padStart(8)}`);
105
104
  });
106
105
  // Final Status
107
- console.log('\n' + chalk_1.default.bold('Final Status:'));
106
+ console.log('\n' + (0, chalk_1.getChalk)().bold('Final Status:'));
108
107
  if (!this.hasFailures() && failedModules === 0) {
109
- console.log(chalk_1.default.bold.green(`✅ ${this.operationName} completed successfully!`));
108
+ console.log((0, chalk_1.getChalk)().bold.green(`✅ ${this.operationName} completed successfully!`));
110
109
  }
111
110
  else if (this.hasFailures() || failedModules > 0) {
112
- console.log(chalk_1.default.bold.yellow(`⚠️ ${this.operationName} completed with failures, see the logs for more details.`));
111
+ console.log((0, chalk_1.getChalk)().bold.yellow(`⚠️ ${this.operationName} completed with failures, see the logs for more details.`));
113
112
  }
114
113
  else {
115
- console.log(chalk_1.default.bold.red(`❌ ${this.operationName} failed`));
114
+ console.log((0, chalk_1.getChalk)().bold.red(`❌ ${this.operationName} failed`));
116
115
  }
117
- console.log(chalk_1.default.bold('='.repeat(80)));
118
- console.log(chalk_1.default.bold('='.repeat(80)));
116
+ console.log((0, chalk_1.getChalk)().bold('='.repeat(80)));
117
+ console.log((0, chalk_1.getChalk)().bold('='.repeat(80)));
119
118
  // Simple failure summary with log reference
120
119
  this.printFailureSummaryWithLogReference();
121
120
  }
@@ -130,35 +129,35 @@ class SummaryManager {
130
129
  if (modulesWithFailures.length === 0)
131
130
  return;
132
131
  const totalFailures = modulesWithFailures.reduce((sum, m) => sum + m.failures.length, 0);
133
- console.log('\n' + chalk_1.default.bold.red('Failure Summary:'));
134
- console.log(chalk_1.default.red('-'.repeat(50)));
132
+ console.log('\n' + (0, chalk_1.getChalk)().bold.red('Failure Summary:'));
133
+ console.log((0, chalk_1.getChalk)().red('-'.repeat(50)));
135
134
  modulesWithFailures.forEach((module) => {
136
- console.log(`${chalk_1.default.bold.red('✗')} ${chalk_1.default.bold(module.name)}: ${chalk_1.default.red(module.failures.length)} failures`);
135
+ console.log(`${(0, chalk_1.getChalk)().bold.red('✗')} ${(0, chalk_1.getChalk)().bold(module.name)}: ${(0, chalk_1.getChalk)().red(module.failures.length)} failures`);
137
136
  // Show just first 2-3 failures briefly
138
137
  const preview = module.failures.slice(0, 2);
139
138
  preview.forEach((failure) => {
140
- console.log(` • ${chalk_1.default.gray(failure.item)}`);
139
+ console.log(` • ${(0, chalk_1.getChalk)().gray(failure.item)}`);
141
140
  });
142
141
  if (module.failures.length > 2) {
143
- console.log(` ${chalk_1.default.gray(`... and ${module.failures.length - 2} more`)}`);
142
+ console.log(` ${(0, chalk_1.getChalk)().gray(`... and ${module.failures.length - 2} more`)}`);
144
143
  }
145
144
  });
146
- console.log(chalk_1.default.blue('\n📋 For detailed error information, check the log files:'));
147
- //console.log(chalk.blue(` ${getSessionLogPath()}`));
148
- console.log(chalk_1.default.gray(' Recent errors are logged with full context and stack traces.'));
145
+ console.log((0, chalk_1.getChalk)().blue('\n📋 For detailed error information, check the log files:'));
146
+ //console.log(getChalk().blue(` ${getSessionLogPath()}`));
147
+ console.log((0, chalk_1.getChalk)().gray(' Recent errors are logged with full context and stack traces.'));
149
148
  }
150
149
  getStatusIcon(status) {
151
150
  switch (status) {
152
151
  case 'completed':
153
- return chalk_1.default.green('✓');
152
+ return (0, chalk_1.getChalk)().green('✓');
154
153
  case 'failed':
155
- return chalk_1.default.red('✗');
154
+ return (0, chalk_1.getChalk)().red('✗');
156
155
  case 'running':
157
- return chalk_1.default.yellow('●');
156
+ return (0, chalk_1.getChalk)().yellow('●');
158
157
  case 'pending':
159
- return chalk_1.default.gray('○');
158
+ return (0, chalk_1.getChalk)().gray('○');
160
159
  default:
161
- return chalk_1.default.gray('?');
160
+ return (0, chalk_1.getChalk)().gray('?');
162
161
  }
163
162
  }
164
163
  formatDuration(ms) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentstack/cli-utilities",
3
- "version": "2.0.0-beta.3",
3
+ "version": "2.0.0-beta.5",
4
4
  "description": "Utilities for contentstack projects",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -33,11 +33,11 @@
33
33
  "author": "contentstack",
34
34
  "license": "MIT",
35
35
  "dependencies": {
36
- "@contentstack/management": "~1.27.6",
36
+ "@contentstack/management": "~1.29.1",
37
37
  "@contentstack/marketplace-sdk": "^1.5.0",
38
38
  "@oclif/core": "^4.3.0",
39
39
  "axios": "^1.13.5",
40
- "chalk": "^4.1.2",
40
+ "chalk": "^5.6.2",
41
41
  "cli-cursor": "^3.1.0",
42
42
  "cli-progress": "^3.12.0",
43
43
  "cli-table": "^0.3.11",