@gnpdev/rpa-tools 1.0.13 → 1.0.15
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.
- package/README.md +40 -34
- package/package.json +1 -1
- package/src/index.d.ts +12 -8
- package/src/index.js +18 -1
package/README.md
CHANGED
|
@@ -23,6 +23,8 @@ Crea un archivo en tu proyecto (ej. `src/lib/rpa.js`) para inicializar y exporta
|
|
|
23
23
|
// src/lib/rpa.js
|
|
24
24
|
import { createRpaTools } from '@gnpdev/rpa-tools';
|
|
25
25
|
import { Pool } from 'pg';
|
|
26
|
+
import * as dotenv from 'dotenv';
|
|
27
|
+
dotenv.config();
|
|
26
28
|
|
|
27
29
|
// 1. Configura tu pool de base de datos (usualmente ya lo tienes)
|
|
28
30
|
const pool = new Pool({
|
|
@@ -47,26 +49,39 @@ export const rpa = await createRpaTools({
|
|
|
47
49
|
}
|
|
48
50
|
})
|
|
49
51
|
|
|
50
|
-
|
|
52
|
+
// 3. Exporta las herramientas
|
|
53
|
+
export const { logger, state, step } = rpa;
|
|
51
54
|
```
|
|
52
55
|
|
|
53
56
|
## Uso en la Aplicación
|
|
54
57
|
|
|
55
|
-
### 1.
|
|
58
|
+
### 1. Gestión de Pasos y Estado
|
|
59
|
+
La librería mantiene el rastro del paso actual del bot. Cada vez que llamas a `step()`, se actualiza el estado interno y se genera un log automático.
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
import { step, state } from './lib/rpa.js';
|
|
63
|
+
|
|
64
|
+
step('Inicio de Sesión');
|
|
65
|
+
console.log(state.currentStep); // 'Inicio de Sesión'
|
|
66
|
+
|
|
67
|
+
step('Extracción de Datos');
|
|
68
|
+
// Genera log: info { "step": "Extracción de Datos" } "Nuevo paso"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 2. Logging Estructurado
|
|
56
72
|
Usa el logger preconfigurado que ya incluye el `botId` en cada entrada.
|
|
57
73
|
|
|
58
74
|
```javascript
|
|
59
|
-
import { logger
|
|
75
|
+
import { logger } from './lib/rpa.js';
|
|
60
76
|
|
|
61
77
|
logger.info('Procesando orden');
|
|
62
78
|
```
|
|
63
79
|
|
|
64
|
-
###
|
|
80
|
+
### 3. Gestión de Credenciales
|
|
65
81
|
Recupera de forma segura el `usuario`, `password` e `idUsuario` de una aplicación específica vinculada al bot.
|
|
66
82
|
|
|
67
83
|
```javascript
|
|
68
|
-
import {
|
|
69
|
-
|
|
84
|
+
import { rpa, logger } from './lib/rpa.js';
|
|
70
85
|
|
|
71
86
|
logger.info('Obtener credenciales');
|
|
72
87
|
const credentials = await rpa.getCredentials('Portal CRM');
|
|
@@ -77,7 +92,7 @@ if (credentials) {
|
|
|
77
92
|
}
|
|
78
93
|
```
|
|
79
94
|
|
|
80
|
-
###
|
|
95
|
+
### 4. Capturas de Pantalla bajo demanda (Playwright)
|
|
81
96
|
Activa el watcher pasando la instancia de `page`. El bot detectará cambios en la tabla de la DB para tomar screenshots automáticamente.
|
|
82
97
|
|
|
83
98
|
```javascript
|
|
@@ -92,53 +107,44 @@ rpa.watchDebugFlag(page);
|
|
|
92
107
|
|
|
93
108
|
|
|
94
109
|
// Al terminar el proceso del bot
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
puedes incluir
|
|
110
|
+
rpa.destroy();
|
|
98
111
|
|
|
99
|
-
|
|
112
|
+
// Sugerencia: limpiar al desconectar
|
|
113
|
+
browser.on('disconnected', () => rpa.destroy());
|
|
100
114
|
```
|
|
101
115
|
|
|
102
|
-
###
|
|
103
|
-
Captura el estado completo del bot cuando ocurre una excepción
|
|
116
|
+
### 5. Captura Automática de Errores (Screenshot + Trace)
|
|
117
|
+
Captura el estado completo del bot cuando ocurre una excepción. **`captureError` detecta automáticamente el paso actual** definido con `step()`.
|
|
104
118
|
|
|
105
119
|
```javascript
|
|
106
120
|
import { chromium } from 'playwright';
|
|
107
|
-
import { rpa, logger } from './lib/rpa.js';
|
|
121
|
+
import { rpa, logger, step } from './lib/rpa.js';
|
|
108
122
|
|
|
109
123
|
const browser = await chromium.launch({ headless: true });
|
|
110
124
|
const context = await browser.newContext();
|
|
111
125
|
const page = await context.newPage();
|
|
112
126
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
// snapshots:true → guarda el DOM y estado de red en cada paso
|
|
116
|
-
await context.tracing.start({
|
|
117
|
-
screenshots: true,
|
|
118
|
-
snapshots: true,
|
|
119
|
-
});
|
|
127
|
+
// ── Activar tracing ANTES de que empiece la sesión ──────────────────────
|
|
128
|
+
await context.tracing.start({ screenshots: true, snapshots: true });
|
|
120
129
|
|
|
121
|
-
|
|
130
|
+
browser.on('disconnected', () => rpa.destroy());
|
|
122
131
|
|
|
123
132
|
try {
|
|
124
|
-
|
|
133
|
+
step('Navegación');
|
|
125
134
|
await page.goto('https://example.com');
|
|
126
135
|
|
|
127
|
-
|
|
136
|
+
step('Login');
|
|
128
137
|
await login(page);
|
|
129
138
|
|
|
130
|
-
|
|
139
|
+
step('Procesar Datos');
|
|
131
140
|
await page.click('#boton-inexistente');
|
|
141
|
+
|
|
132
142
|
} catch (err) {
|
|
133
|
-
// Captura automática de evidencia
|
|
134
|
-
const { errorId } = await rpa.captureError({
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
step: currentStep
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
logger.error({ errorId, step: currentStep }, 'Fallo crítico capturado');
|
|
143
|
+
// Captura automática de evidencia (usa el paso 'Procesar Datos' automáticamente)
|
|
144
|
+
const { errorId } = await rpa.captureError({ page, context, err });
|
|
145
|
+
|
|
146
|
+
logger.error({ errorId }, 'Fallo crítico capturado');
|
|
147
|
+
rpa.destroy();
|
|
142
148
|
throw err;
|
|
143
149
|
}
|
|
144
150
|
```
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -49,6 +49,17 @@ export interface RpaTools {
|
|
|
49
49
|
/** Instancia de Pino lista para usar en el bot */
|
|
50
50
|
logger: Logger;
|
|
51
51
|
|
|
52
|
+
/** Estado compartido del bot */
|
|
53
|
+
state: {
|
|
54
|
+
currentStep: string;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Cambia el paso actual, actualiza el estado y emite un log info.
|
|
59
|
+
* @param name - Nombre del nuevo paso
|
|
60
|
+
*/
|
|
61
|
+
step: (name: string) => void;
|
|
62
|
+
|
|
52
63
|
/**
|
|
53
64
|
* Inicia el polling que activa/desactiva screenshots
|
|
54
65
|
* según bot_debug_config en la BD.
|
|
@@ -80,12 +91,5 @@ export interface RpaTools {
|
|
|
80
91
|
// ── Export principal ─────────────────────────────────────────────────────────
|
|
81
92
|
/**
|
|
82
93
|
* Inicializa la librería rpa-tools.
|
|
83
|
-
* Crea el cliente MinIO, verifica el bucket y retorna
|
|
84
|
-
* el logger y el watcher listos para usar.
|
|
85
|
-
*
|
|
86
|
-
* @example
|
|
87
|
-
* const rpa = await createRpaTools({ botId: 'bot-001', db: pool });
|
|
88
|
-
* rpa.watchDebugFlag(page);
|
|
89
|
-
* rpa.logger.info('Bot iniciado');
|
|
90
94
|
*/
|
|
91
|
-
export function createRpaTools(options: RpaToolsOptions): Promise<RpaTools>;
|
|
95
|
+
export function createRpaTools(options: RpaToolsOptions): Promise<RpaTools>;
|
package/src/index.js
CHANGED
|
@@ -46,11 +46,28 @@ async function createRpaTools(opts = {}) {
|
|
|
46
46
|
const watcher = new ScreenshotWatcher({ botId, pool: db, minioClient, bucket, logger });
|
|
47
47
|
const credentials = new CredentialManager({ botId, pool: db });
|
|
48
48
|
|
|
49
|
+
const state = { currentStep: 'Inicio' };
|
|
50
|
+
|
|
49
51
|
return {
|
|
50
52
|
logger,
|
|
53
|
+
state,
|
|
54
|
+
step: (name) => {
|
|
55
|
+
state.currentStep = name;
|
|
56
|
+
logger.info({ step: name }, 'Nuevo paso');
|
|
57
|
+
},
|
|
51
58
|
watchDebugFlag: (page, pollMs) => watcher.watch(page, pollMs),
|
|
52
59
|
getCredentials: (nombre) => credentials.getAppCredentials(nombre),
|
|
53
|
-
captureError: ({ page, context, err, step }) =>
|
|
60
|
+
captureError: ({ page, context, err, step }) => captureError({
|
|
61
|
+
page,
|
|
62
|
+
context,
|
|
63
|
+
err,
|
|
64
|
+
step: step || state.currentStep,
|
|
65
|
+
botId,
|
|
66
|
+
pool: db,
|
|
67
|
+
minioClient,
|
|
68
|
+
bucket,
|
|
69
|
+
logger
|
|
70
|
+
}),
|
|
54
71
|
destroy: () => watcher.destroy(),
|
|
55
72
|
};
|
|
56
73
|
}
|