@contentstack/cli-utilities 1.17.1 → 1.17.2

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.
@@ -371,6 +371,7 @@ class AuthHandler {
371
371
  else {
372
372
  cli_ux_1.default.print('No OAuth configuration set.');
373
373
  this.unsetConfigData();
374
+ return Promise.resolve();
374
375
  }
375
376
  }
376
377
  restoreOAuthConfig() {
@@ -13,3 +13,4 @@ export declare const levelColors: {
13
13
  info: string;
14
14
  debug: string;
15
15
  };
16
+ export declare const PROGRESS_SUPPORTED_MODULES: readonly ["export", "import", "audit", "import-setup"];
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.levelColors = exports.logLevels = void 0;
3
+ exports.PROGRESS_SUPPORTED_MODULES = exports.levelColors = exports.logLevels = void 0;
4
4
  exports.logLevels = {
5
5
  error: 0,
6
6
  warn: 1,
7
7
  info: 2,
8
8
  success: 2,
9
9
  debug: 3,
10
- verbose: 4
10
+ verbose: 4,
11
11
  };
12
12
  // 2. Create color mappings (for console only)
13
13
  exports.levelColors = {
@@ -15,5 +15,6 @@ exports.levelColors = {
15
15
  warn: 'yellow',
16
16
  success: 'green',
17
17
  info: 'white',
18
- debug: 'blue'
18
+ debug: 'blue',
19
19
  };
20
+ exports.PROGRESS_SUPPORTED_MODULES = ['export', 'import', 'audit', 'import-setup'];
@@ -11,7 +11,6 @@ const node_fs_1 = require("node:fs");
11
11
  const helper_1 = require("./helper");
12
12
  class FsUtility {
13
13
  constructor(options = {}) {
14
- var _a;
15
14
  this.isArray = false;
16
15
  this.prefixKey = '';
17
16
  this.currentFileName = '';
@@ -35,7 +34,7 @@ class FsUtility {
35
34
  this.metaPickKeys = metaPickKeys || [];
36
35
  this.moduleName = moduleName || 'chunk';
37
36
  this.chunkFileSize = chunkFileSize || 10;
38
- this.keepMetadata = keepMetadata || ((_a = keepMetadata === undefined) !== null && _a !== void 0 ? _a : true);
37
+ this.keepMetadata = keepMetadata !== null && keepMetadata !== void 0 ? keepMetadata : true;
39
38
  this.indexFileName = indexFileName || 'index.json';
40
39
  this.pageInfo.hasNextPage = (0, keys_1.default)(this.indexFileContent).length > 0;
41
40
  this.defaultInitContent = defaultInitContent || this.isArray ? '[' : this.fileExt === 'json' ? '{' : '';
package/lib/helpers.d.ts CHANGED
@@ -27,6 +27,7 @@ export declare const formatError: (error: any) => string;
27
27
  * from.
28
28
  */
29
29
  export declare const redactObject: (obj: any) => any;
30
+ export declare function clearProgressModuleSetting(): void;
30
31
  /**
31
32
  * Get authentication method from config
32
33
  * @returns Authentication method string ('OAuth', 'Basic Auth', or empty string)
package/lib/helpers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogContext = exports.getAuthenticationMethod = exports.redactObject = exports.formatError = exports.validateRegex = exports.validateFileName = exports.validateUids = exports.sanitizePath = exports.escapeRegExp = exports.validatePath = exports.createDeveloperHubUrl = exports.isManagementTokenValid = exports.getBranchFromAlias = exports.doesBranchExist = exports.isAuthenticated = void 0;
3
+ exports.createLogContext = exports.getAuthenticationMethod = exports.clearProgressModuleSetting = exports.redactObject = exports.formatError = exports.validateRegex = exports.validateFileName = exports.validateUids = exports.sanitizePath = exports.escapeRegExp = exports.validatePath = exports.createDeveloperHubUrl = exports.isManagementTokenValid = exports.getBranchFromAlias = exports.doesBranchExist = exports.isAuthenticated = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const recheck_1 = require("recheck");
6
6
  const traverse_1 = tslib_1.__importDefault(require("traverse"));
@@ -191,8 +191,8 @@ const formatError = function (error) {
191
191
  // If message is in JSON format, parse it to extract the actual message string
192
192
  try {
193
193
  const parsedMessage = JSON.parse(message);
194
- if (typeof parsedMessage === 'object') {
195
- message = (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.message) || message;
194
+ if (typeof parsedMessage === 'object' && parsedMessage !== null) {
195
+ message = (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.message) || (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.errorMessage) || (parsedMessage === null || parsedMessage === void 0 ? void 0 : parsedMessage.error) || message;
196
196
  }
197
197
  }
198
198
  catch (e) {
@@ -244,6 +244,14 @@ const sensitiveKeys = [
244
244
  /management[-._]?token/i,
245
245
  /delivery[-._]?token/i,
246
246
  ];
247
+ function clearProgressModuleSetting() {
248
+ const logConfig = _1.configHandler.get('log') || {};
249
+ if (logConfig === null || logConfig === void 0 ? void 0 : logConfig.progressSupportedModule) {
250
+ delete logConfig.progressSupportedModule;
251
+ _1.configHandler.set('log', logConfig);
252
+ }
253
+ }
254
+ exports.clearProgressModuleSetting = clearProgressModuleSetting;
247
255
  /**
248
256
  * Get authentication method from config
249
257
  * @returns Authentication method string ('OAuth', 'Basic Auth', or empty string)
package/lib/index.d.ts CHANGED
@@ -26,3 +26,4 @@ export { default as TablePrompt } from './inquirer-table-prompt';
26
26
  export { Logger };
27
27
  export { default as authenticationHandler } from './authentication-handler';
28
28
  export { v2Logger as log, cliErrorHandler, handleAndLogError, getLogPath } from './logger/log';
29
+ export { CLIProgressManager, SummaryManager, PrimaryProcessStrategy, ProgressStrategyRegistry, CustomProgressStrategy, DefaultProgressStrategy } from './progress-summary';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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.run = 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.printFlagDeprecation = 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.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.run = 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.printFlagDeprecation = 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;
@@ -71,3 +71,10 @@ Object.defineProperty(exports, "log", { enumerable: true, get: function () { ret
71
71
  Object.defineProperty(exports, "cliErrorHandler", { enumerable: true, get: function () { return log_1.cliErrorHandler; } });
72
72
  Object.defineProperty(exports, "handleAndLogError", { enumerable: true, get: function () { return log_1.handleAndLogError; } });
73
73
  Object.defineProperty(exports, "getLogPath", { enumerable: true, get: function () { return log_1.getLogPath; } });
74
+ var progress_summary_1 = require("./progress-summary");
75
+ Object.defineProperty(exports, "CLIProgressManager", { enumerable: true, get: function () { return progress_summary_1.CLIProgressManager; } });
76
+ Object.defineProperty(exports, "SummaryManager", { enumerable: true, get: function () { return progress_summary_1.SummaryManager; } });
77
+ Object.defineProperty(exports, "PrimaryProcessStrategy", { enumerable: true, get: function () { return progress_summary_1.PrimaryProcessStrategy; } });
78
+ Object.defineProperty(exports, "ProgressStrategyRegistry", { enumerable: true, get: function () { return progress_summary_1.ProgressStrategyRegistry; } });
79
+ Object.defineProperty(exports, "CustomProgressStrategy", { enumerable: true, get: function () { return progress_summary_1.CustomProgressStrategy; } });
80
+ Object.defineProperty(exports, "DefaultProgressStrategy", { enumerable: true, get: function () { return progress_summary_1.DefaultProgressStrategy; } });
@@ -1,4 +1,5 @@
1
- import { logLevels } from "../constants/logging";
1
+ import { logLevels } from '../constants/logging';
2
+ import ProgressBar from 'cli-progress';
2
3
  export interface IPromptOptions {
3
4
  prompt?: string;
4
5
  type?: 'normal' | 'mask' | 'hide' | 'single';
@@ -101,3 +102,51 @@ export interface ErrorContextBase {
101
102
  export type ErrorContext = ErrorContextBase & {
102
103
  [key: string]: unknown;
103
104
  };
105
+ export interface Failure {
106
+ item: string;
107
+ error: string | null;
108
+ process?: string;
109
+ }
110
+ export interface ProcessProgress {
111
+ name: string;
112
+ total: number;
113
+ current: number;
114
+ status: 'pending' | 'active' | 'completed' | 'failed';
115
+ successCount: number;
116
+ failureCount: number;
117
+ failures: Failure[];
118
+ progressBar?: ProgressBar.SingleBar;
119
+ }
120
+ export interface ProgressManagerOptions {
121
+ showConsoleLogs?: boolean;
122
+ total?: number;
123
+ moduleName?: string;
124
+ enableNestedProgress?: boolean;
125
+ }
126
+ export interface ModuleResult {
127
+ name: string;
128
+ status: 'pending' | 'running' | 'completed' | 'failed';
129
+ startTime?: number;
130
+ endTime?: number;
131
+ totalItems: number;
132
+ successCount: number;
133
+ failureCount: number;
134
+ failures: Array<{
135
+ item: string;
136
+ error: string;
137
+ }>;
138
+ processes?: Array<{
139
+ processName: string;
140
+ [key: string]: any;
141
+ }>;
142
+ }
143
+ export interface SummaryOptions {
144
+ operationName: string;
145
+ context?: any;
146
+ branchName?: string;
147
+ }
148
+ export interface ProgressResult {
149
+ total: number;
150
+ success: number;
151
+ failures: number;
152
+ }
@@ -114,8 +114,7 @@ class CLIErrorHandler {
114
114
  if (typeof error === 'object') {
115
115
  try {
116
116
  const errorObj = error;
117
- const message = errorObj.message || errorObj.error || errorObj.statusText || 'Unknown error';
118
- const normalizedError = new Error(message);
117
+ const normalizedError = new Error('Error occurred');
119
118
  // Only copy essential properties
120
119
  const essentialProps = [
121
120
  'code',
package/lib/logger/log.js CHANGED
@@ -13,7 +13,7 @@ function createLoggerInstance() {
13
13
  var _a;
14
14
  const logConfig = __1.configHandler.get('log');
15
15
  const logLevel = (logConfig === null || logConfig === void 0 ? void 0 : logConfig.level) || 'info';
16
- const showConsoleLogs = (_a = logConfig === null || logConfig === void 0 ? void 0 : logConfig['show-console-logs']) !== null && _a !== void 0 ? _a : false;
16
+ const showConsoleLogs = (_a = logConfig === null || logConfig === void 0 ? void 0 : logConfig.showConsoleLogs) !== null && _a !== void 0 ? _a : false;
17
17
  const config = {
18
18
  basePath: getLogPath(),
19
19
  logLevel: logLevel,
@@ -6,6 +6,7 @@ const full_1 = require("klona/full");
6
6
  const path_1 = require("path");
7
7
  const winston = tslib_1.__importStar(require("winston"));
8
8
  const logging_1 = require("../constants/logging");
9
+ const __1 = require("..");
9
10
  const session_path_1 = require("./session-path");
10
11
  class Logger {
11
12
  constructor(config) {
@@ -46,26 +47,45 @@ class Logger {
46
47
  };
47
48
  }
48
49
  createLogger(level, filePath) {
50
+ var _a;
51
+ const transports = [
52
+ new winston.transports.File(Object.assign(Object.assign({}, this.loggerOptions), { filename: `${filePath}/${level}.log`, format: winston.format.combine(winston.format.timestamp(), winston.format.printf((info) => {
53
+ // Apply minimal redaction for files (debugging info preserved)
54
+ const redactedInfo = this.redact(info, false);
55
+ return JSON.stringify(redactedInfo);
56
+ })) })),
57
+ ];
58
+ // Determine console logging based on configuration
59
+ let showConsoleLogs = true;
60
+ if (__1.configHandler && typeof __1.configHandler.get === 'function') {
61
+ const logConfig = __1.configHandler.get('log') || {};
62
+ const currentModule = logConfig.progressSupportedModule;
63
+ const hasProgressSupport = currentModule && logging_1.PROGRESS_SUPPORTED_MODULES.includes(currentModule);
64
+ if (hasProgressSupport) {
65
+ // Plugin has progress bars - respect user's explicit setting, or default to false (show progress bars)
66
+ showConsoleLogs = (_a = logConfig.showConsoleLogs) !== null && _a !== void 0 ? _a : false;
67
+ }
68
+ else {
69
+ // Plugin doesn't have progress support - always show console logs
70
+ showConsoleLogs = true;
71
+ }
72
+ }
73
+ if (showConsoleLogs) {
74
+ transports.push(new winston.transports.Console({
75
+ format: winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => {
76
+ // Apply full redaction for console (user-facing)
77
+ const redactedInfo = this.redact(info, true);
78
+ const colorizer = winston.format.colorize();
79
+ const levelText = redactedInfo.level.toUpperCase();
80
+ const { timestamp, message } = redactedInfo;
81
+ return colorizer.colorize(redactedInfo.level, `[${timestamp}] ${levelText}: ${message}`);
82
+ })),
83
+ }));
84
+ }
49
85
  return winston.createLogger({
50
86
  levels: logging_1.logLevels,
51
87
  level,
52
- transports: [
53
- new winston.transports.File(Object.assign(Object.assign({}, this.loggerOptions), { filename: `${filePath}/${level}.log`, format: winston.format.combine(winston.format.timestamp(), winston.format.printf((info) => {
54
- // Apply minimal redaction for files (debugging info preserved)
55
- const redactedInfo = this.redact(info, false);
56
- return JSON.stringify(redactedInfo);
57
- })) })),
58
- new winston.transports.Console({
59
- format: winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => {
60
- // Apply full redaction for console (user-facing)
61
- const redactedInfo = this.redact(info, true);
62
- const colorizer = winston.format.colorize();
63
- const levelText = redactedInfo.level.toUpperCase();
64
- const { timestamp, message } = redactedInfo;
65
- return colorizer.colorize(redactedInfo.level, `[${timestamp}] ${levelText}: ${message}`);
66
- })),
67
- }),
68
- ],
88
+ transports,
69
89
  });
70
90
  }
71
91
  isSensitiveKey(keyStr, consoleMode = false) {
@@ -0,0 +1,125 @@
1
+ import SummaryManager from './summary-manager';
2
+ import { ProgressManagerOptions } from '../interfaces';
3
+ interface ProgressCallback {
4
+ onModuleStart?: (moduleName: string) => void;
5
+ onModuleComplete?: (moduleName: string, success: boolean, error?: string) => void;
6
+ onProgress?: (moduleName: string, success: boolean, itemName: string, error?: string) => void;
7
+ }
8
+ export default class CLIProgressManager {
9
+ private static globalSummary;
10
+ private showConsoleLogs;
11
+ private total;
12
+ private moduleName;
13
+ private enableNestedProgress;
14
+ private successCount;
15
+ private failureCount;
16
+ private failures;
17
+ private spinner;
18
+ private progressBar;
19
+ private processes;
20
+ private multiBar;
21
+ private currentProcess;
22
+ private callbacks;
23
+ private branchName;
24
+ constructor({ showConsoleLogs, total, moduleName, enableNestedProgress, }?: ProgressManagerOptions);
25
+ /**
26
+ * Initialize global summary manager for the entire operation
27
+ */
28
+ static initializeGlobalSummary(operationName: string, branchName: string, headerTitle?: string): SummaryManager;
29
+ /**
30
+ * Display operation header with branch information
31
+ */
32
+ static displayOperationHeader(branchName: string, headerTitle?: string): void;
33
+ /**
34
+ * Print the final summary for all modules using strategies
35
+ */
36
+ static printGlobalSummary(): void;
37
+ /**
38
+ * Check if there are any failures in the global summary
39
+ */
40
+ static hasFailures(): boolean;
41
+ /**
42
+ * Apply strategy-based corrections to module data
43
+ */
44
+ private static applyStrategyCorrections;
45
+ /**
46
+ * Clear global summary (for cleanup)
47
+ */
48
+ static clearGlobalSummary(): void;
49
+ /**
50
+ * Create a simple progress manager (no nested processes)
51
+ */
52
+ static createSimple(moduleName: string, total?: number, showConsoleLogs?: boolean): CLIProgressManager;
53
+ /**
54
+ * Create a nested progress manager (with sub-processes)
55
+ */
56
+ static createNested(moduleName: string, showConsoleLogs?: boolean): CLIProgressManager;
57
+ /**
58
+ * Show a loading spinner before initializing progress
59
+ */
60
+ static withLoadingSpinner<T>(message: string, asyncOperation: () => Promise<T>): Promise<T>;
61
+ private setupGlobalSummaryIntegration;
62
+ /**
63
+ * Register process data with summary manager for strategy calculations
64
+ */
65
+ private registerProcessDataWithSummary;
66
+ /**
67
+ * Set callbacks for external integration
68
+ */
69
+ setCallbacks(callbacks: ProgressCallback): void;
70
+ /**
71
+ * Convert module name from UPPERCASE to PascalCase
72
+ */
73
+ private formatModuleName;
74
+ /**
75
+ * Format process name with smart truncation (modules should use short names)
76
+ */
77
+ private formatProcessName;
78
+ /**
79
+ * Format percentage for consistent alignment (always 3 characters)
80
+ */
81
+ private formatPercentage;
82
+ private initializeProgress;
83
+ /**
84
+ * Add a new process to track (for nested progress)
85
+ */
86
+ addProcess(processName: string, total: number): this;
87
+ /**
88
+ * Update the total for a specific process (for dynamic totals after API calls)
89
+ */
90
+ updateProcessTotal(processName: string, newTotal: number): this;
91
+ /**
92
+ * Start a specific process
93
+ */
94
+ startProcess(processName: string): this;
95
+ /**
96
+ * Complete a specific process
97
+ */
98
+ completeProcess(processName: string, success?: boolean): this;
99
+ /**
100
+ * Update status message
101
+ */
102
+ updateStatus(message: string, processName?: string): this;
103
+ /**
104
+ * Update progress
105
+ */
106
+ tick(success?: boolean, itemName?: string, errorMessage?: string | null, processName?: string): this;
107
+ /**
108
+ * Complete the entire module
109
+ */
110
+ complete(success?: boolean, error?: string): this;
111
+ /**
112
+ * Log message (respects showConsoleLogs mode)
113
+ */
114
+ log(msg: string): void;
115
+ /**
116
+ * Stop all progress indicators
117
+ */
118
+ stop(): void;
119
+ private printSummary;
120
+ /**
121
+ * Get the current failure count
122
+ */
123
+ getFailureCount(): number;
124
+ }
125
+ export {};
@@ -0,0 +1,544 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
5
+ const ora_1 = tslib_1.__importDefault(require("ora"));
6
+ const cli_progress_1 = tslib_1.__importDefault(require("cli-progress"));
7
+ const summary_manager_1 = tslib_1.__importDefault(require("./summary-manager"));
8
+ const __1 = require("..");
9
+ const progress_strategy_1 = require("./progress-strategy");
10
+ class CLIProgressManager {
11
+ constructor({ showConsoleLogs = false, total = 0, moduleName = 'Module', enableNestedProgress = false, } = {}) {
12
+ this.showConsoleLogs = showConsoleLogs;
13
+ this.total = total;
14
+ this.moduleName = moduleName;
15
+ this.enableNestedProgress = enableNestedProgress;
16
+ this.successCount = 0;
17
+ this.failureCount = 0;
18
+ this.failures = [];
19
+ this.spinner = null;
20
+ this.progressBar = null;
21
+ this.processes = new Map();
22
+ this.multiBar = null;
23
+ this.currentProcess = null;
24
+ this.callbacks = {};
25
+ this.branchName = '';
26
+ this.initializeProgress();
27
+ this.setupGlobalSummaryIntegration();
28
+ }
29
+ /**
30
+ * Initialize global summary manager for the entire operation
31
+ */
32
+ static initializeGlobalSummary(operationName, branchName, headerTitle) {
33
+ var _a;
34
+ CLIProgressManager.globalSummary = new summary_manager_1.default({ operationName, context: { branchName } });
35
+ // Only show header if console logs are disabled (progress UI mode)
36
+ if (!((_a = __1.configHandler.get('log')) === null || _a === void 0 ? void 0 : _a.showConsoleLogs)) {
37
+ CLIProgressManager.displayOperationHeader(branchName, headerTitle);
38
+ }
39
+ return CLIProgressManager.globalSummary;
40
+ }
41
+ /**
42
+ * Display operation header with branch information
43
+ */
44
+ static displayOperationHeader(branchName, headerTitle) {
45
+ if (!headerTitle)
46
+ return;
47
+ const safeBranchName = branchName || 'main';
48
+ const branchInfo = headerTitle || `${safeBranchName === null || safeBranchName === void 0 ? void 0 : safeBranchName.toUpperCase()} CONTENT`;
49
+ console.log('\n' + chalk_1.default.bold('='.repeat(80)));
50
+ if (branchInfo) {
51
+ console.log(chalk_1.default.bold.white(` ${branchInfo}`));
52
+ }
53
+ console.log(chalk_1.default.bold('='.repeat(80)) + '\n');
54
+ }
55
+ /**
56
+ * Print the final summary for all modules using strategies
57
+ */
58
+ static printGlobalSummary() {
59
+ if (!CLIProgressManager.globalSummary) {
60
+ return;
61
+ }
62
+ // Apply strategy-based corrections before printing
63
+ CLIProgressManager.applyStrategyCorrections();
64
+ // Print the final summary
65
+ CLIProgressManager.globalSummary.printFinalSummary();
66
+ }
67
+ /**
68
+ * Check if there are any failures in the global summary
69
+ */
70
+ static hasFailures() {
71
+ if (!CLIProgressManager.globalSummary) {
72
+ return false;
73
+ }
74
+ return CLIProgressManager.globalSummary.hasFailures();
75
+ }
76
+ /**
77
+ * Apply strategy-based corrections to module data
78
+ */
79
+ static applyStrategyCorrections() {
80
+ if (!CLIProgressManager.globalSummary)
81
+ return;
82
+ const modules = Array.from(CLIProgressManager.globalSummary.getModules().values());
83
+ modules.forEach((module) => {
84
+ // Check if this module has a registered strategy
85
+ if (progress_strategy_1.ProgressStrategyRegistry.has(module.name)) {
86
+ const strategy = progress_strategy_1.ProgressStrategyRegistry.get(module.name);
87
+ // Create a processes map from module data if available
88
+ const processesMap = new Map();
89
+ // If module has process data, populate the map
90
+ if (module.processes && Array.isArray(module.processes)) {
91
+ module.processes.forEach((processData) => {
92
+ if (processData.processName) {
93
+ processesMap.set(processData.processName, processData);
94
+ }
95
+ });
96
+ }
97
+ // Calculate corrected progress using strategy
98
+ const correctedResult = strategy.calculate(processesMap);
99
+ if (correctedResult) {
100
+ // Update module with corrected counts
101
+ module.totalItems = correctedResult.total;
102
+ module.successCount = correctedResult.success;
103
+ module.failureCount = correctedResult.failures;
104
+ }
105
+ }
106
+ });
107
+ }
108
+ /**
109
+ * Clear global summary (for cleanup)
110
+ */
111
+ static clearGlobalSummary() {
112
+ CLIProgressManager.globalSummary = null;
113
+ }
114
+ /**
115
+ * Create a simple progress manager (no nested processes)
116
+ */
117
+ static createSimple(moduleName, total, showConsoleLogs = false) {
118
+ return new CLIProgressManager({
119
+ moduleName: moduleName.toUpperCase(),
120
+ total: total || 0,
121
+ showConsoleLogs,
122
+ enableNestedProgress: false,
123
+ });
124
+ }
125
+ /**
126
+ * Create a nested progress manager (with sub-processes)
127
+ */
128
+ static createNested(moduleName, showConsoleLogs = false) {
129
+ return new CLIProgressManager({
130
+ moduleName: moduleName.toUpperCase(),
131
+ total: 0,
132
+ showConsoleLogs,
133
+ enableNestedProgress: true,
134
+ });
135
+ }
136
+ /**
137
+ * Show a loading spinner before initializing progress
138
+ */
139
+ static async withLoadingSpinner(message, asyncOperation) {
140
+ const spinner = (0, ora_1.default)(message).start();
141
+ try {
142
+ const result = await asyncOperation();
143
+ spinner.stop();
144
+ return result;
145
+ }
146
+ catch (error) {
147
+ spinner.stop();
148
+ throw error;
149
+ }
150
+ }
151
+ setupGlobalSummaryIntegration() {
152
+ var _a, _b;
153
+ // Auto-register with global summary if it exists
154
+ if (CLIProgressManager.globalSummary) {
155
+ this.setCallbacks({
156
+ onModuleStart: (name) => {
157
+ var _a, _b;
158
+ (_a = CLIProgressManager.globalSummary) === null || _a === void 0 ? void 0 : _a.registerModule(name, this.total);
159
+ (_b = CLIProgressManager.globalSummary) === null || _b === void 0 ? void 0 : _b.startModule(name);
160
+ },
161
+ onModuleComplete: (name, success, error) => {
162
+ var _a;
163
+ // Register process data with summary manager before completing
164
+ this.registerProcessDataWithSummary(name);
165
+ (_a = CLIProgressManager.globalSummary) === null || _a === void 0 ? void 0 : _a.completeModule(name, success, error);
166
+ },
167
+ onProgress: (name, success, itemName, error) => {
168
+ var _a;
169
+ (_a = CLIProgressManager.globalSummary) === null || _a === void 0 ? void 0 : _a.updateModuleProgress(name, success, itemName, error);
170
+ },
171
+ });
172
+ // Trigger module start
173
+ (_b = (_a = this.callbacks).onModuleStart) === null || _b === void 0 ? void 0 : _b.call(_a, this.moduleName);
174
+ }
175
+ }
176
+ /**
177
+ * Register process data with summary manager for strategy calculations
178
+ */
179
+ registerProcessDataWithSummary(moduleName) {
180
+ if (!CLIProgressManager.globalSummary)
181
+ return;
182
+ // Register each process with the summary manager
183
+ this.processes.forEach((processData, processName) => {
184
+ var _a;
185
+ (_a = CLIProgressManager.globalSummary) === null || _a === void 0 ? void 0 : _a.registerProcessData(moduleName, processName, {
186
+ processName,
187
+ total: processData.total,
188
+ current: processData.current,
189
+ successCount: processData.successCount,
190
+ failureCount: processData.failureCount,
191
+ status: processData.status,
192
+ failures: processData.failures,
193
+ });
194
+ });
195
+ }
196
+ /**
197
+ * Set callbacks for external integration
198
+ */
199
+ setCallbacks(callbacks) {
200
+ this.callbacks = Object.assign(Object.assign({}, this.callbacks), callbacks);
201
+ }
202
+ /**
203
+ * Convert module name from UPPERCASE to PascalCase
204
+ */
205
+ formatModuleName(name) {
206
+ return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
207
+ }
208
+ /**
209
+ * Format process name with smart truncation (modules should use short names)
210
+ */
211
+ formatProcessName(processName) {
212
+ const cleaned = processName.trim();
213
+ if (cleaned.length <= 20) {
214
+ return cleaned;
215
+ }
216
+ return cleaned.length <= 20 ? cleaned : cleaned.substring(0, 20) + '...';
217
+ }
218
+ /**
219
+ * Format percentage for consistent alignment (always 3 characters)
220
+ */
221
+ formatPercentage(percentage) {
222
+ if (percentage === 100) {
223
+ return '100';
224
+ }
225
+ else if (percentage >= 10) {
226
+ return ` ${percentage}`;
227
+ }
228
+ else {
229
+ return ` ${percentage}`;
230
+ }
231
+ }
232
+ initializeProgress() {
233
+ if (this.showConsoleLogs) {
234
+ return;
235
+ }
236
+ if (this.enableNestedProgress) {
237
+ // Initialize multi-bar for nested progress tracking
238
+ this.multiBar = new cli_progress_1.default.MultiBar({
239
+ clearOnComplete: false,
240
+ hideCursor: true,
241
+ format: ' {label} |' + chalk_1.default.cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
242
+ barCompleteChar: '\u2588',
243
+ barIncompleteChar: '\u2591',
244
+ }, cli_progress_1.default.Presets.shades_classic);
245
+ if (!this.showConsoleLogs) {
246
+ console.log(chalk_1.default.bold.cyan(`\n${this.moduleName}:`));
247
+ }
248
+ }
249
+ else if (this.total > 0) {
250
+ if (!this.showConsoleLogs) {
251
+ console.log(chalk_1.default.bold.cyan(`\n${this.moduleName}:`));
252
+ }
253
+ this.progressBar = new cli_progress_1.default.SingleBar({
254
+ format: ' {label} |' + chalk_1.default.cyan('{bar}') + '| {percentage}% | {value}/{total} | {status}',
255
+ barCompleteChar: '\u2588',
256
+ barIncompleteChar: '\u2591',
257
+ hideCursor: true,
258
+ });
259
+ const formattedName = this.formatModuleName(this.moduleName);
260
+ const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
261
+ this.progressBar.start(this.total, 0, {
262
+ label: chalk_1.default.gray(` └─ ${displayName}`.padEnd(25)),
263
+ status: chalk_1.default.gray('Starting...'),
264
+ percentage: ' 0',
265
+ });
266
+ }
267
+ else {
268
+ this.spinner = (0, ora_1.default)(`${chalk_1.default.bold(this.moduleName)}: Processing...`).start();
269
+ }
270
+ }
271
+ /**
272
+ * Add a new process to track (for nested progress)
273
+ */
274
+ addProcess(processName, total) {
275
+ if (!this.enableNestedProgress)
276
+ return this;
277
+ const process = {
278
+ name: processName,
279
+ total,
280
+ current: 0,
281
+ status: 'pending',
282
+ successCount: 0,
283
+ failureCount: 0,
284
+ failures: [],
285
+ };
286
+ if (!this.showConsoleLogs && this.multiBar) {
287
+ const displayName = this.formatProcessName(processName);
288
+ const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
289
+ process.progressBar = this.multiBar.create(total, 0, {
290
+ label: chalk_1.default.gray(indentedLabel),
291
+ status: chalk_1.default.gray('Pending'),
292
+ percentage: ' 0',
293
+ });
294
+ }
295
+ this.processes.set(processName, process);
296
+ return this;
297
+ }
298
+ /**
299
+ * Update the total for a specific process (for dynamic totals after API calls)
300
+ */
301
+ updateProcessTotal(processName, newTotal) {
302
+ if (!this.enableNestedProgress)
303
+ return this;
304
+ const process = this.processes.get(processName);
305
+ if (process) {
306
+ process.total = newTotal;
307
+ if (process.progressBar && !this.showConsoleLogs) {
308
+ // Update the progress bar with the new total
309
+ process.progressBar.setTotal(newTotal);
310
+ }
311
+ }
312
+ return this;
313
+ }
314
+ /**
315
+ * Start a specific process
316
+ */
317
+ startProcess(processName) {
318
+ if (!this.enableNestedProgress)
319
+ return this;
320
+ const process = this.processes.get(processName);
321
+ if (process) {
322
+ process.status = 'active';
323
+ if (!this.showConsoleLogs && process.progressBar) {
324
+ const displayName = this.formatProcessName(processName);
325
+ const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
326
+ process.progressBar.update(0, {
327
+ label: chalk_1.default.yellow(indentedLabel),
328
+ status: chalk_1.default.yellow('Processing'),
329
+ percentage: ' 0',
330
+ });
331
+ }
332
+ this.currentProcess = processName;
333
+ }
334
+ return this;
335
+ }
336
+ /**
337
+ * Complete a specific process
338
+ */
339
+ completeProcess(processName, success = true) {
340
+ if (!this.enableNestedProgress)
341
+ return this;
342
+ const process = this.processes.get(processName);
343
+ if (process) {
344
+ process.status = success ? 'completed' : 'failed';
345
+ // If process completed without ticks, update current to reflect completion
346
+ if (process.current === 0 && process.total > 0) {
347
+ process.current = process.total;
348
+ if (process.status === 'completed') {
349
+ process.successCount = process.total;
350
+ }
351
+ }
352
+ if (!this.showConsoleLogs && process.progressBar) {
353
+ const totalProcessed = process.current;
354
+ const percentage = Math.round((totalProcessed / process.total) * 100);
355
+ const formattedPercentage = this.formatPercentage(percentage);
356
+ const statusText = success
357
+ ? chalk_1.default.green(`✓ Complete (${process.successCount}/${process.current})`)
358
+ : chalk_1.default.red(`✗ Failed (${process.successCount}/${process.current})`);
359
+ const displayName = this.formatProcessName(processName);
360
+ const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
361
+ process.progressBar.update(process.total, {
362
+ label: success ? chalk_1.default.green(indentedLabel) : chalk_1.default.red(indentedLabel),
363
+ status: statusText,
364
+ percentage: formattedPercentage,
365
+ });
366
+ }
367
+ }
368
+ return this;
369
+ }
370
+ /**
371
+ * Update status message
372
+ */
373
+ updateStatus(message, processName) {
374
+ if (!this.showConsoleLogs) {
375
+ if (this.enableNestedProgress && processName) {
376
+ const process = this.processes.get(processName);
377
+ if (process && process.progressBar) {
378
+ const percentage = Math.round((process.current / process.total) * 100);
379
+ const formattedPercentage = this.formatPercentage(percentage);
380
+ const displayName = this.formatProcessName(processName);
381
+ const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
382
+ process.progressBar.update(process.current, {
383
+ label: chalk_1.default.yellow(indentedLabel),
384
+ status: chalk_1.default.yellow(message),
385
+ percentage: formattedPercentage,
386
+ });
387
+ }
388
+ }
389
+ else if (this.progressBar) {
390
+ const percentage = Math.round(this.progressBar.getProgress() * 100);
391
+ const formattedPercentage = this.formatPercentage(percentage);
392
+ const formattedName = this.formatModuleName(this.moduleName);
393
+ const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
394
+ this.progressBar.update(this.progressBar.getProgress() * this.total, {
395
+ label: chalk_1.default.yellow(` └─ ${displayName}`.padEnd(25)),
396
+ status: chalk_1.default.yellow(message),
397
+ percentage: formattedPercentage,
398
+ });
399
+ }
400
+ else if (this.spinner) {
401
+ this.spinner.text = `${chalk_1.default.bold(this.moduleName)}: ${message}`;
402
+ }
403
+ }
404
+ return this;
405
+ }
406
+ /**
407
+ * Update progress
408
+ */
409
+ tick(success = true, itemName = '', errorMessage = null, processName) {
410
+ var _a, _b;
411
+ const targetProcess = processName || this.currentProcess;
412
+ if (success) {
413
+ this.successCount++;
414
+ }
415
+ else {
416
+ this.failureCount++;
417
+ this.failures.push({
418
+ item: itemName,
419
+ error: errorMessage,
420
+ process: targetProcess || undefined,
421
+ });
422
+ }
423
+ // Trigger callback
424
+ (_b = (_a = this.callbacks).onProgress) === null || _b === void 0 ? void 0 : _b.call(_a, this.moduleName, success, itemName, errorMessage || undefined);
425
+ // Update nested progress if enabled and console logs are disabled
426
+ if (this.enableNestedProgress && targetProcess) {
427
+ const process = this.processes.get(targetProcess);
428
+ if (process) {
429
+ process.current++;
430
+ if (success) {
431
+ process.successCount++;
432
+ }
433
+ else {
434
+ process.failureCount++;
435
+ process.failures.push({ item: itemName, error: errorMessage });
436
+ }
437
+ // Only update progress bar if console logs are disabled
438
+ if (!this.showConsoleLogs && process.progressBar) {
439
+ const percentage = Math.round((process.current / process.total) * 100);
440
+ const formattedPercentage = this.formatPercentage(percentage);
441
+ const statusText = `${process.successCount}✓ ${process.failureCount}✗`;
442
+ const displayName = this.formatProcessName(targetProcess);
443
+ const indentedLabel = ` ├─ ${displayName}`.padEnd(25);
444
+ process.progressBar.increment(1, {
445
+ label: chalk_1.default.cyan(indentedLabel),
446
+ status: chalk_1.default.cyan(statusText),
447
+ percentage: formattedPercentage,
448
+ });
449
+ }
450
+ }
451
+ }
452
+ else {
453
+ // Update single progress bar or spinner only if console logs are disabled
454
+ if (!this.showConsoleLogs) {
455
+ if (this.progressBar) {
456
+ const percentage = Math.round(((this.successCount + this.failureCount) / this.total) * 100);
457
+ const formattedPercentage = this.formatPercentage(percentage);
458
+ const totalProcessed = this.successCount + this.failureCount;
459
+ // Show completion status when finished, otherwise show running count
460
+ const statusText = totalProcessed >= this.total
461
+ ? this.failureCount === 0
462
+ ? chalk_1.default.green(`✓ Complete (${this.successCount}/${totalProcessed})`)
463
+ : chalk_1.default.yellow(`✓ Complete (${this.successCount}/${totalProcessed})`)
464
+ : chalk_1.default.cyan(`${this.successCount}✓ ${this.failureCount}✗`);
465
+ const labelColor = totalProcessed >= this.total ? (this.failureCount === 0 ? chalk_1.default.green : chalk_1.default.yellow) : chalk_1.default.cyan;
466
+ const formattedName = this.formatModuleName(this.moduleName);
467
+ const displayName = formattedName.length > 20 ? formattedName.substring(0, 17) + '...' : formattedName;
468
+ this.progressBar.increment(1, {
469
+ label: labelColor(` └─ ${displayName}`.padEnd(25)),
470
+ status: statusText,
471
+ percentage: formattedPercentage,
472
+ });
473
+ }
474
+ else if (this.spinner) {
475
+ const total = this.successCount + this.failureCount;
476
+ this.spinner.text = `${chalk_1.default.bold(this.moduleName)}: ${total} items (${this.successCount}✓ ${this.failureCount}✗)`;
477
+ }
478
+ }
479
+ }
480
+ return this;
481
+ }
482
+ /**
483
+ * Complete the entire module
484
+ */
485
+ complete(success = true, error) {
486
+ var _a, _b;
487
+ this.stop();
488
+ (_b = (_a = this.callbacks).onModuleComplete) === null || _b === void 0 ? void 0 : _b.call(_a, this.moduleName, success, error);
489
+ return this;
490
+ }
491
+ /**
492
+ * Log message (respects showConsoleLogs mode)
493
+ */
494
+ log(msg) {
495
+ if (this.showConsoleLogs) {
496
+ console.log(msg);
497
+ }
498
+ }
499
+ /**
500
+ * Stop all progress indicators
501
+ */
502
+ stop() {
503
+ // Stop progress bars if they were initialized
504
+ if (this.multiBar) {
505
+ this.multiBar.stop();
506
+ }
507
+ if (this.progressBar) {
508
+ this.progressBar.stop();
509
+ }
510
+ if (this.spinner) {
511
+ this.spinner.stop();
512
+ }
513
+ }
514
+ printSummary() {
515
+ if (!this.enableNestedProgress) {
516
+ // Simple summary for single progress
517
+ this.log('\n' + chalk_1.default.bold(`${this.moduleName} Summary:`));
518
+ this.log(`✓ Success: ${chalk_1.default.green(this.successCount)}`);
519
+ this.log(`✗ Failures: ${chalk_1.default.red(this.failureCount)}`);
520
+ return;
521
+ }
522
+ // Detailed summary for nested progress
523
+ this.log('\n' + chalk_1.default.bold(`${this.moduleName} Detailed Summary:`));
524
+ for (const [processName, process] of this.processes) {
525
+ const status = process.status === 'completed'
526
+ ? '✓'
527
+ : process.status === 'failed'
528
+ ? '✗'
529
+ : process.status === 'active'
530
+ ? '●'
531
+ : '○';
532
+ this.log(` ${status} ${processName}: ${process.successCount}✓ ${process.failureCount}✗ (${process.current}/${process.total})`);
533
+ }
534
+ this.log(`\nOverall: ${this.successCount}✓ ${this.failureCount}✗`);
535
+ }
536
+ /**
537
+ * Get the current failure count
538
+ */
539
+ getFailureCount() {
540
+ return this.failureCount;
541
+ }
542
+ }
543
+ exports.default = CLIProgressManager;
544
+ CLIProgressManager.globalSummary = null;
@@ -0,0 +1,4 @@
1
+ import SummaryManager from './summary-manager';
2
+ import CLIProgressManager from './cli-progress-manager';
3
+ import { PrimaryProcessStrategy, CustomProgressStrategy, ProgressStrategyRegistry, DefaultProgressStrategy } from './progress-strategy';
4
+ export { SummaryManager, CLIProgressManager, PrimaryProcessStrategy, CustomProgressStrategy, ProgressStrategyRegistry, DefaultProgressStrategy, };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DefaultProgressStrategy = exports.ProgressStrategyRegistry = exports.CustomProgressStrategy = exports.PrimaryProcessStrategy = exports.CLIProgressManager = exports.SummaryManager = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const summary_manager_1 = tslib_1.__importDefault(require("./summary-manager"));
6
+ exports.SummaryManager = summary_manager_1.default;
7
+ const cli_progress_manager_1 = tslib_1.__importDefault(require("./cli-progress-manager"));
8
+ exports.CLIProgressManager = cli_progress_manager_1.default;
9
+ const progress_strategy_1 = require("./progress-strategy");
10
+ Object.defineProperty(exports, "PrimaryProcessStrategy", { enumerable: true, get: function () { return progress_strategy_1.PrimaryProcessStrategy; } });
11
+ Object.defineProperty(exports, "CustomProgressStrategy", { enumerable: true, get: function () { return progress_strategy_1.CustomProgressStrategy; } });
12
+ Object.defineProperty(exports, "ProgressStrategyRegistry", { enumerable: true, get: function () { return progress_strategy_1.ProgressStrategyRegistry; } });
13
+ Object.defineProperty(exports, "DefaultProgressStrategy", { enumerable: true, get: function () { return progress_strategy_1.DefaultProgressStrategy; } });
@@ -0,0 +1,25 @@
1
+ import { ProcessProgress, ProgressResult } from '../interfaces';
2
+ export interface ProgressCalculationStrategy {
3
+ calculate(processes: Map<string, ProcessProgress>): ProgressResult | null;
4
+ }
5
+ export declare class DefaultProgressStrategy implements ProgressCalculationStrategy {
6
+ calculate(): ProgressResult | null;
7
+ }
8
+ export declare class PrimaryProcessStrategy implements ProgressCalculationStrategy {
9
+ private primaryProcessName;
10
+ constructor(primaryProcessName: string);
11
+ calculate(processes: Map<string, ProcessProgress>): ProgressResult | null;
12
+ }
13
+ export declare class CustomProgressStrategy implements ProgressCalculationStrategy {
14
+ private calculator;
15
+ constructor(calculator: (processes: Map<string, ProcessProgress>) => ProgressResult | null);
16
+ calculate(processes: Map<string, ProcessProgress>): ProgressResult | null;
17
+ }
18
+ export declare class ProgressStrategyRegistry {
19
+ private static strategies;
20
+ static register(moduleName: string, strategy: ProgressCalculationStrategy): void;
21
+ static get(moduleName: string): ProgressCalculationStrategy;
22
+ static clear(): void;
23
+ static has(moduleName: string): boolean;
24
+ static getAllRegistered(): string[];
25
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ProgressStrategyRegistry = exports.CustomProgressStrategy = exports.PrimaryProcessStrategy = exports.DefaultProgressStrategy = void 0;
4
+ class DefaultProgressStrategy {
5
+ calculate() {
6
+ return null; // Use default aggregated counting
7
+ }
8
+ }
9
+ exports.DefaultProgressStrategy = DefaultProgressStrategy;
10
+ class PrimaryProcessStrategy {
11
+ constructor(primaryProcessName) {
12
+ this.primaryProcessName = primaryProcessName;
13
+ }
14
+ calculate(processes) {
15
+ const primaryProcess = processes.get(this.primaryProcessName);
16
+ if (!primaryProcess)
17
+ return null;
18
+ return {
19
+ total: primaryProcess.total,
20
+ success: primaryProcess.successCount,
21
+ failures: primaryProcess.failureCount
22
+ };
23
+ }
24
+ }
25
+ exports.PrimaryProcessStrategy = PrimaryProcessStrategy;
26
+ class CustomProgressStrategy {
27
+ constructor(calculator) {
28
+ this.calculator = calculator;
29
+ }
30
+ calculate(processes) {
31
+ return this.calculator(processes);
32
+ }
33
+ }
34
+ exports.CustomProgressStrategy = CustomProgressStrategy;
35
+ // Registry
36
+ class ProgressStrategyRegistry {
37
+ static register(moduleName, strategy) {
38
+ this.strategies.set(moduleName.toUpperCase(), strategy);
39
+ }
40
+ static get(moduleName) {
41
+ return this.strategies.get(moduleName.toUpperCase()) || new DefaultProgressStrategy();
42
+ }
43
+ static clear() {
44
+ this.strategies.clear();
45
+ }
46
+ static has(moduleName) {
47
+ return this.strategies.has(moduleName.toUpperCase());
48
+ }
49
+ static getAllRegistered() {
50
+ return Array.from(this.strategies.keys());
51
+ }
52
+ }
53
+ exports.ProgressStrategyRegistry = ProgressStrategyRegistry;
54
+ ProgressStrategyRegistry.strategies = new Map();
@@ -0,0 +1,28 @@
1
+ import { ModuleResult, SummaryOptions } from '../interfaces/index';
2
+ export default class SummaryManager {
3
+ private modules;
4
+ private operationName;
5
+ private context;
6
+ private operationStartTime;
7
+ private branchName;
8
+ constructor({ operationName, context }: SummaryOptions);
9
+ getModules(): Map<string, ModuleResult>;
10
+ registerModule(moduleName: string, totalItems?: number): void;
11
+ startModule(moduleName: string): void;
12
+ completeModule(moduleName: string, success?: boolean, error?: string): void;
13
+ /**
14
+ * Register process data for strategy calculations
15
+ */
16
+ registerProcessData(moduleName: string, processName: string, processData: any): void;
17
+ updateModuleProgress(moduleName: string, success: boolean, itemName: string, error?: string): void;
18
+ printFinalSummary(): void;
19
+ /**
20
+ * Check if there are any failures across all modules
21
+ */
22
+ hasFailures(): boolean;
23
+ private printFailureSummaryWithLogReference;
24
+ private getStatusIcon;
25
+ private formatDuration;
26
+ private calculateSuccessRate;
27
+ private formatSuccessRate;
28
+ }
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
5
+ class SummaryManager {
6
+ constructor({ operationName, context }) {
7
+ this.modules = new Map();
8
+ this.operationName = operationName;
9
+ this.context = context;
10
+ this.operationStartTime = Date.now();
11
+ this.branchName = (context === null || context === void 0 ? void 0 : context.branchName) || '';
12
+ }
13
+ getModules() {
14
+ return this.modules;
15
+ }
16
+ registerModule(moduleName, totalItems = 0) {
17
+ this.modules.set(moduleName, {
18
+ name: moduleName,
19
+ status: 'pending',
20
+ totalItems,
21
+ successCount: 0,
22
+ failureCount: 0,
23
+ failures: [],
24
+ processes: [],
25
+ });
26
+ }
27
+ startModule(moduleName) {
28
+ const module = this.modules.get(moduleName);
29
+ if (module) {
30
+ module.status = 'running';
31
+ module.startTime = Date.now();
32
+ }
33
+ }
34
+ completeModule(moduleName, success = true, error) {
35
+ const module = this.modules.get(moduleName);
36
+ if (module) {
37
+ module.status = success ? 'completed' : 'failed';
38
+ module.endTime = Date.now();
39
+ if (!success && error) {
40
+ module.failures.push({ item: 'module', error });
41
+ }
42
+ }
43
+ }
44
+ /**
45
+ * Register process data for strategy calculations
46
+ */
47
+ registerProcessData(moduleName, processName, processData) {
48
+ const module = this.modules.get(moduleName);
49
+ if (module) {
50
+ if (!module.processes) {
51
+ module.processes = [];
52
+ }
53
+ const existingIndex = module.processes.findIndex((p) => p.processName === processName);
54
+ if (existingIndex >= 0) {
55
+ module.processes[existingIndex] = Object.assign({ processName }, processData);
56
+ }
57
+ else {
58
+ module.processes.push(Object.assign({ processName }, processData));
59
+ }
60
+ }
61
+ }
62
+ updateModuleProgress(moduleName, success, itemName, error) {
63
+ const module = this.modules.get(moduleName);
64
+ if (module) {
65
+ if (success) {
66
+ module.successCount++;
67
+ }
68
+ else {
69
+ module.failureCount++;
70
+ if (error) {
71
+ module.failures.push({ item: itemName, error });
72
+ }
73
+ }
74
+ }
75
+ }
76
+ printFinalSummary() {
77
+ const operationEndTime = Date.now();
78
+ const totalDuration = operationEndTime - this.operationStartTime;
79
+ // Overall Statistics
80
+ const totalModules = this.modules.size;
81
+ const completedModules = Array.from(this.modules.values()).filter((m) => m.status === 'completed').length;
82
+ const failedModules = Array.from(this.modules.values()).filter((m) => m.status === 'failed').length;
83
+ const totalItems = Array.from(this.modules.values()).reduce((sum, m) => sum + m.successCount + m.failureCount, 0);
84
+ const totalSuccess = Array.from(this.modules.values()).reduce((sum, m) => sum + m.successCount, 0);
85
+ 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))}%`);
93
+ // Module Details
94
+ console.log('\n' + chalk_1.default.bold('Module Details:'));
95
+ console.log(chalk_1.default.gray('-'.repeat(80)));
96
+ Array.from(this.modules.values()).forEach((module) => {
97
+ const status = this.getStatusIcon(module.status);
98
+ const totalCount = module.successCount + module.failureCount;
99
+ const duration = module.endTime && module.startTime ? this.formatDuration(module.endTime - module.startTime) : 'N/A';
100
+ const successRate = this.calculateSuccessRate(module.successCount, totalCount);
101
+ console.log(`${status} ${module.name.padEnd(20)} | ` +
102
+ `${String(module.successCount).padStart(4)}/${String(totalCount).padStart(4)} items | ` +
103
+ `${this.formatSuccessRate(successRate).padStart(6)} | ` +
104
+ `${duration.padStart(8)}`);
105
+ });
106
+ // Final Status
107
+ console.log('\n' + chalk_1.default.bold('Final Status:'));
108
+ if (!this.hasFailures() && failedModules === 0) {
109
+ console.log(chalk_1.default.bold.green(`✅ ${this.operationName} completed successfully!`));
110
+ }
111
+ 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.`));
113
+ }
114
+ else {
115
+ console.log(chalk_1.default.bold.red(`❌ ${this.operationName} failed`));
116
+ }
117
+ console.log(chalk_1.default.bold('='.repeat(80)));
118
+ console.log(chalk_1.default.bold('='.repeat(80)));
119
+ // Simple failure summary with log reference
120
+ this.printFailureSummaryWithLogReference();
121
+ }
122
+ /**
123
+ * Check if there are any failures across all modules
124
+ */
125
+ hasFailures() {
126
+ return Array.from(this.modules.values()).some((m) => m.failures.length > 0 || m.failureCount > 0);
127
+ }
128
+ printFailureSummaryWithLogReference() {
129
+ const modulesWithFailures = Array.from(this.modules.values()).filter((m) => m.failures.length > 0);
130
+ if (modulesWithFailures.length === 0)
131
+ return;
132
+ 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)));
135
+ 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`);
137
+ // Show just first 2-3 failures briefly
138
+ const preview = module.failures.slice(0, 2);
139
+ preview.forEach((failure) => {
140
+ console.log(` • ${chalk_1.default.gray(failure.item)}`);
141
+ });
142
+ if (module.failures.length > 2) {
143
+ console.log(` ${chalk_1.default.gray(`... and ${module.failures.length - 2} more`)}`);
144
+ }
145
+ });
146
+ console.log(chalk_1.default.blue('\n📋 For detailed error information, check the log files:'));
147
+ //console.log(chalk.blue(` ${getLogPath()}`));
148
+ console.log(chalk_1.default.gray(' Recent errors are logged with full context and stack traces.'));
149
+ }
150
+ getStatusIcon(status) {
151
+ switch (status) {
152
+ case 'completed':
153
+ return chalk_1.default.green('✓');
154
+ case 'failed':
155
+ return chalk_1.default.red('✗');
156
+ case 'running':
157
+ return chalk_1.default.yellow('●');
158
+ case 'pending':
159
+ return chalk_1.default.gray('○');
160
+ default:
161
+ return chalk_1.default.gray('?');
162
+ }
163
+ }
164
+ formatDuration(ms) {
165
+ if (ms < 1000)
166
+ return `${ms}ms`;
167
+ if (ms < 60000)
168
+ return `${(ms / 1000).toFixed(1)}s`;
169
+ return `${(ms / 60000).toFixed(1)}m`;
170
+ }
171
+ calculateSuccessRate(success, total) {
172
+ if (total === 0)
173
+ return '0';
174
+ return ((success / total) * 100).toFixed(1);
175
+ }
176
+ formatSuccessRate(rate) {
177
+ if (rate === '100.0') {
178
+ return '100%';
179
+ }
180
+ else if (parseFloat(rate) >= 10) {
181
+ return `${rate}%`;
182
+ }
183
+ else {
184
+ return ` ${rate}%`;
185
+ }
186
+ }
187
+ }
188
+ exports.default = SummaryManager;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contentstack/cli-utilities",
3
- "version": "1.17.1",
3
+ "version": "1.17.2",
4
4
  "description": "Utilities for contentstack projects",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",