diff --git a/src/commands/action-flows/module.ts b/src/commands/action-flows/module.ts index ea9d280e..b08f33e5 100644 --- a/src/commands/action-flows/module.ts +++ b/src/commands/action-flows/module.ts @@ -10,7 +10,7 @@ import { SkillCommandService } from "./skill/skill-command.service"; class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const analyzeCommand = configurator.command("analyze"); analyzeCommand.command("action-flows") .description("Analyze Action Flows dependencies for a certain package") diff --git a/src/commands/analysis/analysis-bookmarks.manager.ts b/src/commands/analysis/analysis-bookmarks.manager.ts index 98abfb76..a1d0297d 100644 --- a/src/commands/analysis/analysis-bookmarks.manager.ts +++ b/src/commands/analysis/analysis-bookmarks.manager.ts @@ -45,7 +45,7 @@ export class AnalysisBookmarksManager extends BaseManager { return { pushUrl: `${AnalysisBookmarksManager.BASE_URL}/import?analysisId=${this.analysisId}`, pullUrl: pullUrl, - exportFileName: `${AnalysisBookmarksManager.ANALYSIS_BOOKMARKS_FILE_PREFIX}${this.analysisId}${".json"}`, + exportFileName: `${AnalysisBookmarksManager.ANALYSIS_BOOKMARKS_FILE_PREFIX}${this.analysisId}.json`, onPushSuccessMessage: (): string => { return "Analysis Bookmarks was pushed successfully."; }, diff --git a/src/commands/analysis/module.ts b/src/commands/analysis/module.ts index 1fff2514..8671e330 100644 --- a/src/commands/analysis/module.ts +++ b/src/commands/analysis/module.ts @@ -9,7 +9,7 @@ import { AnalysisBookmarksCommandService } from "./analysis-bookmarks-command.se class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const pullCommand = configurator.command("pull"); pullCommand.command("bookmarks") .description("Command to pull an analysis bookmarks") diff --git a/src/commands/cpm4/module.ts b/src/commands/cpm4/module.ts index 6bdd552b..4fc87387 100644 --- a/src/commands/cpm4/module.ts +++ b/src/commands/cpm4/module.ts @@ -9,7 +9,7 @@ import { CTPCommandService } from "./ctp-command.service"; class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const pushCommand = configurator.command("push") pushCommand.command("ctp") .description("Command to push a .ctp (Celonis 4 transport file) to create a package") diff --git a/src/commands/data-pipeline/connection/connection.commands.ts b/src/commands/data-pipeline/connection/connection.commands.ts index 8584cc29..98c44d23 100644 --- a/src/commands/data-pipeline/connection/connection.commands.ts +++ b/src/commands/data-pipeline/connection/connection.commands.ts @@ -9,7 +9,7 @@ import { Context } from "../../../core/command/cli-context"; export class ConnectionCommands { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const listCommand = configurator.command("list"); listCommand.command("connection") .description("Command to list all connections in a Data Pool") @@ -33,15 +33,15 @@ export class ConnectionCommands { .action(this.updateConnectionProperty); } - async getCommandProperties(context: Context, command: Command, options: OptionValues) { + private async getCommandProperties(context: Context, command: Command, options: OptionValues): Promise { await new ConnectionCommandService(context).getProperties(options.dataPoolId, options.connectionId); } - async listConnections(context: Context, command: Command, options: OptionValues) { + private async listConnections(context: Context, command: Command, options: OptionValues): Promise { await new ConnectionCommandService(context).listConnections(options.dataPoolId); } - async updateConnectionProperty(context: Context, command: Command, options: OptionValues) { + private async updateConnectionProperty(context: Context, command: Command, options: OptionValues): Promise { await new ConnectionCommandService(context).updateProperty(options.dataPoolId, options.connectionId, options.property, options.value); } } diff --git a/src/commands/data-pipeline/connection/connection.service.ts b/src/commands/data-pipeline/connection/connection.service.ts index 79165d22..422dcdb7 100644 --- a/src/commands/data-pipeline/connection/connection.service.ts +++ b/src/commands/data-pipeline/connection/connection.service.ts @@ -23,10 +23,10 @@ export class ConnectionService { const type = connection.type; const typedConnection = await this.dataPoolApi.getTypedConnection(dataPoolId, connectionId, type); logger.info(`Connection ID: ${connection.id} - Name: ${connection.name} - Type: ${connection.type}`); - logger.info(`Properties:`) - for (let k in typedConnection) { - if (typeof typedConnection[k] === 'object') { - for (let o in typedConnection[k]) { + logger.info("Properties:") + for (const k in typedConnection) { + if (typeof typedConnection[k] === "object") { + for (const o in typedConnection[k]) { logger.info(` ${k}.${o} : ${typeof typedConnection[k][o]} := ${typedConnection[k][o]}`) } } else { @@ -36,7 +36,7 @@ export class ConnectionService { return typedConnection; } - public async updateProperty(dataPoolId: string, connectionId: string, property: string, value: string) { + public async updateProperty(dataPoolId: string, connectionId: string, property: string, value: string): Promise { const connection = await this.dataPoolApi.getConnection(dataPoolId, connectionId); const type = connection.type; const typedConnection = await this.dataPoolApi.getTypedConnection(dataPoolId, connectionId, type); diff --git a/src/commands/data-pipeline/data-pool/data-pool-command.service.ts b/src/commands/data-pipeline/data-pool/data-pool-command.service.ts index 080ac7d9..722eff8e 100644 --- a/src/commands/data-pipeline/data-pool/data-pool-command.service.ts +++ b/src/commands/data-pipeline/data-pool/data-pool-command.service.ts @@ -2,7 +2,6 @@ import { ContentService } from "../../../core/http/http-shared/content.service"; import { DataPoolManagerFactory } from "./data-pool-manager.factory"; import { Context } from "../../../core/command/cli-context"; import { DataPoolService } from "./data-pool-service"; -import { logger } from "../../../core/utils/logger"; export class DataPoolCommandService { private contentService = new ContentService(); diff --git a/src/commands/data-pipeline/data-pool/data-pool-manager.interfaces.ts b/src/commands/data-pipeline/data-pool/data-pool-manager.interfaces.ts index 71c00bff..14929380 100644 --- a/src/commands/data-pipeline/data-pool/data-pool-manager.interfaces.ts +++ b/src/commands/data-pipeline/data-pool/data-pool-manager.interfaces.ts @@ -2,10 +2,10 @@ export declare type DataPoolStatus = "CANCEL" | "FAIL" | "QUEUED" | "RUNNING" | export type Tag = {}; export declare class DataSourceSlimTransport { - id: string; - name: string; - imported: boolean; - importedPoolId: string; + public id: string; + public name: string; + public imported: boolean; + public importedPoolId: string; } export interface DataPoolSlimTransport { @@ -19,12 +19,12 @@ export interface DataPoolSlimTransport { dataSources: DataSourceSlimTransport[]; } export declare class DataPoolPageTransport { - content: DataPoolSlimTransport[]; - pageSize: number; - pageNumber: number; - totalCount: number; + public content: DataPoolSlimTransport[]; + public pageSize: number; + public pageNumber: number; + public totalCount: number; } export declare class DataPoolInstallVersionReport { - dataModelIdMappings: Map; + public dataModelIdMappings: Map; } diff --git a/src/commands/data-pipeline/data-pool/data-pool.commands.ts b/src/commands/data-pipeline/data-pool/data-pool.commands.ts index f5cb462b..15c401fd 100644 --- a/src/commands/data-pipeline/data-pool/data-pool.commands.ts +++ b/src/commands/data-pipeline/data-pool/data-pool.commands.ts @@ -8,7 +8,7 @@ import { DataPoolCommandService } from "./data-pool-command.service"; export class DataPoolCommands { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const exportCommand = configurator.command("export"); exportCommand.command("data-pool") .description("Command to export a data pool") @@ -53,31 +53,31 @@ export class DataPoolCommands { .action(this.updateDataPool); } - async exportDataPool(context: Context, command: Command, options: OptionValues) { + private async exportDataPool(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).exportDataPool(options.id, options.outputToJsonFile); } - async batchImportDataPools(context: Context, command: Command, options: OptionValues) { + private async batchImportDataPools(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).batchImportDataPools(options.jsonFile, options.outputToJsonFile); } - async listDataPools(context: Context, command: Command, options: OptionValues) { + private async listDataPools(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).listDataPools(options.json); } - async pullDataPool(context: Context, command: Command, options: OptionValues) { + private async pullDataPool(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).pullDataPool(options.id); } - async pushDataPool(context: Context, command: Command, options: OptionValues) { + private async pushDataPool(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).pushDataPool(options.file); } - async pushDataPools(context: Context, command: Command, options: OptionValues) { + private async pushDataPools(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).pushDataPools(); } - async updateDataPool(context: Context, command: Command, options: OptionValues) { + private async updateDataPool(context: Context, command: Command, options: OptionValues): Promise { await new DataPoolCommandService(context).updateDataPool(options.id, options.file); } } diff --git a/src/commands/data-pipeline/module.ts b/src/commands/data-pipeline/module.ts index 3d0ef319..6b011ea8 100644 --- a/src/commands/data-pipeline/module.ts +++ b/src/commands/data-pipeline/module.ts @@ -9,7 +9,7 @@ import { DataPoolCommands } from "./data-pool/data-pool.commands"; class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { new DataPoolCommands().register(context, configurator); new ConnectionCommands().register(context, configurator); } diff --git a/src/commands/profile/module.ts b/src/commands/profile/module.ts index ae346abb..5f8c07a9 100644 --- a/src/commands/profile/module.ts +++ b/src/commands/profile/module.ts @@ -10,7 +10,7 @@ import { ProfileCommandService } from "./profile-command.service"; class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const command = configurator.command("profile") .description("Manage profiles required to access a system."); @@ -28,17 +28,17 @@ class Module extends IModule { .action(this.defaultProfile); } - async defaultProfile(context: Context, command: Command) { - let profile = command.args[0]; + private async defaultProfile(context: Context, command: Command): Promise { + const profile = command.args[0]; await new ProfileCommandService().makeDefaultProfile(profile); } - async createProfile(context: Context, command: Command, options: OptionValues) { + private async createProfile(context: Context, command: Command, options: OptionValues): Promise { await new ProfileCommandService().createProfile(options.setAsDefault); } - async listProfiles(context: Context, command: Command) { - logger.debug(`List profiles`); + private async listProfiles(context: Context, command: Command): Promise { + logger.debug("List profiles"); await new ProfileCommandService().listProfiles(); } } diff --git a/src/commands/studio/api/studio-variables-api.ts b/src/commands/studio/api/studio-variables-api.ts index c08a79ae..51833fc2 100644 --- a/src/commands/studio/api/studio-variables-api.ts +++ b/src/commands/studio/api/studio-variables-api.ts @@ -20,7 +20,7 @@ export class StudioVariablesApi { }); } - public getRuntimeVariableValues(packageKey: string, appMode: string): Promise { + public async getRuntimeVariableValues(packageKey: string, appMode: string): Promise { const queryParams = new URLSearchParams(); queryParams.set("appMode", appMode); diff --git a/src/commands/studio/module.ts b/src/commands/studio/module.ts index b5014ba8..8807c996 100644 --- a/src/commands/studio/module.ts +++ b/src/commands/studio/module.ts @@ -12,7 +12,7 @@ import { SpaceCommandService } from "./command-service/space-command.service"; class Module extends IModule { - register(context: Context, configurator: Configurator) { + public register(context: Context, configurator: Configurator): void { const exportCommand = configurator.command("export"); exportCommand.command("packages") .description("Command to export all given packages") diff --git a/src/commands/studio/service/package.service.ts b/src/commands/studio/service/package.service.ts index 6ffae206..6fef2d77 100644 --- a/src/commands/studio/service/package.service.ts +++ b/src/commands/studio/service/package.service.ts @@ -278,7 +278,7 @@ export class PackageService { continue; } - const dependentPackage = manifestNodes.find((node) => node.packageKey === dependency.key); + const dependentPackage = manifestNodes.find(node => node.packageKey === dependency.key); await this.importPackage(dependentPackage, manifestNodes, sourceToTargetVersionsByNodeKey, spaceMappings, dmTargetIdsBySourceIds, importedVersionsByNodeKey, draftIdsByPackageKeyAndVersion, importedFilePath, excludeActionFlows); } } @@ -298,7 +298,7 @@ export class PackageService { } private async getTargetSpaceForExportedPackage(packageToImport: ManifestNodeTransport, spaceMappings: Map): Promise { - let targetSpace; + let targetSpace: SpaceTransport; const allSpaces = await this.spaceService.refreshAndGetAllSpaces(); if (spaceMappings.has(packageToImport.packageKey)) { const customSpaceId = spaceMappings.get(packageToImport.packageKey); @@ -408,8 +408,7 @@ export class PackageService { } public async getPackagesWithDependencies(draftIdByNodeId: Map): Promise> { - const allPackageDependencies: Map = await this.packageDependenciesApi.findPackageDependenciesByIds(draftIdByNodeId); - return allPackageDependencies; + return await this.packageDependenciesApi.findPackageDependenciesByIds(draftIdByNodeId); } private async getDependencyPackages(nodesToResolve: BatchExportNodeTransport[], dependencyPackages: BatchExportNodeTransport[], allPackages: ContentNodeTransport[], resolvedDependencies: string[], versionsByNodeKey: Map): Promise { @@ -499,7 +498,7 @@ export class PackageService { private exportManifestOfPackages(nodes: BatchExportNodeTransport[], dependencyVersionsByNodeKey: Map): ManifestNodeTransport[] { const manifestNodesByPackageKey = new Map(); - nodes.forEach((node) => { + nodes.forEach(node => { const manifestNode = manifestNodesByPackageKey.get(node.key) ?? {} as ManifestNodeTransport; manifestNode.packageKey = node.key; manifestNode.packageId = node.id; @@ -507,7 +506,7 @@ export class PackageService { spaceName: node.space.name, spaceIcon: node.space.iconReference } - manifestNode.variables = node.variables?.map((variable) => { + manifestNode.variables = node.variables?.map(variable => { if (variable.type === PackageManagerVariableType.DATA_MODEL) { // @ts-ignore const dataModel = node.datamodels?.find(dataModel => dataModel.dataModelId === variable.value); diff --git a/src/content-cli.ts b/src/content-cli.ts index 3d4b6d68..3bf4cd41 100644 --- a/src/content-cli.ts +++ b/src/content-cli.ts @@ -38,7 +38,7 @@ if (!program.opts().quietmode) { if (program.opts().debug) { logger.transports.forEach(t => { - t.level = 'debug'; + t.level = "debug"; }); } @@ -46,17 +46,17 @@ if (program.opts().debug) { * To support the legacy command structure, we have to configure some root commands * that the individual modules will extend. */ -function configureRootCommands(configurator: Configurator) { +function configureRootCommands(configurator: Configurator): void { configurator.command("list") .description("Commands to list content.") .alias("ls"); } -async function run() { - let context = new Context(program.opts()); +async function run(): Promise { + const context = new Context(program.opts()); await context.init(); - let moduleHandler = new ModuleHandler(program, context); + const moduleHandler = new ModuleHandler(program, context); configureRootCommands(moduleHandler.configurator); @@ -65,16 +65,16 @@ async function run() { try { program.parse(process.argv); } catch (error) { - logger.error(`An unexpected error occured: ${error}`); + logger.error(`An unexpected error occurred: ${error}`); } } run(); // catch uncaught exceptions -process.on('uncaughtException', (error: Error, origin: NodeJS.UncaughtExceptionOrigin) => { - console.error(`\n💥 UNCAUGHT EXCEPTION!\n`); - console.error('Error:', error); - console.error('Origin:', origin); +process.on("uncaughtException", (error: Error, origin: NodeJS.UncaughtExceptionOrigin) => { + console.error("\n💥 UNCAUGHT EXCEPTION!\n"); + console.error("Error:", error); + console.error("Origin:", origin); process.exit(1); }); \ No newline at end of file diff --git a/src/core/command/module-handler.ts b/src/core/command/module-handler.ts index b6ac6a4d..c81e4aff 100644 --- a/src/core/command/module-handler.ts +++ b/src/core/command/module-handler.ts @@ -5,27 +5,23 @@ import { Context } from "./cli-context"; import { logger } from "../utils/logger"; export abstract class IModule { - abstract register(context: Context, commandConfig: Configurator); - - showHelp(context: Context, command: Command) { - command.outputHelp(); - } + public abstract register(context: Context, commandConfig: Configurator): void; } -export interface IModuleConstructor { - new(): IModule; -} +export type IModuleConstructor = new () => IModule; export class ModuleHandler { - public configurator: Configurator; - constructor(public program: Command, public context: Context) { + constructor( + public program: Command, + public context: Context + ) { this.configurator = new Configurator(this.program, this.context); } // Store registered module instances if needed later - registeredModules: IModule[] = []; + public registeredModules: IModule[] = []; /** * Discovers modules in the specified directory, imports them, @@ -34,8 +30,8 @@ export class ModuleHandler { * @param {any} rootPath - __dirname when invoked from the main entry file * @param devMode - Use uncompiled modules for development debug mode */ - discoverAndRegisterModules(rootPath, devMode = false) { - let modulesDirPath = path.resolve(rootPath, "commands"); + public discoverAndRegisterModules(rootPath: string, devMode: boolean = false): void { + const modulesDirPath = path.resolve(rootPath, "commands"); try { const moduleFolders = fs.readdirSync(modulesDirPath, { withFileTypes: true }); @@ -47,9 +43,11 @@ export class ModuleHandler { const moduleFileName = devMode ? "module.ts" : "module.js"; // Calculate path relative to *this file's location in dist* - let potentialModuleJsPath; + let potentialModuleJsPath: any; potentialModuleJsPath = path.resolve( - rootPath, 'commands', moduleFolderName, + rootPath, + "commands", + moduleFolderName, moduleFileName // Look for the compiled JS file ); try { @@ -60,9 +58,10 @@ export class ModuleHandler { } if (!potentialModuleJsPath) { - logger.debug(`Module folder ${moduleFolderName} does not contain a valid entry point and is skipped.`); + logger.debug( + `Module folder ${moduleFolderName} does not contain a valid entry point and is skipped.` + ); } else { - // Check if the compiled JS file exists try { logger.debug(`Found potential module definition: ${potentialModuleJsPath}`); @@ -74,15 +73,14 @@ export class ModuleHandler { const ModuleClass = requiredModule as IModuleConstructor; // Cast for TS check // Basic check: Is it a class (function)? - if (typeof ModuleClass === 'function' && ModuleClass.prototype) { + if (typeof ModuleClass === "function" && ModuleClass.prototype) { const moduleInstance: IModule = new ModuleClass(); // Instantiate // Check if the instance has the register method - if (typeof moduleInstance.register === 'function') { + if (typeof moduleInstance.register === "function") { logger.debug(`Registering module: ${moduleFolderName}`); // Call register - can still be async even if require() is sync - let ctx = this.context; - moduleInstance.register(ctx, this.configurator); + moduleInstance.register(this.context, this.configurator); this.registeredModules.push(moduleInstance); } else { logger.warn(`Module ${moduleFolderName} export does not have a 'register' method.`); @@ -90,16 +88,18 @@ export class ModuleHandler { } else { logger.warn(`Module ${moduleFolderName} export is not a class/constructor function.`); } - } catch (error: any) { - if (error.code === 'ENOENT') { + if (error.code === "ENOENT") { // Compiled module.js not found, maybe folder doesn't contain a valid module - logger.warn(`Directory ${moduleFolderName} does not contain a compiled module.js file.`); - } else if (error.code === 'MODULE_NOT_FOUND') { - logger.debug(`Error details`, error); - logger.warn(`Could not require module ${moduleFolderName}. Check dependencies or compilation. Path: ${potentialModuleJsPath}`); - } - else { + logger.warn( + `Directory ${moduleFolderName} does not contain a compiled module.js file.` + ); + } else if (error.code === "MODULE_NOT_FOUND") { + logger.debug("Error details", error); + logger.warn( + `Could not require module ${moduleFolderName}. Check dependencies or compilation. Path: ${potentialModuleJsPath}` + ); + } else { logger.error(`Error processing module in ${moduleFolderName}:`, error); } } @@ -107,45 +107,45 @@ export class ModuleHandler { } } } catch (error: any) { - if (error.code === 'ENOENT') { - logger.error(`Modules directory not found relative to JS output: ${path.resolve(path.dirname(__filename), "commands")}`); + if (error.code === "ENOENT") { + logger.error( + `Modules directory not found relative to JS output: ${path.resolve(path.dirname(__filename), "commands")}` + ); } else { - logger.error('Failed to read modules directory:', error); + logger.error("Failed to read modules directory:", error); } } logger.debug(`Module discovery complete. ${this.registeredModules.length} modules registered.`); } - } -type CommandHandler = (context: Context, command: Command, options: OptionValues) => void; +type CommandHandler = (context: Context, command: Command, options: OptionValues) => Promise; /** * Allows the creation of root level commands. */ export class Configurator { + public rootCommandMap = new Map(); - rootCommandMap = new Map(); - - constructor(private program: Command, private ctx: Context) { - - } + constructor( + private program: Command, + private ctx: Context + ) {} /** * Get or create a root level command. * @param name - * @returns + * @returns */ - command(name: string) : CommandConfig { + public command(name: string): CommandConfig { if (this.rootCommandMap.has(name)) { return this.rootCommandMap.get(name); } - let cmd = this.program.command(name); - let cmdConfig = new CommandConfig(cmd, this.ctx); + const cmd = this.program.command(name); + const cmdConfig = new CommandConfig(cmd, this.ctx); this.rootCommandMap.set(name, cmdConfig); return cmdConfig; } - } /** @@ -153,51 +153,48 @@ export class Configurator { * executed. */ export class CommandConfig { - constructor(private cmd: Command, private ctx: Context) { - } + constructor( + private cmd: Command, + private ctx: Context + ) {} public command(nameAndArgs: string, opts?: CommandOptions): CommandConfig { return new CommandConfig(this.cmd.command(nameAndArgs, opts), this.ctx) .option("-p, --profile ", "Profile which you want to use"); } - alias(alias: string) { + public alias(alias: string): CommandConfig { this.cmd.alias(alias); return this; } - description(description: string) { + public description(description: string): CommandConfig { this.cmd.description(description); return this; } - argument(name: string, description?: string, defaultValue?: unknown): this { + public argument(name: string, description?: string, defaultValue?: unknown): CommandConfig { this.cmd.argument(name, description, defaultValue); return this; } - option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this { + public option(flags: string, description?: string, defaultValue?: string | boolean | string[]): CommandConfig { this.cmd.option(flags, description, defaultValue); return this; } - requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this { + public requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): CommandConfig { this.cmd.requiredOption(flags, description, defaultValue); return this; } - action(handler: CommandHandler) { - let ctx = this.ctx; - this.cmd.action(async function () { + public action(handler: CommandHandler): void { + this.cmd.action(async (): Promise => { try { - let cmd = this; // in the context of the execution, this refers to the Command object - let cmdOptions = cmd.opts(); - await handler(ctx, this, cmdOptions); + await handler(this.ctx, this.cmd, this.cmd.opts()); } catch (error) { logger.error(`An unexpected error occured executing a command: ${error}`); } - }) + }); } - } - diff --git a/src/core/http/base-api.ts b/src/core/http/base-api.ts index e33245da..dd47bfa0 100644 --- a/src/core/http/base-api.ts +++ b/src/core/http/base-api.ts @@ -6,9 +6,9 @@ import { logger } from "../utils/logger"; import { HttpClient } from "./http-client"; export class ForbiddenError extends Error { - constructor(message = 'Access Forbidden') { + constructor(message: string = "Access Forbidden") { super(message); - this.name = 'ForbiddenError'; + this.name = "ForbiddenError"; // Maintains proper stack trace in V8 environments (Node, Chrome) if (Error.captureStackTrace) { Error.captureStackTrace(this, ForbiddenError); @@ -18,9 +18,9 @@ export class ForbiddenError extends Error { // Custom error for Server (5xx) responses. export class ServerError extends Error { - constructor(message = 'Internal Server Error') { + constructor(message: string = "Internal Server Error") { super(message); - this.name = 'ServerError'; + this.name = "ServerError"; if (Error.captureStackTrace) { Error.captureStackTrace(this, ServerError); } @@ -29,9 +29,9 @@ export class ServerError extends Error { // Custom error for Not Found (404) responses. export class NotFoundError extends Error { - constructor(message = 'Resource Not Found') { + constructor(message: string = "Resource Not Found") { super(message); - this.name = 'NotFoundError'; + this.name = "NotFoundError"; if (Error.captureStackTrace) { Error.captureStackTrace(this, NotFoundError); } @@ -40,9 +40,9 @@ export class NotFoundError extends Error { // Custom error for general network or unexpected issues. export class NetworkError extends Error { - constructor(message = 'Network or unexpected error occurred') { + constructor(message: string = "Network or unexpected error occurred") { super(message); - this.name = 'NetworkError'; + this.name = "NetworkError"; if (Error.captureStackTrace) { Error.captureStackTrace(this, NetworkError); } @@ -75,39 +75,39 @@ export abstract class BaseApi { * @returns Never, as this method always throws an error. */ protected handleError(error: any): never { - logger.debug('API Error:', error); // Basic logging + logger.debug("API Error:", error); // Basic logging // Check if it looks like an HTTP error with a status code - if (error && typeof error.status === 'number') { + if (error && typeof error.status === "number") { const httpError = error as HttpError; switch (httpError.status) { case 401: // Handle Unauthorized (e.g., redirect to login) // Depending on the app, might not throw, but trigger auth flow // Example: throw new AuthenticationError('Authentication required'); - throw new Error(`Unauthorized (401): ${httpError.message || 'Authentication required'}`); // Placeholder + throw new Error(`Unauthorized (401): ${httpError.message || "Authentication required"}`); // Placeholder case 403: - throw new ForbiddenError(`Forbidden (403): ${httpError.message || 'Access denied'}`); + throw new ForbiddenError(`Forbidden (403): ${httpError.message || "Access denied"}`); case 404: - throw new NotFoundError(`Not Found (404): ${httpError.message || 'Resource not found'}`); + throw new NotFoundError(`Not Found (404): ${httpError.message || "Resource not found"}`); case 500: case 501: case 502: case 503: case 504: - throw new ServerError(`Server Error (${httpError.status}): ${httpError.message || 'Server issue'}`); + throw new ServerError(`Server Error (${httpError.status}): ${httpError.message || "Server issue"}`); default: // Handle other HTTP errors (e.g., 400 Bad Request) - throw new Error(`HTTP Error (${httpError.status}): ${httpError.message || 'An HTTP error occurred'}`); + throw new Error(`HTTP Error (${httpError.status}): ${httpError.message || "An HTTP error occurred"}`); } } else if (error instanceof Error) { // Handle non-HTTP errors (e.g., network issues, client-side errors) - console.debug('Non-HTTP Error:', error.message); + console.debug("Non-HTTP Error:", error.message); throw new NetworkError(`Network or client-side error: ${error.message}`); } else { // Handle cases where the caught object is not an Error instance - console.debug('Unknown error structure:', error); - throw new Error('An unknown error occurred'); + console.debug("Unknown error structure:", error); + throw new Error("An unknown error occurred"); } } } \ No newline at end of file diff --git a/src/core/http/http-client.ts b/src/core/http/http-client.ts index 460627ab..284ba98a 100644 --- a/src/core/http/http-client.ts +++ b/src/core/http/http-client.ts @@ -12,7 +12,7 @@ import {VersionUtils} from "../utils/version"; * based on the profile in the context and also use the base URL accordingly. */ export class HttpClient { - + private axios = AxiosInitializer.initializeAxios(); constructor(private context: Context) {} @@ -27,7 +27,7 @@ export class HttpClient { logger.debug(`Response ${response.status}`); this.handleResponse(response, resolve, reject); }).catch(err => { - logger.debug(`HTTP GET resulted in error`, err); + logger.debug("HTTP GET resulted in error", err); this.handleError(err, resolve, reject); }) }).catch(e => { @@ -161,7 +161,7 @@ export class HttpClient { }); } - private handleResponseStreamData(data, resolve, reject): void { + private handleResponseStreamData(data: any, resolve: any, reject: any): void { if (data) { resolve(data); return; @@ -175,7 +175,7 @@ export class HttpClient { return this.context.profile.team.replace(/\/?$/, url); } - private handleResponse(res: AxiosResponse, resolve, reject): void { + private handleResponse(res: AxiosResponse, resolve: any, reject: any): void { if (this.checkBadRequest(res.status)) { this.handleBadRequest(res.status, res.data, reject); return; @@ -183,7 +183,7 @@ export class HttpClient { resolve(res.data); } - private handleError(err: any, resolve, reject): void { + private handleError(err: any, resolve: any, reject: any): void { if (err.response) { this.handleResponse(err.response, resolve, reject); } else { @@ -196,7 +196,7 @@ export class HttpClient { } // tslint:disable-next-line:typedef - private handleBadRequest(statusCode, data, reject): void { + private handleBadRequest(statusCode: number, data: any, reject: any): void { if (data) { reject(JSON.stringify(data)); } else { diff --git a/src/core/utils/logger.ts b/src/core/utils/logger.ts index c3dbf9f5..570b06dc 100644 --- a/src/core/utils/logger.ts +++ b/src/core/utils/logger.ts @@ -26,8 +26,8 @@ class CustomTransport extends Transport { // directories for now. Consider changing this to a general 'home' directory such // as .celonis-cli or alike. const logDirName = ".celonis-content-cli-profiles"; -const logFileName = 'celonis-cli.log'; -const exceptionLogFileName = 'exceptions.log'; +const logFileName = "celonis-cli.log"; +const exceptionLogFileName = "exceptions.log"; const maxLogSizeMB = 3; const logDir = path.join(os.homedir(), logDirName); const logFilePath = path.join(logDir, logFileName); @@ -45,16 +45,16 @@ try { export const logger: Logger = winston.createLogger({ format: winston.format.combine(winston.format.cli()), - level: 'debug', + level: "debug", transports: [ new winston.transports.Console({ - level: 'info', + level: "info", format: winston.format.combine( winston.format.colorize(), ), }), new winston.transports.File({ - level: 'info', // Log everything from debug up to the file + level: "info", // Log everything from debug up to the file filename: logFilePath, format: winston.format.combine( winston.format.timestamp(), // Add timestamp to file logs @@ -94,7 +94,7 @@ export class FatalError extends Error { public error = "FatalError"; } -// By default the logger will process.exit(1) when logging an uncaught fatal error +// By default, the logger will process.exit(1) when logging an uncaught fatal error // This interface allows us to throw errors that do not force the process to exit and can be handled gracefully // tslint:disable-next-line: max-classes-per-file export class GracefulError extends Error { diff --git a/src/core/utils/question.service.ts b/src/core/utils/question.service.ts index a6281c6b..7a91456b 100644 --- a/src/core/utils/question.service.ts +++ b/src/core/utils/question.service.ts @@ -7,7 +7,7 @@ import { ReadLine } from "readline"; */ export class QuestionService { - readLine: ReadLine; + private readLine: ReadLine; constructor() { this.readLine = readline.createInterface({ @@ -17,13 +17,13 @@ export class QuestionService { }); } - async ask(question: string): Promise { - return new Promise((resolve) => { + public async ask(question: string): Promise { + return new Promise(resolve => { this.readLine.question(question, input => resolve(input)); }); } - close() { + public async close(): Promise { this.readLine.close(); } }