import fs from 'node:fs'; import path from 'node:path'; import { execSync } from 'node:child_process'; const PUBLIC_DIR = path.resolve('public'); const DIST_ZIP = path.join(PUBLIC_DIR, 'maestri-agent.zip'); const STAGING_DIR = path.resolve('.temp_agent_pkg'); if (!fs.existsSync(PUBLIC_DIR)) { fs.mkdirSync(PUBLIC_DIR, { recursive: true }); } if (fs.existsSync(STAGING_DIR)) { fs.rmSync(STAGING_DIR, { recursive: true, force: true }); } fs.mkdirSync(STAGING_DIR, { recursive: true }); console.log('[BuildAgentPkg] Montando estrutura do pacote maestri-agent...'); // Copia bin/ fs.mkdirSync(path.join(STAGING_DIR, 'bin'), { recursive: true }); fs.copyFileSync(path.resolve('bin', 'maestri-remote.js'), path.join(STAGING_DIR, 'bin', 'maestri-remote.js')); // Copia src/gateway/ fs.mkdirSync(path.join(STAGING_DIR, 'src', 'gateway'), { recursive: true }); fs.copyFileSync(path.resolve('src', 'gateway', 'daemon.js'), path.join(STAGING_DIR, 'src', 'gateway', 'daemon.js')); fs.copyFileSync(path.resolve('src', 'gateway', 'maestri-adapter.js'), path.join(STAGING_DIR, 'src', 'gateway', 'maestri-adapter.js')); fs.copyFileSync(path.resolve('src', 'gateway', 'agent-updater.js'), path.join(STAGING_DIR, 'src', 'gateway', 'agent-updater.js')); // Copia src/utils/ fs.mkdirSync(path.join(STAGING_DIR, 'src', 'utils'), { recursive: true }); if (fs.existsSync(path.resolve('src', 'utils', 'text-sanitizer.js'))) { fs.copyFileSync(path.resolve('src', 'utils', 'text-sanitizer.js'), path.join(STAGING_DIR, 'src', 'utils', 'text-sanitizer.js')); } if (fs.existsSync(path.resolve('src', 'utils', 'activity-detector.js'))) { fs.copyFileSync(path.resolve('src', 'utils', 'activity-detector.js'), path.join(STAGING_DIR, 'src', 'utils', 'activity-detector.js')); } // Copia package.json enxuto (apenas dependências de runtime do gateway) const fullPkg = JSON.parse(fs.readFileSync('package.json', 'utf8')); const agentPkg = { name: 'maestri-remote-agent', version: fullPkg.version, type: 'module', description: 'Gateway Local do Maestri Remote para estações de trabalho', bin: { 'maestri-remote': 'bin/maestri-remote.js' }, scripts: { start: 'node bin/maestri-remote.js start' }, dependencies: { ws: fullPkg.dependencies.ws || '^8.18.0' } }; fs.writeFileSync(path.join(STAGING_DIR, 'package.json'), JSON.stringify(agentPkg, null, 2)); // Adiciona scripts de inicialização rápida com auto-restart em atualizações para Windows e Linux const startBat = `@echo off setlocal title Maestri Remote Daemon set "MAESTRI_MANAGED_BY_WRAPPER=1" :loop echo ============================================== echo Maestri Remote Daemon - Gateway da Estacao echo ============================================== if not exist node_modules ( echo Instalando dependencias necessarias... call npm install --omit=dev ) echo. echo Iniciando gateway de comunicacao... node bin\\maestri-remote.js start set "CODE=%ERRORLEVEL%" if "%CODE%"=="42" goto restart if "%CODE%"=="0" goto restart if "%CODE%"=="130" ( echo. echo [Maestri Remote] Daemon encerrado pelo operador. exit /b 0 ) echo. echo [Maestri Remote] Gateway finalizado com codigo %CODE%. echo Tentando reiniciar em 3 segundos... (Pressione Ctrl+C para sair) timeout /t 3 goto loop :restart echo. echo [Maestri Remote] Daemon atualizado com sucesso. Reiniciando em 2 segundos... timeout /t 2 /nobreak >nul goto loop `; fs.writeFileSync(path.join(STAGING_DIR, 'iniciar.bat'), startBat.replace(/\r?\n/g, '\r\n')); const startSh = `#!/bin/bash echo "==============================================" echo " Maestri Remote Daemon - Gateway da Estacao " echo "==============================================" if [ ! -d "node_modules" ]; then echo "Instalando dependencias necessarias..." npm install --omit=dev fi export MAESTRI_MANAGED_BY_WRAPPER=1 while true; do echo "" echo "Iniciando gateway de comunicacao..." node bin/maestri-remote.js start EXIT_CODE=$? if [ $EXIT_CODE -eq 42 ] || [ $EXIT_CODE -eq 0 ]; then echo "" echo "[Maestri Remote] Daemon atualizado com sucesso. Reiniciando em 2 segundos..." sleep 2 else echo "" echo "[Maestri Remote] Gateway finalizado com codigo $EXIT_CODE." break fi done `; fs.writeFileSync(path.join(STAGING_DIR, 'iniciar.sh'), startSh); // Adiciona README.txt explicativo const readme = `=== Maestri Remote Agent === Este pacote permite conectar qualquer estacao de trabalho ao seu aplicativo celular Maestri Remote. Como executar no Windows: 1. Extraia este arquivo ZIP em qualquer pasta 2. De um duplo clique em "iniciar.bat" Como executar no Linux / macOS / WSL: 1. Extraia este arquivo ZIP 2. Abra o terminal na pasta e execute: bash iniciar.sh Ou manualmente via Node.js: 1. npm install --omit=dev 2. node bin/maestri-remote.js start Um PIN de 6 digitos sera gerado no terminal. No seu celular, toque em "+ Estacao" ou digite o PIN para conectar imediatamente! `; fs.writeFileSync(path.join(STAGING_DIR, 'README.txt'), readme); console.log(`[BuildAgentPkg] Gerando ${DIST_ZIP}...`); if (fs.existsSync(DIST_ZIP)) { fs.unlinkSync(DIST_ZIP); } // Criação do ZIP padrão compatível com Windows Explorer (sem o bug de ./ do bsdtar) let zipSuccess = false; try { // Tenta Compress-Archive do PowerShell (padrão oficial do Windows Explorer) execSync(`powershell -NoProfile -Command "Compress-Archive -Path '${STAGING_DIR}\\*' -DestinationPath '${DIST_ZIP}' -Force"`, { stdio: 'inherit' }); zipSuccess = true; } catch (psErr) { console.warn('[BuildAgentPkg] PowerShell Compress-Archive falhou, tentando tar com wildcard:', psErr.message); } if (!zipSuccess) { // Fallback: usa tar com * em vez de . para não criar ./ na raiz execSync(`tar -a -c -f "${DIST_ZIP}" -C "${STAGING_DIR}" *`, { stdio: 'inherit' }); } // Limpa staging fs.rmSync(STAGING_DIR, { recursive: true, force: true }); const stats = fs.statSync(DIST_ZIP); console.log(`[BuildAgentPkg] maestri-agent.zip gerado com sucesso! (${(stats.size / 1024).toFixed(1)} KB)`);