maestri-remote/scripts/build-agent-pkg.js

279 lines
9.9 KiB
JavaScript

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 com cópia recursiva completa...');
function copyRecursiveSync(src, dest, filterExt = ['.js', '.json', '.txt']) {
if (!fs.existsSync(src)) return;
fs.mkdirSync(dest, { recursive: true });
const entries = fs.readdirSync(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
copyRecursiveSync(srcPath, destPath, filterExt);
} else {
const ext = path.extname(entry.name).toLowerCase();
if (!filterExt || filterExt.includes(ext) || entry.name.startsWith('.')) {
fs.copyFileSync(srcPath, destPath);
}
}
}
}
// 1. Copia bin/ de forma completa
copyRecursiveSync(path.resolve('bin'), path.join(STAGING_DIR, 'bin'));
// 2. Copia src/gateway/ de forma dinâmica e completa (NUNCA mais omitirá módulos novos)
copyRecursiveSync(path.resolve('src', 'gateway'), path.join(STAGING_DIR, 'src', 'gateway'));
// 3. Copia src/utils/ de forma dinâmica e completa
copyRecursiveSync(path.resolve('src', 'utils'), path.join(STAGING_DIR, 'src', 'utils'));
// 4. 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',
verify: 'node bin/maestri-remote.js --verify'
},
dependencies: {
ws: fullPkg.dependencies.ws || '^8.18.0'
}
};
fs.writeFileSync(path.join(STAGING_DIR, 'package.json'), JSON.stringify(agentPkg, null, 2));
// 5. Adiciona scripts de inicialização rápida com auto-restart e auto-recuperação de emergência (Self-Healing)
const startBat = `@echo off
setlocal enabledelayedexpansion
title Maestri Remote Daemon
set "MAESTRI_MANAGED_BY_WRAPPER=1"
set "CONSECUTIVE_FAILURES=0"
: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" (
set "CONSECUTIVE_FAILURES=0"
goto restart
)
if "%CODE%"=="0" (
set "CONSECUTIVE_FAILURES=0"
goto restart
)
if "%CODE%"=="130" (
echo.
echo [Maestri Remote] Daemon encerrado pelo operador.
exit /b 0
)
rem Incrementa contador de falhas consecutivas
set /a CONSECUTIVE_FAILURES+=1
echo.
echo [Maestri Remote] Gateway finalizado com codigo %CODE% (Falha consecutiva: !CONSECUTIVE_FAILURES!).
rem Se acumular 3 falhas consecutivas, aciona protocolo de auto-recuperacao de emergencia
if !CONSECUTIVE_FAILURES! GEQ 3 (
echo.
echo [Maestri Remote ALERTA] Multiplas falhas consecutivas detectadas.
echo [Maestri Remote ALERTA] Executando protocolo de auto-recuperacao de emergencia via Relay...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference = 'Stop'; try { Write-Host 'Baixando pacote limpo do Relay...'; Invoke-WebRequest -Uri 'https://remote.winicomw.ddnsfree.com/maestri-agent.zip' -OutFile '.emergency_update.zip'; Write-Host 'Aplicando arquivos integro...'; Expand-Archive -Path '.emergency_update.zip' -DestinationPath '.' -Force; Remove-Item '.emergency_update.zip'; Write-Host 'Restauracao de emergencia concluida com sucesso!'; exit 0 } catch { Write-Host 'Falha no download de emergencia:' $_.Exception.Message; exit 1 }"
if !ERRORLEVEL! EQU 0 (
set "CONSECUTIVE_FAILURES=0"
echo [Maestri Remote] Pacote restaurado! Reiniciando em 2 segundos...
timeout /t 2 /nobreak >nul
goto loop
)
)
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
FAIL_COUNT=0
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
FAIL_COUNT=0
echo ""
echo "[Maestri Remote] Daemon atualizado com sucesso. Reiniciando em 2 segundos..."
sleep 2
elif [ $EXIT_CODE -eq 130 ]; then
echo ""
echo "[Maestri Remote] Daemon encerrado pelo operador."
break
else
FAIL_COUNT=$((FAIL_COUNT + 1))
echo ""
echo "[Maestri Remote] Gateway finalizado com codigo $EXIT_CODE (Falha $FAIL_COUNT)."
if [ $FAIL_COUNT -ge 3 ]; then
echo "[Maestri Remote] Executando auto-recuperacao de emergencia..."
curl -sSfL "https://remote.winicomw.ddnsfree.com/maestri-agent.zip" -o ".emergency.zip" && \
unzip -o -q ".emergency.zip" -d "." && \
rm -f ".emergency.zip" && \
FAIL_COUNT=0 && \
echo "[Maestri Remote] Recuperacao concluida!"
fi
sleep 3
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);
// ====================================================================
// 6. SMOKE TEST OBRIGATÓRIO DE PRÉ-EMPACOTAMENTO (Integrity Verification)
// ====================================================================
console.log('[BuildAgentPkg] Executando Smoke Test e validacao estrita de integridade no pacote staging...');
// 6.1. Verifica se todos os arquivos importados em src/gateway existem fisicamente no staging
const gatewayFiles = fs.readdirSync(path.join(STAGING_DIR, 'src', 'gateway')).filter(f => f.endsWith('.js'));
for (const file of gatewayFiles) {
const fullPath = path.join(STAGING_DIR, 'src', 'gateway', file);
const content = fs.readFileSync(fullPath, 'utf8');
const importRegex = /(?:import|from)\s+['"](\.[^'"]+)['"]/g;
let match;
while ((match = importRegex.exec(content)) !== null) {
const importRel = match[1];
const resolvedPath = path.resolve(path.dirname(fullPath), importRel);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`[BuildAgentPkg FATAL] Integridade comprometida! O arquivo ${file} importa '${importRel}', mas ele NAO EXISTE no pacote staging (${resolvedPath})!`);
}
}
}
// 6.2. Executa node --check em cada arquivo JS empacotado
const allJsFiles = [];
function findJs(dir) {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) findJs(p);
else if (p.endsWith('.js')) allJsFiles.push(p);
}
}
findJs(STAGING_DIR);
for (const js of allJsFiles) {
try {
execSync(`node --check "${js}"`, { stdio: 'pipe' });
} catch (chkErr) {
throw new Error(`[BuildAgentPkg FATAL] Sintaxe invalida em ${js}: ${chkErr.message}`);
}
}
// 6.3. Executa teste de import do bootloader
try {
execSync(`node "${path.join(STAGING_DIR, 'bin', 'maestri-remote.js')}" --verify`, {
cwd: STAGING_DIR,
stdio: 'pipe',
env: { ...process.env, NODE_PATH: path.resolve('node_modules') }
});
console.log('[BuildAgentPkg] Smoke Test APROVADO! Todos os modulos e dependencias sao 100% integraveis.');
} catch (vErr) {
throw new Error(`[BuildAgentPkg FATAL] Falha no teste de execucao do bootloader: ${vErr.message}`);
}
// ====================================================================
// 7. GERAÇÃO DO ZIP
// ====================================================================
console.log(`[BuildAgentPkg] Gerando ${DIST_ZIP}...`);
if (fs.existsSync(DIST_ZIP)) {
fs.unlinkSync(DIST_ZIP);
}
let zipSuccess = false;
try {
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) {
const items = fs.readdirSync(STAGING_DIR);
execSync(`tar -a -c -f "${DIST_ZIP}" -C "${STAGING_DIR}" ${items.join(' ')}`, { 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)`);