versacompiler 1.0.5 → 2.0.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.
Files changed (42) hide show
  1. package/README.md +357 -145
  2. package/dist/compiler/compile.js +1120 -0
  3. package/dist/compiler/error-reporter.js +467 -0
  4. package/dist/compiler/linter.js +72 -0
  5. package/dist/{services → compiler}/minify.js +40 -31
  6. package/dist/compiler/parser.js +30 -0
  7. package/dist/compiler/tailwindcss.js +39 -0
  8. package/dist/compiler/transformTStoJS.js +16 -0
  9. package/dist/compiler/transforms.js +544 -0
  10. package/dist/compiler/typescript-error-parser.js +282 -0
  11. package/dist/compiler/typescript-sync-validator.js +230 -0
  12. package/dist/compiler/typescript-worker-thread.cjs +457 -0
  13. package/dist/compiler/typescript-worker.js +309 -0
  14. package/dist/compiler/typescript.js +382 -0
  15. package/dist/compiler/vuejs.js +296 -0
  16. package/dist/hrm/VueHRM.js +353 -0
  17. package/dist/hrm/errorScreen.js +23 -1
  18. package/dist/hrm/getInstanciaVue.js +313 -0
  19. package/dist/hrm/initHRM.js +140 -0
  20. package/dist/main.js +287 -0
  21. package/dist/servicios/browserSync.js +177 -0
  22. package/dist/servicios/chokidar.js +178 -0
  23. package/dist/servicios/logger.js +33 -0
  24. package/dist/servicios/readConfig.js +429 -0
  25. package/dist/utils/module-resolver.js +506 -0
  26. package/dist/utils/promptUser.js +48 -0
  27. package/dist/utils/resolve-bin.js +29 -0
  28. package/dist/utils/utils.js +8 -35
  29. package/dist/wrappers/eslint-node.js +145 -0
  30. package/dist/wrappers/oxlint-node.js +120 -0
  31. package/dist/wrappers/tailwind-node.js +92 -0
  32. package/package.json +62 -17
  33. package/dist/hrm/devMode.js +0 -346
  34. package/dist/hrm/instanciaVue.js +0 -35
  35. package/dist/hrm/setupHMR.js +0 -57
  36. package/dist/index.js +0 -1010
  37. package/dist/services/acorn.js +0 -29
  38. package/dist/services/linter.js +0 -55
  39. package/dist/services/typescript.js +0 -89
  40. package/dist/services/vueLoader.js +0 -326
  41. package/dist/services/vuejs.js +0 -259
  42. package/dist/utils/transformWithAcorn.js +0 -316
@@ -0,0 +1,457 @@
1
+ /**
2
+ * TypeScript Worker Thread - Ejecuta type checking asíncrono
3
+ * Este archivo se ejecuta en un worker thread separado para validación de tipos
4
+ */
5
+
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const { parentPort } = require('node:worker_threads');
9
+
10
+ // Debug: Log de inicio del worker
11
+ // console.log('[Worker] TypeScript Worker Thread iniciado');
12
+
13
+ let ts;
14
+ try {
15
+ ts = require('typescript');
16
+ // console.log('[Worker] TypeScript cargado exitosamente');
17
+ } catch (error) {
18
+ console.error('[Worker] Error cargando TypeScript:', error);
19
+ process.exit(1);
20
+ }
21
+
22
+ /**
23
+ * Language Service Host para validación de tipos en el worker
24
+ */
25
+ class WorkerTypeScriptLanguageServiceHost {
26
+ constructor(compilerOptions) {
27
+ this.files = new Map();
28
+ // Crear opciones ultra-limpias para evitar problemas de serialización
29
+ this.compilerOptions =
30
+ this.createUltraCleanCompilerOptions(compilerOptions);
31
+ } /**
32
+ * Crea opciones del compilador que respetan la configuración del tsconfig.json
33
+ */
34
+ createUltraCleanCompilerOptions(options) {
35
+ // Usar las opciones del tsconfig.json pasadas desde el hilo principal
36
+ const cleanOptions = {
37
+ target: options.target || ts.ScriptTarget.ES2020,
38
+ module: options.module || ts.ModuleKind.ES2020,
39
+ strict: Boolean(options.strict),
40
+ noEmitOnError: Boolean(options.noEmitOnError),
41
+ skipLibCheck: Boolean(options.skipLibCheck !== false), // true por defecto
42
+ skipDefaultLibCheck: Boolean(options.skipDefaultLibCheck !== false), // true por defecto
43
+ allowJs: Boolean(options.allowJs !== false), // true por defecto
44
+ esModuleInterop: Boolean(options.esModuleInterop !== false), // true por defecto
45
+ allowSyntheticDefaultImports: Boolean(
46
+ options.allowSyntheticDefaultImports !== false,
47
+ ), // true por defecto
48
+ declaration: Boolean(options.declaration),
49
+ sourceMap: Boolean(options.sourceMap),
50
+ noImplicitAny: Boolean(options.noImplicitAny),
51
+ noImplicitReturns: Boolean(options.noImplicitReturns),
52
+ noImplicitThis: Boolean(options.noImplicitThis),
53
+ noUnusedLocals: Boolean(options.noUnusedLocals),
54
+ noUnusedParameters: Boolean(options.noUnusedParameters),
55
+ isolatedModules: Boolean(options.isolatedModules !== false), // true por defecto // Usar las librerías especificadas en el tsconfig.json
56
+ lib: Array.isArray(options.lib)
57
+ ? options.lib
58
+ : ['es2020', 'dom', 'dom.iterable'],
59
+
60
+ // Soporte para decorators
61
+ experimentalDecorators: Boolean(
62
+ options.experimentalDecorators !== false,
63
+ ),
64
+ emitDecoratorMetadata: Boolean(
65
+ options.emitDecoratorMetadata !== false,
66
+ ),
67
+
68
+ // Opciones críticas para el worker pero manteniendo compatibilidad
69
+ noLib: false, // Permitir librerías para APIs básicas (DOM, Promise, etc.)
70
+ noResolve: true, // Evitar resolución de módulos compleja pero mantener tipos globales
71
+ suppressOutputPathCheck: true,
72
+ allowNonTsExtensions: true,
73
+ };
74
+
75
+ // console.log(
76
+ // '[Worker] Opciones del compilador limpias creadas:',
77
+ // Object.keys(cleanOptions),
78
+ // );
79
+ return cleanOptions;
80
+ }
81
+
82
+ addFile(fileName, content) {
83
+ const existing = this.files.get(fileName);
84
+ this.files.set(fileName, {
85
+ version: existing ? existing.version + 1 : 1,
86
+ content,
87
+ });
88
+ }
89
+
90
+ getCompilationSettings() {
91
+ return this.compilerOptions;
92
+ }
93
+
94
+ getScriptFileNames() {
95
+ return Array.from(this.files.keys());
96
+ }
97
+
98
+ getScriptVersion(fileName) {
99
+ const file = this.files.get(fileName);
100
+ return file ? file.version.toString() : '0';
101
+ }
102
+
103
+ getScriptSnapshot(fileName) {
104
+ const file = this.files.get(fileName);
105
+ if (file) {
106
+ return ts.ScriptSnapshot.fromString(file.content);
107
+ }
108
+
109
+ // Intentar leer el archivo del sistema de archivos para dependencias
110
+ if (fs.existsSync(fileName)) {
111
+ try {
112
+ const content = fs.readFileSync(fileName, 'utf-8');
113
+ return ts.ScriptSnapshot.fromString(content);
114
+ } catch {
115
+ return undefined;
116
+ }
117
+ }
118
+
119
+ return undefined;
120
+ }
121
+
122
+ getCurrentDirectory() {
123
+ return process.cwd();
124
+ }
125
+
126
+ getDefaultLibFileName(options) {
127
+ return ts.getDefaultLibFilePath(options);
128
+ }
129
+
130
+ fileExists(path) {
131
+ return this.files.has(path) || fs.existsSync(path);
132
+ }
133
+
134
+ readFile(path) {
135
+ const file = this.files.get(path);
136
+ if (file) {
137
+ return file.content;
138
+ }
139
+
140
+ if (fs.existsSync(path)) {
141
+ try {
142
+ return fs.readFileSync(path, 'utf-8');
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ return undefined;
149
+ }
150
+
151
+ getNewLine() {
152
+ return ts.sys.newLine;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Realiza validación de tipos en el worker thread
158
+ */
159
+ function validateTypesInWorker(fileName, content, compilerOptions) {
160
+ let actualFileName = fileName;
161
+
162
+ try {
163
+ let scriptContent = content;
164
+
165
+ // Si el script está vacío o es solo espacios en blanco, no validar
166
+ if (!scriptContent.trim()) {
167
+ return { diagnostics: [], hasErrors: false };
168
+ }
169
+
170
+ // Crear Language Service Host
171
+ const host = new WorkerTypeScriptLanguageServiceHost(compilerOptions); // Para archivos Vue, crear un archivo virtual .ts
172
+ if (fileName.endsWith('.vue')) {
173
+ // Crear un nombre de archivo virtual único
174
+ const virtualFileName = `${fileName}.ts`;
175
+ host.addFile(virtualFileName, scriptContent);
176
+ actualFileName = virtualFileName;
177
+ // console.log('[Worker] Archivo Vue agregado como:', virtualFileName);
178
+ } else {
179
+ // Para archivos virtuales, usar el nombre tal como viene
180
+ host.addFile(fileName, scriptContent);
181
+ actualFileName = fileName;
182
+ // console.log('[Worker] Archivo agregado como:', fileName);
183
+ }
184
+
185
+ // console.log(
186
+ // '[Worker] Contenido del archivo:',
187
+ // scriptContent.substring(0, 100) + '...',
188
+ // );
189
+ // console.log('[Worker] Archivos en host:', host.getScriptFileNames());
190
+
191
+ // Agregar declaraciones básicas de tipos para Vue si es necesario
192
+ if (fileName.endsWith('.vue')) {
193
+ // Usar el directorio del archivo actual para las declaraciones
194
+ const projectDir = path.dirname(actualFileName);
195
+ const vueTypesPath = path.join(projectDir, 'vue-types.d.ts');
196
+ const vueTypesDeclaration = `// Declaraciones de tipos Vue para validación
197
+ declare global {
198
+ function ref<T>(value: T): { value: T };
199
+ function reactive<T extends object>(target: T): T;
200
+ function computed<T>(getter: () => T): { value: T };
201
+ function defineComponent<T>(options: T): T;
202
+ function defineProps<T = {}>(): T;
203
+ function defineEmits<T = {}>(): T;
204
+ function onMounted(fn: () => void): void;
205
+ function onUnmounted(fn: () => void): void;
206
+ function watch<T>(source: () => T, callback: (newValue: T, oldValue: T) => void): void;
207
+ }
208
+ export {};`;
209
+ host.addFile(vueTypesPath, vueTypesDeclaration);
210
+ }
211
+
212
+ // Crear Language Service
213
+ const languageService = ts.createLanguageService(host);
214
+
215
+ try {
216
+ // Verificar que el archivo existe en el host antes de solicitar diagnósticos
217
+ if (!host.fileExists(actualFileName)) {
218
+ return { diagnostics: [], hasErrors: false };
219
+ }
220
+
221
+ // Obtener diagnósticos de tipos con manejo de errores
222
+ let syntacticDiagnostics = [];
223
+ let semanticDiagnostics = [];
224
+ try {
225
+ syntacticDiagnostics =
226
+ languageService.getSyntacticDiagnostics(actualFileName);
227
+ // console.log(
228
+ // '[Worker] Diagnósticos sintácticos:',
229
+ // syntacticDiagnostics.length,
230
+ // );
231
+ } catch (error) {
232
+ console.error(
233
+ '[Worker] Error obteniendo diagnósticos sintácticos:',
234
+ error.message,
235
+ );
236
+ }
237
+
238
+ try {
239
+ semanticDiagnostics =
240
+ languageService.getSemanticDiagnostics(actualFileName);
241
+ // console.log(
242
+ // '[Worker] Diagnósticos semánticos:',
243
+ // semanticDiagnostics.length,
244
+ // );
245
+ } catch (error) {
246
+ console.error(
247
+ '[Worker] Error obteniendo diagnósticos semánticos:',
248
+ error.message,
249
+ );
250
+ } // Combinar todos los diagnósticos
251
+ const allDiagnostics = [
252
+ ...syntacticDiagnostics,
253
+ ...semanticDiagnostics,
254
+ ];
255
+
256
+ // console.log(
257
+ // '[Worker] Total diagnósticos encontrados:',
258
+ // allDiagnostics.length,
259
+ // );
260
+
261
+ // Log de todos los diagnósticos antes del filtrado
262
+ // allDiagnostics.forEach((diag, index) => {
263
+ // const messageText = ts.flattenDiagnosticMessageText(
264
+ // diag.messageText,
265
+ // '\n',
266
+ // );
267
+ // console.log(
268
+ // `[Worker] Diagnóstico ${index + 1}: [${diag.category}] ${messageText}`,
269
+ // );
270
+ // });
271
+
272
+ // Filtrar diagnósticos relevantes
273
+ const filteredDiagnostics = allDiagnostics.filter(diag => {
274
+ const messageText = ts.flattenDiagnosticMessageText(
275
+ diag.messageText,
276
+ '\n',
277
+ );
278
+
279
+ // Solo errores de categoría Error
280
+ if (diag.category !== ts.DiagnosticCategory.Error) {
281
+ return false;
282
+ } // Ignorar SOLO errores específicos de infraestructura Vue y rutas de módulos
283
+ return (
284
+ !messageText.includes('Cannot find module') &&
285
+ !messageText.includes('Could not find source file') &&
286
+ !messageText.includes(
287
+ "Parameter '$props' implicitly has an 'any' type",
288
+ ) &&
289
+ !messageText.includes(
290
+ "Parameter '$setup' implicitly has an 'any' type",
291
+ ) &&
292
+ !messageText.includes(
293
+ "Parameter '$data' implicitly has an 'any' type",
294
+ ) &&
295
+ !messageText.includes(
296
+ "Parameter '$options' implicitly has an 'any' type",
297
+ ) &&
298
+ !messageText.includes(
299
+ "Parameter '$event' implicitly has an 'any' type",
300
+ ) &&
301
+ !messageText.includes(
302
+ "Parameter '_ctx' implicitly has an 'any' type",
303
+ ) &&
304
+ !messageText.includes(
305
+ "Parameter '_cache' implicitly has an 'any' type",
306
+ ) &&
307
+ // Ignorar errores específicos de decorators cuando están mal configurados
308
+ !messageText.includes(
309
+ 'Unable to resolve signature of method decorator when called as an expression',
310
+ ) &&
311
+ !messageText.includes(
312
+ 'The runtime will invoke the decorator with',
313
+ ) &&
314
+ // Ignorar errores TS7031 (binding element implicitly has any type)
315
+ diag.code !== 7031 &&
316
+ // Ignorar errores TS7006 (parameter implicitly has any type)
317
+ diag.code !== 7006 &&
318
+ // Ignorar errores TS1241 (decorator signature mismatch) durante desarrollo
319
+ diag.code !== 1241 &&
320
+ !(
321
+ messageText.includes("implicitly has an 'any' type") &&
322
+ (messageText.includes('_ctx') ||
323
+ messageText.includes('_cache') ||
324
+ messageText.includes('$props') ||
325
+ messageText.includes('$setup') ||
326
+ messageText.includes('__expose') ||
327
+ messageText.includes('__emit'))
328
+ )
329
+ );
330
+ });
331
+
332
+ return {
333
+ diagnostics: filteredDiagnostics,
334
+ hasErrors: filteredDiagnostics.length > 0,
335
+ };
336
+ } catch {
337
+ return { diagnostics: [], hasErrors: false };
338
+ }
339
+ } catch (error) {
340
+ // En caso de error, devolver diagnóstico de error
341
+ const errorDiagnostic = {
342
+ file: undefined,
343
+ start: undefined,
344
+ length: undefined,
345
+ messageText: `Error en validación de tipos: ${error instanceof Error ? error.message : 'Error desconocido'}`,
346
+ category: ts.DiagnosticCategory.Error,
347
+ code: 0,
348
+ };
349
+
350
+ return {
351
+ diagnostics: [errorDiagnostic],
352
+ hasErrors: true,
353
+ };
354
+ }
355
+ }
356
+
357
+ // Escuchar mensajes del proceso principal
358
+ if (parentPort) {
359
+ parentPort.on('message', message => {
360
+ try {
361
+ // console.log('[Worker] Mensaje recibido:', {
362
+ // id: message.id,
363
+ // fileName: message.fileName,
364
+ // contentLength: message.content?.length,
365
+ // compilerOptions: Object.keys(message.compilerOptions || {}),
366
+ // });
367
+
368
+ const { id, fileName, content, compilerOptions } = message;
369
+
370
+ // Validar que el mensaje tiene la estructura correcta
371
+ if (!id || !fileName || typeof content !== 'string') {
372
+ parentPort.postMessage({
373
+ id: id || 'unknown',
374
+ success: false,
375
+ error: 'Mensaje del worker inválido',
376
+ });
377
+ return;
378
+ }
379
+
380
+ // Realizar validación de tipos
381
+ const result = validateTypesInWorker(
382
+ fileName,
383
+ content,
384
+ compilerOptions,
385
+ ); // Serializar diagnósticos de forma segura
386
+ const serializableDiagnostics = result.diagnostics.map(diag => ({
387
+ category: diag.category,
388
+ code: diag.code,
389
+ messageText:
390
+ typeof diag.messageText === 'string'
391
+ ? diag.messageText
392
+ : ts.flattenDiagnosticMessageText(
393
+ diag.messageText,
394
+ '\n',
395
+ ),
396
+ file: diag.file
397
+ ? {
398
+ fileName: diag.file.fileName,
399
+ text: diag.file.text,
400
+ }
401
+ : undefined,
402
+ start: diag.start,
403
+ length: diag.length,
404
+ }));
405
+
406
+ // Enviar respuesta al proceso principal
407
+ // console.log('[Worker] Enviando respuesta:', {
408
+ // id,
409
+ // success: true,
410
+ // diagnosticsCount: serializableDiagnostics.length,
411
+ // hasErrors: result.hasErrors,
412
+ // });
413
+
414
+ parentPort.postMessage({
415
+ id,
416
+ success: true,
417
+ diagnostics: serializableDiagnostics,
418
+ hasErrors: result.hasErrors,
419
+ });
420
+ } catch (error) {
421
+ // Enviar error al proceso principal
422
+ parentPort.postMessage({
423
+ id: message?.id || 'unknown',
424
+ success: false,
425
+ error:
426
+ error instanceof Error
427
+ ? error.message
428
+ : 'Error desconocido en worker',
429
+ });
430
+ }
431
+ });
432
+ }
433
+
434
+ // Manejar errores no capturados en el worker
435
+ process.on('uncaughtException', error => {
436
+ console.error('[Worker] Error no capturado en TypeScript worker:', error);
437
+ if (parentPort) {
438
+ parentPort.postMessage({
439
+ id: 'error',
440
+ success: false,
441
+ error: `Error crítico en worker: ${error.message}`,
442
+ });
443
+ }
444
+ process.exit(1);
445
+ });
446
+
447
+ // Log de confirmación de que el worker está listo
448
+ // console.log('[Worker] TypeScript Worker Thread listo para recibir mensajes');
449
+
450
+ // Señal de que el worker está listo
451
+ if (parentPort) {
452
+ parentPort.postMessage({
453
+ id: 'worker-ready',
454
+ success: true,
455
+ message: 'TypeScript worker iniciado correctamente',
456
+ });
457
+ }