versacompiler 2.0.7 → 2.0.8
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/dist/compiler/compile.js +26 -2332
- package/dist/compiler/error-reporter.js +38 -467
- package/dist/compiler/linter.js +1 -72
- package/dist/compiler/minify.js +1 -229
- package/dist/compiler/module-resolution-optimizer.js +1 -821
- package/dist/compiler/parser.js +1 -203
- package/dist/compiler/performance-monitor.js +56 -192
- package/dist/compiler/tailwindcss.js +1 -39
- package/dist/compiler/transform-optimizer.js +1 -392
- package/dist/compiler/transformTStoJS.js +1 -16
- package/dist/compiler/transforms.js +1 -550
- package/dist/compiler/typescript-compiler.js +2 -172
- package/dist/compiler/typescript-error-parser.js +10 -281
- package/dist/compiler/typescript-manager.js +2 -273
- package/dist/compiler/typescript-sync-validator.js +31 -295
- package/dist/compiler/typescript-worker-pool.js +1 -842
- package/dist/compiler/typescript-worker-thread.cjs +41 -466
- package/dist/compiler/typescript-worker.js +1 -339
- package/dist/compiler/vuejs.js +37 -392
- package/dist/hrm/VueHRM.js +1 -353
- package/dist/hrm/errorScreen.js +1 -83
- package/dist/hrm/getInstanciaVue.js +1 -313
- package/dist/hrm/initHRM.js +1 -141
- package/dist/main.js +7 -347
- package/dist/servicios/browserSync.js +5 -501
- package/dist/servicios/file-watcher.js +4 -379
- package/dist/servicios/logger.js +3 -63
- package/dist/servicios/readConfig.js +105 -430
- package/dist/utils/excluded-modules.js +1 -36
- package/dist/utils/module-resolver.js +1 -466
- package/dist/utils/promptUser.js +2 -48
- package/dist/utils/proxyValidator.js +1 -68
- package/dist/utils/resolve-bin.js +1 -48
- package/dist/utils/utils.js +1 -21
- package/dist/utils/vue-types-setup.js +241 -435
- package/dist/wrappers/eslint-node.js +1 -145
- package/dist/wrappers/oxlint-node.js +1 -120
- package/dist/wrappers/tailwind-node.js +1 -92
- package/package.json +36 -35
|
@@ -1,339 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* TypeScript Worker Manager - Gestiona workers dedicados para type checking asíncrono
|
|
3
|
-
* Implementa el patrón Singleton para reutilizar workers entre compilaciones
|
|
4
|
-
*/
|
|
5
|
-
import * as path from 'node:path';
|
|
6
|
-
import * as process from 'node:process';
|
|
7
|
-
import { Worker } from 'node:worker_threads';
|
|
8
|
-
import { validateTypesWithLanguageService } from './typescript-sync-validator.js';
|
|
9
|
-
/**
|
|
10
|
-
* Gestiona workers dedicados para type checking asíncrono de TypeScript
|
|
11
|
-
* Implementa patrón Singleton para eficiencia y reutilización de recursos
|
|
12
|
-
*/
|
|
13
|
-
export class TypeScriptWorkerManager {
|
|
14
|
-
static instance;
|
|
15
|
-
worker = null;
|
|
16
|
-
pendingTasks = new Map();
|
|
17
|
-
taskCounter = 0;
|
|
18
|
-
workerReady = false;
|
|
19
|
-
initPromise = null; // Configuración del worker private readonly WORKER_TIMEOUT = 45000; // 45 segundos timeout (incrementado para manejar concurrencia)
|
|
20
|
-
MAX_RETRY_ATTEMPTS = 2;
|
|
21
|
-
MAX_CONCURRENT_TASKS = 20; // Aumentar límite de tareas concurrentes
|
|
22
|
-
TASK_TIMEOUT = 15000; // 15 segundos timeout por tarea individual
|
|
23
|
-
// NUEVOS: Gestión de modo y estado para optimización
|
|
24
|
-
currentMode = null;
|
|
25
|
-
constructor() { }
|
|
26
|
-
/**
|
|
27
|
-
* NUEVO: Configura el modo de operación del worker
|
|
28
|
-
*/
|
|
29
|
-
setMode(mode) {
|
|
30
|
-
this.currentMode = mode;
|
|
31
|
-
// En modo watch, el worker se mantiene activo más tiempo
|
|
32
|
-
// En otros modos, se puede optimizar la gestión de recursos
|
|
33
|
-
console.log(`[WorkerManager] Modo establecido: ${mode}`);
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Obtiene la instancia singleton del Worker Manager
|
|
37
|
-
*/
|
|
38
|
-
static getInstance() {
|
|
39
|
-
if (!TypeScriptWorkerManager.instance) {
|
|
40
|
-
TypeScriptWorkerManager.instance = new TypeScriptWorkerManager();
|
|
41
|
-
}
|
|
42
|
-
return TypeScriptWorkerManager.instance;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* Inicializa el worker thread de TypeScript
|
|
46
|
-
*/
|
|
47
|
-
async initializeWorker() {
|
|
48
|
-
if (this.initPromise) {
|
|
49
|
-
return this.initPromise;
|
|
50
|
-
}
|
|
51
|
-
this.initPromise = this._performWorkerInitialization();
|
|
52
|
-
return this.initPromise;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Realiza la inicialización del worker thread
|
|
56
|
-
*/ async _performWorkerInitialization() {
|
|
57
|
-
try {
|
|
58
|
-
console.log('[WorkerManager] 🚀 Iniciando proceso de inicialización del worker...'); // Obtener ruta al worker thread (compatible con ES modules y Windows)
|
|
59
|
-
const workerPath = path.join(process.env.PATH_PROY || path.join(process.cwd(), 'src'), 'compiler', 'typescript-worker-thread.cjs');
|
|
60
|
-
console.log('[WorkerManager] 📂 Ruta del worker:', workerPath);
|
|
61
|
-
console.log('[WorkerManager] 🌍 PATH_PROY:', process.env.PATH_PROY);
|
|
62
|
-
console.log('[WorkerManager] 📁 CWD:', process.cwd());
|
|
63
|
-
// Verificar que el archivo existe
|
|
64
|
-
const fs = await import('node:fs');
|
|
65
|
-
const exists = fs.existsSync(workerPath);
|
|
66
|
-
console.log('[WorkerManager] 📋 Worker file exists:', exists);
|
|
67
|
-
// Crear el worker thread sin tsx para evitar dependencias externas
|
|
68
|
-
console.log('[WorkerManager] 🔧 Creando Worker...');
|
|
69
|
-
this.worker = new Worker(workerPath, {
|
|
70
|
-
env: {
|
|
71
|
-
...process.env,
|
|
72
|
-
NODE_OPTIONS: '', // Limpiar NODE_OPTIONS para evitar conflictos con tsx
|
|
73
|
-
},
|
|
74
|
-
});
|
|
75
|
-
console.log('[WorkerManager] ✅ Worker creado, configurando listeners...');
|
|
76
|
-
// Configurar listeners del worker
|
|
77
|
-
this.setupWorkerListeners();
|
|
78
|
-
console.log('[WorkerManager] ⏳ Esperando que el worker esté listo...');
|
|
79
|
-
// Esperar a que el worker esté listo
|
|
80
|
-
await this.waitForWorkerReady();
|
|
81
|
-
console.log('[WorkerManager] ✅ Worker inicializado exitosamente');
|
|
82
|
-
}
|
|
83
|
-
catch (error) {
|
|
84
|
-
console.error('[WorkerManager] ❌ Error inicializando worker:', error);
|
|
85
|
-
this.worker = null;
|
|
86
|
-
this.workerReady = false;
|
|
87
|
-
throw error;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Configura los listeners del worker thread
|
|
92
|
-
*/
|
|
93
|
-
setupWorkerListeners() {
|
|
94
|
-
if (!this.worker)
|
|
95
|
-
return;
|
|
96
|
-
this.worker.on('message', (response) => {
|
|
97
|
-
try {
|
|
98
|
-
// console.log('[WorkerManager] Mensaje recibido del worker:', {
|
|
99
|
-
// id: response.id,
|
|
100
|
-
// success: response.success,
|
|
101
|
-
// hasErrors: response.hasErrors,
|
|
102
|
-
// diagnosticsCount: response.diagnostics?.length,
|
|
103
|
-
// });
|
|
104
|
-
// Manejar mensaje de worker ready
|
|
105
|
-
if (response.id === 'worker-ready') {
|
|
106
|
-
this.workerReady = true;
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
109
|
-
// Buscar la tarea pendiente correspondiente
|
|
110
|
-
const pendingTask = this.pendingTasks.get(response.id);
|
|
111
|
-
if (!pendingTask) {
|
|
112
|
-
console.warn('[WorkerManager] Respuesta para tarea desconocida:', response.id);
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
// Limpiar timeout y eliminar tarea pendiente
|
|
116
|
-
clearTimeout(pendingTask.timeout);
|
|
117
|
-
this.pendingTasks.delete(response.id);
|
|
118
|
-
// Procesar respuesta
|
|
119
|
-
if (response.success &&
|
|
120
|
-
response.diagnostics !== undefined &&
|
|
121
|
-
response.hasErrors !== undefined) {
|
|
122
|
-
pendingTask.resolve({
|
|
123
|
-
diagnostics: response.diagnostics,
|
|
124
|
-
hasErrors: response.hasErrors,
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
const errorMessage = response.error || 'Error desconocido del worker';
|
|
129
|
-
pendingTask.reject(new Error(errorMessage));
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
catch (error) {
|
|
133
|
-
console.error('[WorkerManager] Error procesando respuesta del worker:', error);
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
this.worker.on('error', error => {
|
|
137
|
-
console.error('[WorkerManager] Error en worker thread:', error);
|
|
138
|
-
this.handleWorkerError(error);
|
|
139
|
-
});
|
|
140
|
-
this.worker.on('exit', code => {
|
|
141
|
-
console.warn('[WorkerManager] Worker thread cerrado con código:', code);
|
|
142
|
-
this.workerReady = false;
|
|
143
|
-
// Rechazar todas las tareas pendientes
|
|
144
|
-
this.pendingTasks.forEach(task => {
|
|
145
|
-
clearTimeout(task.timeout);
|
|
146
|
-
task.reject(new Error(`Worker cerrado inesperadamente con código ${code}`));
|
|
147
|
-
});
|
|
148
|
-
this.pendingTasks.clear();
|
|
149
|
-
});
|
|
150
|
-
} /**
|
|
151
|
-
* Espera a que el worker esté listo para recibir tareas
|
|
152
|
-
*/
|
|
153
|
-
async waitForWorkerReady() {
|
|
154
|
-
return new Promise((resolve, reject) => {
|
|
155
|
-
// Reducir timeout para inicialización a 5 segundos
|
|
156
|
-
const timeout = setTimeout(() => {
|
|
157
|
-
reject(new Error('Timeout esperando a que el worker esté listo'));
|
|
158
|
-
}, 5000);
|
|
159
|
-
const checkReady = () => {
|
|
160
|
-
if (this.workerReady) {
|
|
161
|
-
clearTimeout(timeout);
|
|
162
|
-
resolve();
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
setTimeout(checkReady, 50); // Verificar cada 50ms (más frecuente)
|
|
166
|
-
}
|
|
167
|
-
};
|
|
168
|
-
checkReady();
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Maneja errores del worker thread
|
|
173
|
-
*/
|
|
174
|
-
handleWorkerError(error) {
|
|
175
|
-
console.error('[WorkerManager] Manejando error del worker:', error);
|
|
176
|
-
// Rechazar todas las tareas pendientes
|
|
177
|
-
this.pendingTasks.forEach(task => {
|
|
178
|
-
clearTimeout(task.timeout);
|
|
179
|
-
task.reject(new Error(`Error en worker: ${error.message}`));
|
|
180
|
-
});
|
|
181
|
-
this.pendingTasks.clear();
|
|
182
|
-
// Marcar worker como no disponible
|
|
183
|
-
this.workerReady = false;
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Genera un ID único para cada tarea
|
|
187
|
-
*/
|
|
188
|
-
generateTaskId() {
|
|
189
|
-
return `task-${++this.taskCounter}-${Date.now()}`;
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Realiza type checking usando el worker thread (con fallback síncrono)
|
|
193
|
-
* @param fileName - Nombre del archivo TypeScript
|
|
194
|
-
* @param content - Contenido del archivo
|
|
195
|
-
* @param compilerOptions - Opciones del compilador TypeScript
|
|
196
|
-
* @returns Resultado de la validación de tipos
|
|
197
|
-
*/ async typeCheck(fileName, content, compilerOptions) {
|
|
198
|
-
// Limitar tareas concurrentes para evitar saturación
|
|
199
|
-
if (this.pendingTasks.size >= this.MAX_CONCURRENT_TASKS) {
|
|
200
|
-
return this.typeCheckWithSyncFallback(fileName, content, compilerOptions);
|
|
201
|
-
}
|
|
202
|
-
// En modo de testing o si hay problemas de inicialización, usar fallback directo
|
|
203
|
-
if (process.env.NODE_ENV === 'test' || !this.worker) {
|
|
204
|
-
if (!this.worker) {
|
|
205
|
-
try {
|
|
206
|
-
await this.initializeWorker();
|
|
207
|
-
if (this.worker && this.workerReady) {
|
|
208
|
-
console.log('[WorkerManager] ✅ Worker inicializado exitosamente, reintentando...');
|
|
209
|
-
return this.typeCheckWithWorker(fileName, content, compilerOptions);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
catch (error) {
|
|
213
|
-
console.error('[WorkerManager] ❌ Error inicializando worker:', error);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
console.log('[WorkerManager] 🔄 Usando fallback síncrono (test mode o worker no disponible)');
|
|
217
|
-
return this.typeCheckWithSyncFallback(fileName, content, compilerOptions);
|
|
218
|
-
}
|
|
219
|
-
try {
|
|
220
|
-
console.log('[WorkerManager] 🚀 Intentando usar worker thread...');
|
|
221
|
-
// Intentar usar el worker thread con timeout más realista
|
|
222
|
-
const workerPromise = this.typeCheckWithWorker(fileName, content, compilerOptions);
|
|
223
|
-
const timeoutPromise = new Promise((resolve, reject) => {
|
|
224
|
-
setTimeout(() => {
|
|
225
|
-
console.log('[WorkerManager] ⏰ Worker timeout, usando fallback');
|
|
226
|
-
reject(new Error('Worker timeout - usando fallback'));
|
|
227
|
-
}, this.TASK_TIMEOUT); // Usar timeout por tarea más realista
|
|
228
|
-
});
|
|
229
|
-
console.log('[WorkerManager] ⏳ Esperando respuesta del worker...');
|
|
230
|
-
const result = await Promise.race([workerPromise, timeoutPromise]);
|
|
231
|
-
console.log('[WorkerManager] ✅ Worker completado exitosamente');
|
|
232
|
-
return result;
|
|
233
|
-
}
|
|
234
|
-
catch (workerError) {
|
|
235
|
-
const errorMessage = workerError instanceof Error
|
|
236
|
-
? workerError.message
|
|
237
|
-
: String(workerError);
|
|
238
|
-
console.warn('[WorkerManager] ❌ Error en worker, usando fallback síncrono:', errorMessage);
|
|
239
|
-
// Fallback a validación síncrona
|
|
240
|
-
return this.typeCheckWithSyncFallback(fileName, content, compilerOptions);
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
/**
|
|
244
|
-
* Realiza type checking usando el worker thread
|
|
245
|
-
*/
|
|
246
|
-
async typeCheckWithWorker(fileName, content, compilerOptions) {
|
|
247
|
-
// Asegurar que el worker esté inicializado
|
|
248
|
-
await this.initializeWorker();
|
|
249
|
-
if (!this.worker || !this.workerReady) {
|
|
250
|
-
throw new Error('Worker no disponible');
|
|
251
|
-
}
|
|
252
|
-
return new Promise((resolve, reject) => {
|
|
253
|
-
const taskId = this.generateTaskId(); // Configurar timeout para la tarea
|
|
254
|
-
const timeout = setTimeout(() => {
|
|
255
|
-
this.pendingTasks.delete(taskId);
|
|
256
|
-
reject(new Error(`Timeout en type checking para ${fileName}`));
|
|
257
|
-
}, this.TASK_TIMEOUT);
|
|
258
|
-
// Agregar tarea a la lista de pendientes
|
|
259
|
-
this.pendingTasks.set(taskId, {
|
|
260
|
-
resolve,
|
|
261
|
-
reject,
|
|
262
|
-
timeout,
|
|
263
|
-
});
|
|
264
|
-
try {
|
|
265
|
-
// Crear mensaje para el worker
|
|
266
|
-
const message = {
|
|
267
|
-
id: taskId,
|
|
268
|
-
fileName,
|
|
269
|
-
content,
|
|
270
|
-
compilerOptions,
|
|
271
|
-
};
|
|
272
|
-
// console.log('[WorkerManager] Enviando tarea al worker:', {
|
|
273
|
-
// id: taskId,
|
|
274
|
-
// fileName,
|
|
275
|
-
// contentLength: content.length,
|
|
276
|
-
// compilerOptionsKeys: Object.keys(compilerOptions),
|
|
277
|
-
// });
|
|
278
|
-
// Enviar mensaje al worker
|
|
279
|
-
this.worker.postMessage(message);
|
|
280
|
-
}
|
|
281
|
-
catch (error) {
|
|
282
|
-
// Limpiar en caso de error
|
|
283
|
-
clearTimeout(timeout);
|
|
284
|
-
this.pendingTasks.delete(taskId);
|
|
285
|
-
reject(error);
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* Fallback síncrono para type checking cuando el worker no está disponible
|
|
291
|
-
*/
|
|
292
|
-
typeCheckWithSyncFallback(fileName, content, compilerOptions) {
|
|
293
|
-
// console.log(
|
|
294
|
-
// '[WorkerManager] Ejecutando type checking síncrono como fallback',
|
|
295
|
-
// );
|
|
296
|
-
try {
|
|
297
|
-
return validateTypesWithLanguageService(fileName, content, compilerOptions);
|
|
298
|
-
}
|
|
299
|
-
catch (error) {
|
|
300
|
-
console.error('[WorkerManager] Error en fallback síncrono:', error);
|
|
301
|
-
// Devolver resultado vacío en caso de error total
|
|
302
|
-
return {
|
|
303
|
-
diagnostics: [],
|
|
304
|
-
hasErrors: false,
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
/**
|
|
309
|
-
* Cierra el worker thread y limpia recursos
|
|
310
|
-
*/
|
|
311
|
-
async terminate() {
|
|
312
|
-
if (this.worker) {
|
|
313
|
-
// console.log('[WorkerManager] Cerrando worker thread...');
|
|
314
|
-
// Rechazar todas las tareas pendientes
|
|
315
|
-
this.pendingTasks.forEach(task => {
|
|
316
|
-
clearTimeout(task.timeout);
|
|
317
|
-
task.reject(new Error('Worker manager cerrado'));
|
|
318
|
-
});
|
|
319
|
-
this.pendingTasks.clear();
|
|
320
|
-
// Cerrar worker
|
|
321
|
-
await this.worker.terminate();
|
|
322
|
-
this.worker = null;
|
|
323
|
-
this.workerReady = false;
|
|
324
|
-
this.initPromise = null;
|
|
325
|
-
// console.log('[WorkerManager] Worker cerrado exitosamente');
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
/**
|
|
329
|
-
* Obtiene estadísticas del worker manager
|
|
330
|
-
*/
|
|
331
|
-
getStats() {
|
|
332
|
-
return {
|
|
333
|
-
workerReady: this.workerReady,
|
|
334
|
-
pendingTasks: this.pendingTasks.size,
|
|
335
|
-
taskCounter: this.taskCounter,
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
//# sourceMappingURL=typescript-worker.js.map
|
|
1
|
+
import*as e from"node:path";import*as t from"node:process";import{Worker as n}from"node:worker_threads";import{validateTypesWithLanguageService as r}from"./typescript-sync-validator.js";export class TypeScriptWorkerManager{static instance;worker=null;pendingTasks=new Map;taskCounter=0;workerReady=!1;initPromise=null;MAX_RETRY_ATTEMPTS=2;MAX_CONCURRENT_TASKS=20;TASK_TIMEOUT=15e3;currentMode=null;constructor(){}setMode(e){this.currentMode=e,console.log(`[WorkerManager] Modo establecido: ${e}`)}static getInstance(){return TypeScriptWorkerManager.instance||=new TypeScriptWorkerManager,TypeScriptWorkerManager.instance}async initializeWorker(){return this.initPromise||=this._performWorkerInitialization(),this.initPromise}async _performWorkerInitialization(){try{console.log(`[WorkerManager] 🚀 Iniciando proceso de inicialización del worker...`);let r=e.join(t.env.PATH_PROY||e.join(t.cwd(),`src`),`compiler`,`typescript-worker-thread.cjs`);console.log(`[WorkerManager] 📂 Ruta del worker:`,r),console.log(`[WorkerManager] 🌍 PATH_PROY:`,t.env.PATH_PROY),console.log(`[WorkerManager] 📁 CWD:`,t.cwd());let i=await import(`node:fs`),a=i.existsSync(r);console.log(`[WorkerManager] 📋 Worker file exists:`,a),console.log(`[WorkerManager] 🔧 Creando Worker...`),this.worker=new n(r,{env:{...t.env,NODE_OPTIONS:``}}),console.log(`[WorkerManager] ✅ Worker creado, configurando listeners...`),this.setupWorkerListeners(),console.log(`[WorkerManager] ⏳ Esperando que el worker esté listo...`),await this.waitForWorkerReady(),console.log(`[WorkerManager] ✅ Worker inicializado exitosamente`)}catch(e){throw console.error(`[WorkerManager] ❌ Error inicializando worker:`,e),this.worker=null,this.workerReady=!1,e}}setupWorkerListeners(){this.worker&&(this.worker.on(`message`,e=>{try{if(e.id===`worker-ready`){this.workerReady=!0;return}let t=this.pendingTasks.get(e.id);if(!t){console.warn(`[WorkerManager] Respuesta para tarea desconocida:`,e.id);return}if(clearTimeout(t.timeout),this.pendingTasks.delete(e.id),e.success&&e.diagnostics!==void 0&&e.hasErrors!==void 0)t.resolve({diagnostics:e.diagnostics,hasErrors:e.hasErrors});else{let n=e.error||`Error desconocido del worker`;t.reject(Error(n))}}catch(e){console.error(`[WorkerManager] Error procesando respuesta del worker:`,e)}}),this.worker.on(`error`,e=>{console.error(`[WorkerManager] Error en worker thread:`,e),this.handleWorkerError(e)}),this.worker.on(`exit`,e=>{console.warn(`[WorkerManager] Worker thread cerrado con código:`,e),this.workerReady=!1,this.pendingTasks.forEach(t=>{clearTimeout(t.timeout),t.reject(Error(`Worker cerrado inesperadamente con código ${e}`))}),this.pendingTasks.clear()}))}async waitForWorkerReady(){return new Promise((e,t)=>{let n=setTimeout(()=>{t(Error(`Timeout esperando a que el worker esté listo`))},5e3),r=()=>{this.workerReady?(clearTimeout(n),e()):setTimeout(r,50)};r()})}handleWorkerError(e){console.error(`[WorkerManager] Manejando error del worker:`,e),this.pendingTasks.forEach(t=>{clearTimeout(t.timeout),t.reject(Error(`Error en worker: ${e.message}`))}),this.pendingTasks.clear(),this.workerReady=!1}generateTaskId(){return`task-${++this.taskCounter}-${Date.now()}`}async typeCheck(e,n,r){if(this.pendingTasks.size>=this.MAX_CONCURRENT_TASKS)return this.typeCheckWithSyncFallback(e,n,r);if(t.env.NODE_ENV===`test`||!this.worker){if(!this.worker)try{if(await this.initializeWorker(),this.worker&&this.workerReady)return console.log(`[WorkerManager] ✅ Worker inicializado exitosamente, reintentando...`),this.typeCheckWithWorker(e,n,r)}catch(e){console.error(`[WorkerManager] ❌ Error inicializando worker:`,e)}return console.log(`[WorkerManager] 🔄 Usando fallback síncrono (test mode o worker no disponible)`),this.typeCheckWithSyncFallback(e,n,r)}try{console.log(`[WorkerManager] 🚀 Intentando usar worker thread...`);let t=this.typeCheckWithWorker(e,n,r),i=new Promise((e,t)=>{setTimeout(()=>{console.log(`[WorkerManager] ⏰ Worker timeout, usando fallback`),t(Error(`Worker timeout - usando fallback`))},this.TASK_TIMEOUT)});console.log(`[WorkerManager] ⏳ Esperando respuesta del worker...`);let a=await Promise.race([t,i]);return console.log(`[WorkerManager] ✅ Worker completado exitosamente`),a}catch(t){let i=t instanceof Error?t.message:String(t);return console.warn(`[WorkerManager] ❌ Error en worker, usando fallback síncrono:`,i),this.typeCheckWithSyncFallback(e,n,r)}}async typeCheckWithWorker(e,t,n){if(await this.initializeWorker(),!this.worker||!this.workerReady)throw Error(`Worker no disponible`);return new Promise((r,i)=>{let a=this.generateTaskId(),o=setTimeout(()=>{this.pendingTasks.delete(a),i(Error(`Timeout en type checking para ${e}`))},this.TASK_TIMEOUT);this.pendingTasks.set(a,{resolve:r,reject:i,timeout:o});try{let r={id:a,fileName:e,content:t,compilerOptions:n};this.worker.postMessage(r)}catch(e){clearTimeout(o),this.pendingTasks.delete(a),i(e)}})}typeCheckWithSyncFallback(e,t,n){try{return r(e,t,n)}catch(e){return console.error(`[WorkerManager] Error en fallback síncrono:`,e),{diagnostics:[],hasErrors:!1}}}async terminate(){this.worker&&(this.pendingTasks.forEach(e=>{clearTimeout(e.timeout),e.reject(Error(`Worker manager cerrado`))}),this.pendingTasks.clear(),await this.worker.terminate(),this.worker=null,this.workerReady=!1,this.initPromise=null)}getStats(){return{workerReady:this.workerReady,pendingTasks:this.pendingTasks.size,taskCounter:this.taskCounter}}}
|