diff --git a/README.md b/README.md index d11e790..81e809d 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,12 @@ yarn build This will create a `dist` folder with the compiled assets. +## Evolution-Manager CLI - Documentation + +For detailed information on how to use the Evolution-Manager CLI, please refer to the documentation available at the following links: + +- [Documentation in English](https://github.com/gabrielpastori1/evolution-manager/blob/main/docs/en/cli.md) + ## Self-Hosted - Evolution Manager CLI and PM2 ### Straight to the Point: Quick Setup with PM2 diff --git a/README.pt_BR.md b/README.pt_BR.md index 4514ee2..c69037a 100644 --- a/README.pt_BR.md +++ b/README.pt_BR.md @@ -52,6 +52,12 @@ yarn build Isso criará uma pasta `dist` com os ativos compilados. +## Evolution-Manager CLI - Documentação + +Para informações detalhadas sobre como usar o Evolution-Manager CLI, consulte a documentação disponível nos seguintes links: + +- [Documentação em Português](https://github.com/gabrielpastori1/evolution-manager/blob/main/docs/pt_br/cli.md) + ## Auto-Hospedagem - CLI e PM2 do Evolution Manager ### Direto ao Ponto: Configuração Rápida com PM2 diff --git a/docs/en/cli.md b/docs/en/cli.md new file mode 100644 index 0000000..d35db9e --- /dev/null +++ b/docs/en/cli.md @@ -0,0 +1,44 @@ +# Evolution-Manager CLI + +## Description +The Evolution-Manager CLI is a command-line tool designed to manage servers, PM2 processes, and interact with the "evolution-api" project. + +## Installation +To install the Evolution-Manager CLI, run the following command: +``` +npm install -g evolution-manager +``` + +## Available Commands + +### General +- `help`: Displays a list of available commands. Refer to this document for additional details on each command. + +### Server +- `server start [--port=9615]`: Starts a temporary server in the terminal, ideal for local use. The `--port` parameter allows specifying the port, with `9615` as the default. +- `server build`: Executes the server build but does not start it. (Currently without specific use). + +### PM2 +Interacts with PM2 to manage Evolution Manager processes: +- `pm2 setup`: Configures PM2 to host the Evolution Manager. Automatically installs PM2 if not present. +- `pm2 start`: Starts the Evolution Manager process in PM2. +- `pm2 stop`: Stops the Evolution Manager process in PM2. +- `pm2 restart`: Restarts the Evolution Manager process in PM2. +- `pm2 delete`: Removes the Evolution Manager process from PM2. + +### API + +The API section of the Evolution-Manager CLI includes various functions for managing the installation and versions of the Evolution Manager within the API. The available commands are: + +- `setup` or `install`: Installs the manager inside the Evolution API at the path `/manager`. This command can also be accessed using the shorthand `i`. +- `uninstall`: Uninstalls the manager from the Evolution API. +- `changeVersion` or `cv`: Switches to a specific version of the Evolution API, whether newer or older. Example usage: `changeVersion --v=1.5.0`. + +These commands provide a flexible and powerful command-line interface for managing the versions and configuration of the manager in your Evolution API installation. + +## Typical Usage Flow +1. Install the CLI globally. +2. Use `help` to view available commands. +3. Use PM2 commands to host the Evolution Manager. +4. Run `server start` for a local temporary server. +5. Within the "evolution-api" installation, use `api setup` to update to the new manager. diff --git a/docs/pt_br/cli.md b/docs/pt_br/cli.md new file mode 100644 index 0000000..81bd883 --- /dev/null +++ b/docs/pt_br/cli.md @@ -0,0 +1,42 @@ +# Evolution-Manager CLI + +## Instalação +Para instalar o Evolution-Manager CLI, execute o seguinte comando: +``` +npm install -g evolution-manager +``` + +## Comandos Disponíveis + +### Geral +- `help`: Exibe uma lista de comandos disponíveis. Para mais detalhes sobre cada comando, consulte este documento. + +### Server +- `server start [--port=9615]`: Inicia um servidor temporário no terminal, ideal para execução local. O parâmetro `--port` define a porta do servidor, sendo `9615` o valor padrão. +- `server build`: Realiza o build do servidor, mas não o executa. (Atualmente sem uso específico). + +### PM2 +O CLI interage com o PM2 para gerenciar processos do Evolution Manager. +- `pm2 setup`: Configura o PM2 para hospedar o Evolution Manager. Se o PM2 não estiver instalado, o CLI o instalará automaticamente. +- `pm2 start`: Inicia o processo do Evolution Manager no PM2. +- `pm2 stop`: Para o processo do Evolution Manager no PM2. +- `pm2 restart`: Reinicia o processo do Evolution Manager no PM2. +- `pm2 delete`: Remove o processo do Evolution Manager do PM2. + +## API + +A seção API do Evolution-Manager CLI inclui várias funções para gerenciar a instalação e as versões do Evolution Manager na API. Os comandos disponíveis são: + +- `setup` ou `install`: Instala o manager dentro da Evolution API no caminho `/manager`. Este comando também pode ser acessado usando a abreviação `i`. +- `uninstall`: Desinstala o manager da Evolution API. +- `changeVersion` ou `cv`: Altera para uma versão específica da Evolution API, seja ela mais nova ou mais antiga. Exemplo de uso: `changeVersion --v=1.5.0`. + +Esses comandos fornecem uma interface de linha de comando flexível e poderosa para gerenciar as versões e a configuração do manager na sua instalação da Evolution API. + + +## Fluxo de Uso Típico +1. Instale o CLI globalmente. +2. Utilize o comando `help` para ver a lista de comandos disponíveis. +3. Para hospedar o Evolution Manager, use os comandos sob `PM2`. +4. Use o comando `server start` para rodar um servidor temporário localmente. +5. Utilize `api setup` para interagir com o projeto "evolution-api" e configurar o manager. \ No newline at end of file diff --git a/lib/api/changeVersion.js b/lib/api/changeVersion.js new file mode 100644 index 0000000..77124d8 --- /dev/null +++ b/lib/api/changeVersion.js @@ -0,0 +1,18 @@ +const verifyEvolutionInstallation = require('../utils/verifyEvolutionInstallation.js'); +const revertToVersion = require('../utils/revertToVersion.js'); + +module.exports = async (argv) => { + const { v } = argv || {} + if (!v) throw new Error('❌ Please specify a version to revert to. Example: evolution-manager api revert --v=1.5.0') + + const isEvolutionInstalled = verifyEvolutionInstallation(); + if (!isEvolutionInstalled) return; + + + + console.log(`🔃 Reverting to Evolution-Api v${v}...`); + await revertToVersion(v); + console.log(`🔃 Reverted to Evolution-Api v${v} successfully`); + + console.log('\n🔁 Please restart the process to use the reverted version\n') +}; \ No newline at end of file diff --git a/lib/api/index.js b/lib/api/index.js index 117dbbb..848f015 100644 --- a/lib/api/index.js +++ b/lib/api/index.js @@ -1,5 +1,10 @@ const functions = { + i: require('./setup.js'), + install: require('./setup.js'), setup: require('./setup.js'), + uninstall: require('./uninstall.js'), + cv: require('./changeVersion.js'), + changeVersion: require('./changeVersion.js'), } module.exports = async (argv) => { diff --git a/lib/api/setup.js b/lib/api/setup.js index 0569e93..10aadec 100644 --- a/lib/api/setup.js +++ b/lib/api/setup.js @@ -1,16 +1,15 @@ const build = require('../utils/build.js'); const fs = require('fs-extra'); const path = require('path'); +const verifyEvolutionInstallation = require('../utils/verifyEvolutionInstallation.js'); module.exports = async () => { const isEvolutionInstalled = verifyEvolutionInstallation(); if (!isEvolutionInstalled) return; - console.log('👍 Evolution-Api installation found'); await build({ VITE_BASE_URL: '/manager/' }); - // copy dist folder to evolution-api/Extras/evolution-manager - console.time('📦 Copy dist folder to evolution-api/Extras/evolution-manager'); + console.time('📦 Copy dist folder to /Extras/evolution-manager'); const distFolder = path.join(__dirname, '..', '..', 'dist'); const extrasFolder = path.join(process.cwd(), 'Extras'); @@ -19,47 +18,18 @@ module.exports = async () => { if (!fs.existsSync(evolutionManagerFolder)) fs.mkdirSync(evolutionManagerFolder); fs.copySync(distFolder, evolutionManagerFolder); - console.timeEnd('📦 Copy dist folder to evolution-api/Extras/evolution-manager'); + console.timeEnd('📦 Copy dist folder to /Extras/evolution-manager'); // Apply diff git patch - console.time('↘️ Apply diff git patch'); + console.time('📥 Apply diff git patch'); const patchPath = path.join(__dirname, './view.router.ts.patch'); const apiFile = path.join(process.cwd(), 'src', 'whatsapp', 'routers', 'view.router.ts'); // copy/replace file with patch fs.copySync(patchPath, apiFile); - console.timeEnd('↘️ Apply diff git patch'); + console.timeEnd('📥 Apply diff git patch'); - console.log('\n 🎉 Evolution-Api Manager installed successfully! 🎉'); - console.log('👉 Restart your Evolution-Api server to apply changes 👈') -}; - -function verifyEvolutionInstallation(version = "1.5.0") { - // load package.json current context - const packageJsonPath = path.join(process.cwd(), 'package.json'); - if (!fs.existsSync(packageJsonPath)) { - console.error("🚨 package.json not found. Certify you are in the root of the Evolution-Api installation") - return false - } - var packageJson = fs.readFileSync(packageJsonPath, 'utf8'); - packageJson = JSON.parse(packageJson); - - - // check if evolution is installed - if (packageJson.name !== "evolution-api") { - console.error("🚨 This is not a Evolution-API installation. Certify you are in the root of the Evolution-Api installation") - return false - } - - // verify if version is same or higher - if (version) { - const semver = require('semver'); - if (!semver.gte(packageJson.version, version)) { - console.error(`🚨 Evolution-Api version ${version} or higher is required. Please update your Evolution-Api installation`) - return false - } - } - - return true -} \ No newline at end of file + console.log('\n🎉 Evolution-Api Manager installed successfully! 🎉'); + console.log('🔁 Restart your Evolution-Api server to apply changes 🔁') +}; \ No newline at end of file diff --git a/lib/api/uninstall.js b/lib/api/uninstall.js new file mode 100644 index 0000000..f8a4a53 --- /dev/null +++ b/lib/api/uninstall.js @@ -0,0 +1,41 @@ +const fs = require('fs-extra'); +const path = require('path'); +const { exec } = require('child_process'); + +const verifyEvolutionInstallation = require('../utils/verifyEvolutionInstallation.js'); +const revertToVersion = require('../utils/revertToVersion.js'); + +module.exports = async () => { + const isEvolutionInstalled = verifyEvolutionInstallation(); + if (!isEvolutionInstalled) return; + + // Verify manager instalation + const extrasFolder = path.join(process.cwd(), 'Extras'); + const evolutionManagerIndex = path.join(extrasFolder, 'evolution-manager/index.html'); + if (!fs.existsSync(evolutionManagerIndex)) throw new Error('❌ Evolution Manager installation not found. Please install it first'); + + + const apiVersion = isEvolutionInstalled.version; + + // git pull force tag version + console.log(`🔃 Reverting to Evolution-Api v${apiVersion}...`); + await discardChanges(); + await revertToVersion(apiVersion); + console.log(`🔃 Reverted to Evolution-Api v${apiVersion} successfully`); + + console.log('\n🔁 Please restart the process to use the reverted version\n') +}; + +function discardChanges() { + return new Promise((resolve) => { + exec(`git clean -f -d -q && git checkout .`, (err) => { + if (err) { + console.error(err) + return resolve(false) + } + + resolve(true) + }) + }) +} + diff --git a/lib/help.js b/lib/help.js index f6c5384..71de8e0 100644 --- a/lib/help.js +++ b/lib/help.js @@ -1,31 +1,34 @@ module.exports = () => { // Welcome message - console.log(`👋 Welcome to evolution-manager CLI!`); + console.log(`👋 Welcome to the evolution-manager CLI! Explore the power of managing your server and API with ease.`); // Help message - console.log(`📋 Available commands:`); + console.log(`📘 Here's what you can do with evolution-manager CLI:`); // Server commands - console.log(`\nServer:`); - console.log(` help`); - console.log(` server`); - console.log(` - start [--port=9615]`); - console.log(` - build`); + console.log(`\n🖥️ Server Commands:`); + console.log(` help - Get help and command summaries`); + console.log(` server - Manage your server`); + console.log(` - start [--port=9615] - Start the server on a specific port`); + console.log(` - build - Build the server environment`); // PM2 commands - console.log(`\nPM2:`); - console.log(` pm2`); - console.log(` - setup`); - console.log(` - start`); - console.log(` - stop`); - console.log(` - restart`); - console.log(` - delete`); + console.log(`\n🔄 PM2 Management:`); + console.log(` pm2 - Control your PM2 processes`); + console.log(` - setup - Set up a PM2 process`); + console.log(` - start - Start a PM2 process`); + console.log(` - stop - Stop a PM2 process`); + console.log(` - restart - Restart a PM2 process`); + console.log(` - delete - Delete a PM2 process`); // API commands - console.log(`\nAPI:`); - console.log(` api`); - console.log(` - setup (Install the manager inside the Evolution Manager in path /manager)`); + console.log(`\n🔗 API Interaction (Run these inside the Evolution API folder):`); + console.log(` api - Manage your Evolution API`); + console.log(` - setup - Install the manager at /manager in the Evolution API`); + console.log(` - uninstall - Uninstall the manager from the Evolution API`); + console.log(` - changeVersion --v=1.5.0 - Change to a specific version of the Evolution API`); - // Spacing - console.log(`\n`); + // Documentation link and disclaimer + console.log(`\n📚 For complete documentation, visit: https://github.com/gabrielpastori1/evolution-manager`); + console.log(`\n ℹ️ Disclaimer: This evolution-manager CLI project is independent and not affiliated with the evolution-api project.`); }; diff --git a/lib/utils/build.js b/lib/utils/build.js index 8349c19..8b44485 100644 --- a/lib/utils/build.js +++ b/lib/utils/build.js @@ -4,25 +4,51 @@ const path = require('path') module.exports = (envs = {}) => { return new Promise((resolve, reject) => { - console.log('📦 Build start') - console.time('📦 Build complete') - const distFolder = path.join(__dirname, '..', '..', 'dist') - if (fs.existsSync(distFolder)) { - console.time('📦 Remove dist folder') - fs.rmSync(distFolder, { recursive: true, force: true }) - console.timeEnd('📦 Remove dist folder') - } - - // pass envs to build - exec(`npm run build`, { env: envs, cwd: path.join(__dirname, '..', '..') }, (err, stdout) => { - if (err) { - console.error(err) - reject(err) - return + verifyViteInstallation().then(() => { + console.log('📦 Build start') + console.time('📦 Build complete') + const distFolder = path.join(__dirname, '..', '..', 'dist') + if (fs.existsSync(distFolder)) { + console.time('📦 Remove dist folder') + fs.rmSync(distFolder, { recursive: true, force: true }) + console.timeEnd('📦 Remove dist folder') } - console.log(stdout) - console.timeEnd('📦 Build complete') - resolve() + + // pass envs to build + exec(`npm run build`, { env: envs, cwd: path.join(__dirname, '..', '..') }, (err, stdout) => { + if (err) { + console.error(err) + reject(err) + return + } + console.log(stdout) + console.timeEnd('📦 Build complete') + resolve() + }) }) + }).catch(() => { + return }) } + + +const verifyViteInstallation = () => { + return new Promise((resolve, reject) => { + exec(`vite --v`, (err) => { + if (!err) return resolve() + + console.log('🚨 Vite not installed, trying to install it') + exec(`npm install -g vite`, (err) => { + if (err) { + console.log('🚨 Vite installation failed') + reject(err) + return + } + + console.log('🚨 Vite installed') + console.log('🔁 Run the command again') + reject() + }) + }) + }) +} \ No newline at end of file diff --git a/lib/utils/revertToVersion.js b/lib/utils/revertToVersion.js new file mode 100644 index 0000000..fd86f88 --- /dev/null +++ b/lib/utils/revertToVersion.js @@ -0,0 +1,14 @@ +const { exec } = require('child_process') + +module.exports = (version) => { + return new Promise((resolve) => { + exec(`git fetch --all && git reset --hard ${version}`, (err, stdout) => { + if (err) { + console.error(err) + return resolve(false) + } + console.log(stdout) + resolve(true) + }) + }) +} \ No newline at end of file diff --git a/lib/utils/verifyEvolutionInstallation.js b/lib/utils/verifyEvolutionInstallation.js new file mode 100644 index 0000000..b4f8b7f --- /dev/null +++ b/lib/utils/verifyEvolutionInstallation.js @@ -0,0 +1,34 @@ +const fs = require('fs'); +const path = require('path'); + +module.exports = (version = "1.5.0") => { + // load package.json current context + const packageJsonPath = path.join(process.cwd(), 'package.json'); + if (!fs.existsSync(packageJsonPath)) { + console.error("🚨 package.json not found. Certify you are in the root of the Evolution-Api installation") + return false + } + var packageJson = fs.readFileSync(packageJsonPath, 'utf8'); + packageJson = JSON.parse(packageJson); + + + // check if evolution is installed + if (packageJson.name !== "evolution-api") { + console.error("🚨 This is not a Evolution-API installation. Certify you are in the root of the Evolution-Api installation") + return false + } + + // verify if version is same or higher + if (version) { + const semver = require('semver'); + if (!semver.gte(packageJson.version, version)) { + console.error(`🚨 Evolution-Api version ${version} or higher is required. Please update your Evolution-Api installation`) + return false + } + } + console.log(`👍 Evolution-Api ${packageJson.version} installation found`); + + return { + ...packageJson, + } +} diff --git a/lib/utils/verifyPm2Installation.js b/lib/utils/verifyPm2Installation.js index 882bb8d..a373369 100644 --- a/lib/utils/verifyPm2Installation.js +++ b/lib/utils/verifyPm2Installation.js @@ -29,7 +29,10 @@ function installPM2() { return resolve(false) } console.log(stdout) - resolve(true) + + console.log('\n\n🔁 Please restart the process to use PM2') + + resolve(false) }) }) } \ No newline at end of file diff --git a/package.json b/package.json index 31dca80..1e0a202 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "evolution-manager", - "version": "0.3.0", + "version": "0.3.1", "main": "dist", "scripts": { "dev": "vite",