@saulwade/swl-ses 1.5.2 → 1.6.0

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.
@@ -0,0 +1,334 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Wizard de instalación TUI.
5
+ * Reemplaza la versión simple basada en preguntarOpcion del install-asistido.js
6
+ * con un flujo multi-step visual usando los componentes selector-unico y
7
+ * selector-multi.
8
+ *
9
+ * Pasos:
10
+ * 1. Runtime destino (Claude/Codex/OpenCode/etc.)
11
+ * 2. Perfil (core / backend-python / fullstack-* / completo / ...)
12
+ * 3. Scope (proyecto / global)
13
+ * 4. Flags adicionales (with-mcp, dry-run)
14
+ * 5. Stacks de lenguajes (solo si perfil = completo)
15
+ * 6. Preview del plan
16
+ * 7. Confirmación final
17
+ *
18
+ * Devuelve el objeto de opciones para `scripts/instalador.js` o null si el
19
+ * usuario canceló en cualquier paso.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+
25
+ const { selectorUnico } = require('../componentes/selector-unico');
26
+ const { selectorMulti } = require('../componentes/selector-multi');
27
+ const render = require('../lib/render');
28
+ const teclas = require('../lib/teclas');
29
+ const { colores, semantico, iconos } = require('../lib/colores');
30
+
31
+ const RAIZ = path.resolve(__dirname, '..', '..', '..');
32
+ const PERFILES_PATH = path.join(RAIZ, 'manifiestos', 'perfiles.json');
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Datos estáticos
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const RUNTIMES = [
39
+ {
40
+ valor: 'claude',
41
+ etiqueta: 'Claude Code',
42
+ descripcion: 'Runtime principal de Anthropic. Soporte completo de hooks, agentes, skills y comandos.',
43
+ badge: 'recomendado',
44
+ },
45
+ {
46
+ valor: 'openclaude',
47
+ etiqueta: 'OpenClaude',
48
+ descripcion: 'Fork open source compatible con Claude Code. Soporte completo.',
49
+ },
50
+ {
51
+ valor: 'opencode',
52
+ etiqueta: 'OpenCode',
53
+ descripcion: 'CLI de código abierto multi-modelo. Soporte completo.',
54
+ },
55
+ {
56
+ valor: 'codex',
57
+ etiqueta: 'Codex CLI (OpenAI)',
58
+ descripcion: 'CLI oficial de OpenAI. Soporte parcial: agentes en TOML, hooks limitados.',
59
+ },
60
+ {
61
+ valor: 'gemini',
62
+ etiqueta: 'Gemini CLI (Google)',
63
+ descripcion: 'CLI oficial de Google Gemini. Soporte completo.',
64
+ },
65
+ {
66
+ valor: 'copilot',
67
+ etiqueta: 'GitHub Copilot',
68
+ descripcion: 'Copilot Chat / CLI. Soporte parcial — no soporta todos los hooks SWL.',
69
+ },
70
+ {
71
+ valor: 'cursor',
72
+ etiqueta: 'Cursor',
73
+ descripcion: 'IDE basado en VS Code con Cursor Agents. Soporte completo de hooks (17 eventos).',
74
+ },
75
+ ];
76
+
77
+ const SCOPES = [
78
+ {
79
+ valor: 'proyecto',
80
+ etiqueta: 'Proyecto (./.claude/)',
81
+ descripcion: 'Solo este proyecto. Recomendado para uso por proyecto y CI/CD.',
82
+ badge: 'recomendado',
83
+ },
84
+ {
85
+ valor: 'global',
86
+ etiqueta: 'Global (~/.claude/)',
87
+ descripcion: 'Disponible en todos los proyectos del usuario. Útil para herramientas comunes.',
88
+ },
89
+ ];
90
+
91
+ const STACKS_ADICIONALES = [
92
+ { valor: 'java', etiqueta: 'Java + Spring Boot' },
93
+ { valor: 'go', etiqueta: 'Go' },
94
+ { valor: 'rust', etiqueta: 'Rust' },
95
+ { valor: 'csharp', etiqueta: 'C# / .NET' },
96
+ { valor: 'kotlin', etiqueta: 'Kotlin + Android' },
97
+ { valor: 'swift', etiqueta: 'Swift + iOS' },
98
+ { valor: 'php', etiqueta: 'PHP + Laravel' },
99
+ { valor: 'nextjs', etiqueta: 'Next.js' },
100
+ ];
101
+
102
+ const FLAGS = [
103
+ {
104
+ valor: 'with-mcp',
105
+ etiqueta: 'Configurar MCP server swl-memory',
106
+ descripcion: 'Habilita búsqueda híbrida BM25+vector en sesiones pasadas. Recomendado.',
107
+ preseleccionado: false,
108
+ },
109
+ {
110
+ valor: 'dry-run',
111
+ etiqueta: 'Dry-run (solo mostrar plan, no copiar archivos)',
112
+ descripcion: 'Útil para inspeccionar qué se haría sin tocar el filesystem.',
113
+ preseleccionado: false,
114
+ },
115
+ ];
116
+
117
+ // ---------------------------------------------------------------------------
118
+ // Helpers
119
+ // ---------------------------------------------------------------------------
120
+
121
+ function cargarPerfiles() {
122
+ try {
123
+ const data = JSON.parse(fs.readFileSync(PERFILES_PATH, 'utf8'));
124
+ return data.perfiles || {};
125
+ } catch (_) {
126
+ return {};
127
+ }
128
+ }
129
+
130
+ function construirItemsPerfil(perfiles) {
131
+ // Orden: core primero, completo al final, el resto alfabético
132
+ const keys = Object.keys(perfiles);
133
+ const ordenados = [];
134
+ if (keys.includes('core')) ordenados.push('core');
135
+ const intermedios = keys.filter(k => k !== 'core' && k !== 'completo').sort();
136
+ ordenados.push(...intermedios);
137
+ if (keys.includes('completo')) ordenados.push('completo');
138
+
139
+ return ordenados.map(k => {
140
+ const p = perfiles[k];
141
+ return {
142
+ valor: k,
143
+ etiqueta: k,
144
+ descripcion: p.descripcion || `Perfil ${k} con ${p.modulos?.length || 0} módulos`,
145
+ badge: k === 'core' ? 'mínimo' : k === 'completo' ? 'todo' : undefined,
146
+ };
147
+ });
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // Pantalla de preview
152
+ // ---------------------------------------------------------------------------
153
+
154
+ /**
155
+ * Renderiza una pantalla de preview con el resumen del plan y espera Enter
156
+ * (continuar a confirmación) o Esc (cancelar). Devuelve true/false.
157
+ */
158
+ function pantallaPreview(opciones, perfiles) {
159
+ return new Promise((resolve) => {
160
+ if (!render.ES_TTY || !process.stdin.isTTY) {
161
+ resolve(true);
162
+ return;
163
+ }
164
+
165
+ function _renderizar() {
166
+ render.limpiarPantalla();
167
+ const { cols } = render.obtenerDimensiones();
168
+
169
+ render.escribirEn(2, 3, semantico.titulo('Resumen del plan'));
170
+ render.escribirEn(3, 3, colores.dim('Revisa antes de confirmar:'));
171
+
172
+ const filas = [
173
+ ['Runtime', opciones.target],
174
+ ['Perfil', opciones.profile],
175
+ ['Scope', opciones.global ? 'global (~/.claude)' : 'proyecto (./.claude)'],
176
+ ['With MCP', opciones.with_mcp ? 'sí' : 'no'],
177
+ ['Dry-run', opciones.dry_run ? 'sí (no copia archivos)' : 'no'],
178
+ ];
179
+
180
+ if (opciones.profile === 'completo' && opciones.stacks?.length > 0) {
181
+ filas.push(['Stacks extra', opciones.stacks.join(', ')]);
182
+ }
183
+
184
+ const perfilInfo = perfiles[opciones.profile];
185
+ if (perfilInfo?.modulos) {
186
+ filas.push(['Módulos', String(perfilInfo.modulos.length)]);
187
+ }
188
+
189
+ filas.forEach((fila, i) => {
190
+ const [k, v] = fila;
191
+ render.escribirEn(5 + i, 5,
192
+ render.rellenarDer(colores.dim(k + ':'), 16) + semantico.enfasis(v));
193
+ });
194
+
195
+ // Si hay perfil con módulos, listar los primeros 8
196
+ if (perfilInfo?.modulos) {
197
+ const filaMod = 7 + filas.length;
198
+ render.escribirEn(filaMod, 5, colores.dim('Módulos incluidos:'));
199
+ const mostrar = perfilInfo.modulos.slice(0, 8);
200
+ mostrar.forEach((m, i) => {
201
+ render.escribirEn(filaMod + 1 + i, 7, colores.cyan(iconos.punto) + ' ' + m);
202
+ });
203
+ if (perfilInfo.modulos.length > 8) {
204
+ render.escribirEn(filaMod + 1 + mostrar.length, 7,
205
+ colores.dim(`... y ${perfilInfo.modulos.length - 8} más`));
206
+ }
207
+ }
208
+
209
+ render.dibujarPiePagina([
210
+ ['Enter', 'continuar a confirmación'],
211
+ ['Esc', 'cancelar'],
212
+ ]);
213
+ }
214
+
215
+ render.iniciarModoTui();
216
+ _renderizar();
217
+
218
+ const onResize = () => _renderizar();
219
+ process.stdout.on('resize', onResize);
220
+
221
+ const teclado = teclas.crearTeclado();
222
+
223
+ function _finalizar(continuar) {
224
+ teclado.desactivar();
225
+ process.stdout.removeListener('resize', onResize);
226
+ render.salirModoTui();
227
+ resolve(continuar);
228
+ }
229
+
230
+ teclado.on('return', () => _finalizar(true));
231
+ teclado.on('escape', () => _finalizar(false));
232
+ teclado.activar();
233
+ });
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // Wizard principal
238
+ // ---------------------------------------------------------------------------
239
+
240
+ async function ejecutarWizardInstall() {
241
+ const perfiles = cargarPerfiles();
242
+ if (Object.keys(perfiles).length === 0) {
243
+ return { exito: false, error: 'No se pudo cargar manifiestos/perfiles.json' };
244
+ }
245
+
246
+ // 1. Runtime
247
+ const target = await selectorUnico({
248
+ titulo: 'Paso 1/6 — ¿En qué runtime instalas SWL?',
249
+ items: RUNTIMES,
250
+ indiceDefault: 0,
251
+ });
252
+ if (!target) return { exito: false, cancelado: true };
253
+
254
+ // 2. Perfil
255
+ const profile = await selectorUnico({
256
+ titulo: 'Paso 2/6 — ¿Qué perfil instalas?',
257
+ items: construirItemsPerfil(perfiles),
258
+ indiceDefault: 0,
259
+ });
260
+ if (!profile) return { exito: false, cancelado: true };
261
+
262
+ // 3. Scope
263
+ const scope = await selectorUnico({
264
+ titulo: 'Paso 3/6 — ¿Dónde se instala?',
265
+ items: SCOPES,
266
+ indiceDefault: 0,
267
+ });
268
+ if (!scope) return { exito: false, cancelado: true };
269
+
270
+ // 4. Flags
271
+ const flagsSeleccionados = await selectorMulti({
272
+ titulo: 'Paso 4/6 — Flags adicionales (espacio para toggle):',
273
+ items: FLAGS,
274
+ });
275
+ if (flagsSeleccionados === null) return { exito: false, cancelado: true };
276
+
277
+ // 5. Stacks (solo si perfil = completo)
278
+ let stacks = [];
279
+ if (profile === 'completo') {
280
+ const elegidos = await selectorMulti({
281
+ titulo: 'Paso 5/6 — Stacks de lenguajes adicionales (perfil completo):',
282
+ items: STACKS_ADICIONALES,
283
+ });
284
+ if (elegidos === null) return { exito: false, cancelado: true };
285
+ stacks = elegidos;
286
+ }
287
+
288
+ const opciones = {
289
+ target,
290
+ profile,
291
+ global: scope === 'global',
292
+ with_mcp: flagsSeleccionados.includes('with-mcp'),
293
+ dry_run: flagsSeleccionados.includes('dry-run'),
294
+ all_langs: stacks.length > 0,
295
+ stacks,
296
+ };
297
+
298
+ // 6. Preview
299
+ const procederPreview = await pantallaPreview(opciones, perfiles);
300
+ if (!procederPreview) return { exito: false, cancelado: true };
301
+
302
+ // 7. Confirmación final (selector único con 2 opciones para claridad visual)
303
+ const confirmacion = await selectorUnico({
304
+ titulo: 'Paso 6/6 — Confirmar e iniciar instalación',
305
+ items: [
306
+ {
307
+ valor: 'si',
308
+ etiqueta: 'Sí, instalar ahora',
309
+ descripcion: 'Ejecuta el plan y muestra progreso. Puedes usar dry-run en el paso 4 si solo quieres ver qué pasaría.',
310
+ },
311
+ {
312
+ valor: 'no',
313
+ etiqueta: 'No, cancelar',
314
+ descripcion: 'Vuelve al menú principal sin tocar nada.',
315
+ },
316
+ ],
317
+ indiceDefault: 0,
318
+ });
319
+
320
+ if (confirmacion !== 'si') return { exito: false, cancelado: true };
321
+
322
+ return { exito: true, opciones };
323
+ }
324
+
325
+ module.exports = {
326
+ ejecutarWizardInstall,
327
+ // exports auxiliares para tests
328
+ RUNTIMES,
329
+ SCOPES,
330
+ STACKS_ADICIONALES,
331
+ FLAGS,
332
+ cargarPerfiles,
333
+ construirItemsPerfil,
334
+ };
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Menú principal de la TUI de swl-ses.
5
+ * 4 operaciones disponibles: Install / Update / Inspect / Uninstall.
6
+ *
7
+ * Devuelve uno de: 'install' | 'update' | 'inspect' | 'uninstall' | null
8
+ * (null = el usuario canceló con Escape)
9
+ */
10
+
11
+ const { selectorUnico } = require('../componentes/selector-unico');
12
+
13
+ const OPCIONES = [
14
+ {
15
+ valor: 'install',
16
+ etiqueta: 'Install — Instalar SWL en un runtime nuevo',
17
+ descripcion:
18
+ 'Asistente paso a paso: runtime + perfil + scope + flags. ' +
19
+ 'Detecta instalaciones existentes y avisa si hay conflictos de scope.',
20
+ },
21
+ {
22
+ valor: 'update',
23
+ etiqueta: 'Update — Actualizar instalaciones existentes',
24
+ descripcion:
25
+ 'Multi-select de runtimes a actualizar + componentes a refrescar ' +
26
+ '(skills, hooks, agentes, reglas, comandos). Muestra diff antes de aplicar.',
27
+ },
28
+ {
29
+ valor: 'inspect',
30
+ etiqueta: 'Inspect — Explorar componentes instalados',
31
+ descripcion:
32
+ 'Navega por runtime → perfil → componentes sin modificar nada. ' +
33
+ 'Lee de los manifiestos y archivos de estado.',
34
+ },
35
+ {
36
+ valor: 'uninstall',
37
+ etiqueta: 'Uninstall — Desinstalar SWL de un runtime',
38
+ descripcion:
39
+ 'Elige runtime y scope a desinstalar. Preserva _userland/ y APRENDIZAJES.md ' +
40
+ 'por default. Pide confirmación explícita antes de borrar.',
41
+ },
42
+ ];
43
+
44
+ function mostrarMenuPrincipal() {
45
+ return selectorUnico({
46
+ titulo: '¿Qué operación quieres realizar?',
47
+ items: OPCIONES,
48
+ indiceDefault: 0,
49
+ });
50
+ }
51
+
52
+ module.exports = { mostrarMenuPrincipal, OPCIONES };
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pantalla de progreso de la TUI.
5
+ * Diseño:
6
+ * - Cabecera con título de la operación (Install / Update)
7
+ * - Barra global de progreso con porcentaje
8
+ * - Tabla de contadores por categoría (skills, hooks, agentes, reglas, etc.)
9
+ * - Panel inferior con log rotativo (últimas N líneas)
10
+ *
11
+ * Modelo de uso:
12
+ *
13
+ * const ctrl = crearProgreso({ titulo, categorias });
14
+ * ctrl.iniciar();
15
+ *
16
+ * // El instalador emite eventos:
17
+ * ctrl.onEvento({ tipo: 'archivo-copiado', componente: 'skills', archivo: '...' });
18
+ * ctrl.onEvento({ tipo: 'componente-completado', componente: 'skills' });
19
+ * ctrl.onEvento({ tipo: 'log', linea: 'Backup creado: ...' });
20
+ *
21
+ * // Al terminar:
22
+ * ctrl.finalizar({ ok: true, mensaje: 'Instalación completa' });
23
+ *
24
+ * En no-TTY: imprime líneas simples a stdout sin esperar.
25
+ */
26
+
27
+ const render = require('../lib/render');
28
+ const teclas = require('../lib/teclas');
29
+ const { colores, semantico, iconos } = require('../lib/colores');
30
+
31
+ const MAX_LOG_LINEAS_DEFAULT = 8;
32
+ const MAX_LOG_LINEAS_VERBOSE = 24;
33
+
34
+ // Compat: el contador histórico exportado seguía siendo MAX_LOG_LINEAS.
35
+ // Lo mantenemos para no romper consumidores externos.
36
+ const MAX_LOG_LINEAS = MAX_LOG_LINEAS_DEFAULT;
37
+
38
+ /**
39
+ * @param {object} opciones
40
+ * @param {string} opciones.titulo - Encabezado (ej: "Instalando SWL en Claude Code...")
41
+ * @param {Array<{nombre:string, etiqueta:string, total:number}>} opciones.categorias
42
+ * Categorías a contar. Ej: [{ nombre:'skills', etiqueta:'Skills', total:162 }, ...]
43
+ * @param {boolean} [opciones.verbose=false] - Expande el panel de log para mostrar
44
+ * más líneas (24 vs 8) y deshabilita el truncado del log por archivo.
45
+ * Util cuando se quiere depurar qué hace exactamente el instalador.
46
+ */
47
+ function crearProgreso(opciones) {
48
+ const titulo = opciones.titulo || 'Procesando...';
49
+ const categorias = opciones.categorias || [];
50
+ const verbose = !!opciones.verbose;
51
+ const maxLogLineas = verbose ? MAX_LOG_LINEAS_VERBOSE : MAX_LOG_LINEAS_DEFAULT;
52
+
53
+ // Estado interno
54
+ const conteos = new Map(); // nombre → contador actual
55
+ for (const c of categorias) conteos.set(c.nombre, 0);
56
+ const logBuffer = []; // últimas N líneas
57
+ let finalizado = false;
58
+ let mensajeFinal = '';
59
+ let okFinal = true;
60
+ let onResize = null;
61
+ let teclado = null;
62
+ let resolverEspera = null;
63
+
64
+ function _porcentajeGlobal() {
65
+ let hecho = 0, total = 0;
66
+ for (const c of categorias) {
67
+ hecho += Math.min(conteos.get(c.nombre) || 0, c.total);
68
+ total += c.total;
69
+ }
70
+ return total > 0 ? hecho / total : 0;
71
+ }
72
+
73
+ function _renderizar() {
74
+ if (!render.ES_TTY) return;
75
+ render.limpiarPantalla();
76
+ const { cols, rows } = render.obtenerDimensiones();
77
+
78
+ // Cabecera
79
+ render.escribirEn(2, 3, semantico.titulo(titulo));
80
+
81
+ // Barra global
82
+ const filaBarra = 4;
83
+ render.escribirEn(filaBarra, 3, colores.dim('Progreso global'));
84
+ render.dibujarBarra(filaBarra + 1, 3, Math.min(cols - 6, 60), _porcentajeGlobal());
85
+
86
+ // Contadores por categoría
87
+ const filaCat = filaBarra + 4;
88
+ render.escribirEn(filaCat - 1, 3, colores.dim('Por categoría:'));
89
+ categorias.forEach((c, i) => {
90
+ const actual = conteos.get(c.nombre) || 0;
91
+ const pct = c.total > 0 ? actual / c.total : 0;
92
+ const completo = actual >= c.total && c.total > 0;
93
+ const icono = completo ? semantico.exito(iconos.check) : (actual > 0 ? semantico.info(iconos.arrow) : colores.dim(iconos.punto));
94
+ const linea =
95
+ `${icono} ` +
96
+ render.rellenarDer(colores.negrita(c.etiqueta), 14) +
97
+ render.rellenarDer(`${actual}/${c.total}`, 12);
98
+ render.escribirEn(filaCat + i, 5, linea);
99
+ // Mini-barra al lado
100
+ const anchoMini = Math.min(20, cols - 50);
101
+ if (anchoMini > 8) {
102
+ render.dibujarBarra(filaCat + i, 32, anchoMini, pct, {
103
+ colorLleno: completo ? colores.verde : colores.cyan,
104
+ });
105
+ }
106
+ });
107
+
108
+ // Panel inferior con log rotativo
109
+ const filaLog = filaCat + categorias.length + 2;
110
+ const altoLog = Math.min(maxLogLineas + 2, rows - filaLog - 2);
111
+ if (altoLog >= 3) {
112
+ const tituloLog = verbose
113
+ ? `Log detallado (verbose, ${maxLogLineas} líneas)`
114
+ : 'Log (últimas líneas)';
115
+ render.dibujarCaja(filaLog, 3, cols - 5, altoLog, {
116
+ titulo: tituloLog,
117
+ color: colores.dim,
118
+ });
119
+ const lineasMostradas = logBuffer.slice(-Math.max(1, altoLog - 2));
120
+ lineasMostradas.forEach((l, i) => {
121
+ render.escribirEn(filaLog + 1 + i, 5,
122
+ render.recortar(colores.dim(l), cols - 9));
123
+ });
124
+ }
125
+
126
+ // Pie
127
+ if (finalizado) {
128
+ const colorPie = okFinal ? semantico.exito : semantico.error;
129
+ const ico = okFinal ? iconos.check : iconos.cross;
130
+ render.escribirEn(rows - 2, 3,
131
+ colorPie(`${ico} ${mensajeFinal} ${colores.dim('— Enter para continuar')}`));
132
+ } else {
133
+ render.dibujarPiePagina([
134
+ ['Esc', 'cancelar'],
135
+ ]);
136
+ }
137
+ }
138
+
139
+ // ── API pública ───────────────────────────────────────────────────────────
140
+
141
+ function iniciar() {
142
+ if (!render.ES_TTY) {
143
+ console.log('');
144
+ console.log(` ${titulo}`);
145
+ return;
146
+ }
147
+ render.iniciarModoTui();
148
+ _renderizar();
149
+ onResize = () => _renderizar();
150
+ process.stdout.on('resize', onResize);
151
+ teclado = teclas.crearTeclado();
152
+ teclado.on('escape', () => {
153
+ // No interrumpimos directamente: el caller decide cómo manejar.
154
+ // Aquí solo registramos en el log.
155
+ onEvento({ tipo: 'log', linea: '[usuario presionó Esc — ignorado durante ejecución]' });
156
+ });
157
+ teclado.activar();
158
+ }
159
+
160
+ /**
161
+ * Recibe eventos del instalador.
162
+ * tipos soportados:
163
+ * - 'archivo-copiado' { componente, archivo? }
164
+ * - 'componente-completado' { componente }
165
+ * - 'log' { linea }
166
+ * - 'set-total' { componente, total } — actualizar total dinámico
167
+ */
168
+ function onEvento(evento) {
169
+ if (!evento || !evento.tipo) return;
170
+
171
+ switch (evento.tipo) {
172
+ case 'archivo-copiado':
173
+ if (evento.componente) {
174
+ const actual = conteos.get(evento.componente) || 0;
175
+ conteos.set(evento.componente, actual + 1);
176
+ }
177
+ if (evento.archivo) {
178
+ logBuffer.push(`${semantico.exito('+')} ${evento.componente}: ${evento.archivo}`);
179
+ if (logBuffer.length > maxLogLineas * 2) logBuffer.splice(0, logBuffer.length - maxLogLineas * 2);
180
+ }
181
+ break;
182
+ case 'componente-completado':
183
+ if (evento.componente) {
184
+ const cat = categorias.find(c => c.nombre === evento.componente);
185
+ if (cat) conteos.set(evento.componente, cat.total);
186
+ }
187
+ break;
188
+ case 'log':
189
+ if (evento.linea) {
190
+ logBuffer.push(evento.linea);
191
+ if (logBuffer.length > maxLogLineas * 2) logBuffer.splice(0, logBuffer.length - maxLogLineas * 2);
192
+ }
193
+ break;
194
+ case 'set-total':
195
+ if (evento.componente && typeof evento.total === 'number') {
196
+ const cat = categorias.find(c => c.nombre === evento.componente);
197
+ if (cat) cat.total = evento.total;
198
+ }
199
+ break;
200
+ }
201
+
202
+ _renderizar();
203
+ if (!render.ES_TTY && evento.linea) {
204
+ // Modo no-TTY: imprimir log lineal
205
+ console.log(` ${evento.linea}`);
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Marca la pantalla como finalizada. El usuario debe presionar Enter para
211
+ * cerrar. Resuelve la promise devuelta por esperarSalida().
212
+ */
213
+ function finalizar(opts = {}) {
214
+ finalizado = true;
215
+ okFinal = opts.ok !== false;
216
+ mensajeFinal = opts.mensaje || (okFinal ? 'Completado' : 'Falló');
217
+ if (!render.ES_TTY) {
218
+ console.log('');
219
+ console.log(` ${okFinal ? '[OK]' : '[ERROR]'} ${mensajeFinal}`);
220
+ if (resolverEspera) resolverEspera();
221
+ return;
222
+ }
223
+ _renderizar();
224
+
225
+ if (teclado) {
226
+ teclado.on('return', () => {
227
+ cerrar();
228
+ if (resolverEspera) {
229
+ const r = resolverEspera;
230
+ resolverEspera = null;
231
+ r();
232
+ }
233
+ });
234
+ }
235
+ }
236
+
237
+ function cerrar() {
238
+ if (teclado) teclado.desactivar();
239
+ if (onResize) process.stdout.removeListener('resize', onResize);
240
+ render.salirModoTui();
241
+ }
242
+
243
+ /**
244
+ * Devuelve una promise que se resuelve cuando el usuario presiona Enter
245
+ * después de finalizar(). En no-TTY se resuelve inmediatamente al finalizar.
246
+ */
247
+ function esperarSalida() {
248
+ return new Promise((resolve) => {
249
+ if (finalizado && !render.ES_TTY) {
250
+ resolve();
251
+ return;
252
+ }
253
+ resolverEspera = resolve;
254
+ });
255
+ }
256
+
257
+ return {
258
+ iniciar,
259
+ onEvento,
260
+ finalizar,
261
+ cerrar,
262
+ esperarSalida,
263
+ // exports auxiliares para tests
264
+ _getEstado: () => ({
265
+ conteos: Object.fromEntries(conteos),
266
+ logBuffer: [...logBuffer],
267
+ finalizado,
268
+ mensajeFinal,
269
+ okFinal,
270
+ }),
271
+ };
272
+ }
273
+
274
+ module.exports = { crearProgreso, MAX_LOG_LINEAS, MAX_LOG_LINEAS_DEFAULT, MAX_LOG_LINEAS_VERBOSE };