versacompiler 1.0.5 → 2.0.1

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 (48) hide show
  1. package/README.md +633 -145
  2. package/dist/compiler/compile.js +1362 -0
  3. package/dist/compiler/error-reporter.js +467 -0
  4. package/dist/compiler/linter.js +72 -0
  5. package/dist/compiler/minify.js +229 -0
  6. package/dist/compiler/module-resolution-optimizer.js +844 -0
  7. package/dist/compiler/parser.js +203 -0
  8. package/dist/compiler/performance-monitor.js +192 -0
  9. package/dist/compiler/tailwindcss.js +39 -0
  10. package/dist/compiler/transform-optimizer.js +287 -0
  11. package/dist/compiler/transformTStoJS.js +16 -0
  12. package/dist/compiler/transforms.js +578 -0
  13. package/dist/compiler/typescript-compiler.js +379 -0
  14. package/dist/compiler/typescript-error-parser.js +281 -0
  15. package/dist/compiler/typescript-manager.js +378 -0
  16. package/dist/compiler/typescript-sync-validator.js +228 -0
  17. package/dist/compiler/typescript-worker-pool.js +479 -0
  18. package/dist/compiler/typescript-worker-thread.cjs +457 -0
  19. package/dist/compiler/typescript-worker.js +339 -0
  20. package/dist/compiler/vuejs.js +390 -0
  21. package/dist/hrm/VueHRM.js +353 -0
  22. package/dist/hrm/errorScreen.js +23 -1
  23. package/dist/hrm/getInstanciaVue.js +313 -0
  24. package/dist/hrm/initHRM.js +140 -0
  25. package/dist/main.js +286 -0
  26. package/dist/servicios/browserSync.js +469 -0
  27. package/dist/servicios/file-watcher.js +316 -0
  28. package/dist/servicios/logger.js +34 -0
  29. package/dist/servicios/readConfig.js +430 -0
  30. package/dist/utils/module-resolver.js +495 -0
  31. package/dist/utils/promptUser.js +48 -0
  32. package/dist/utils/resolve-bin.js +48 -0
  33. package/dist/utils/utils.js +8 -35
  34. package/dist/wrappers/eslint-node.js +145 -0
  35. package/dist/wrappers/oxlint-node.js +120 -0
  36. package/dist/wrappers/tailwind-node.js +92 -0
  37. package/package.json +62 -17
  38. package/dist/hrm/devMode.js +0 -346
  39. package/dist/hrm/instanciaVue.js +0 -35
  40. package/dist/hrm/setupHMR.js +0 -57
  41. package/dist/index.js +0 -1010
  42. package/dist/services/acorn.js +0 -29
  43. package/dist/services/linter.js +0 -55
  44. package/dist/services/minify.js +0 -31
  45. package/dist/services/typescript.js +0 -89
  46. package/dist/services/vueLoader.js +0 -326
  47. package/dist/services/vuejs.js +0 -259
  48. package/dist/utils/transformWithAcorn.js +0 -316
@@ -0,0 +1,203 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs, { readFile } from 'node:fs/promises';
3
+ import oxc from 'oxc-parser';
4
+ class ParserASTCache {
5
+ static instance;
6
+ cache = new Map();
7
+ MAX_CACHE_SIZE = 150; // Máximo ASTs en cache
8
+ MAX_CACHE_MEMORY = 30 * 1024 * 1024; // 30MB límite
9
+ CACHE_TTL = 10 * 60 * 1000; // 10 minutos
10
+ currentMemoryUsage = 0;
11
+ // Métricas
12
+ cacheHits = 0;
13
+ cacheMisses = 0;
14
+ totalParses = 0;
15
+ static getInstance() {
16
+ if (!ParserASTCache.instance) {
17
+ ParserASTCache.instance = new ParserASTCache();
18
+ }
19
+ return ParserASTCache.instance;
20
+ }
21
+ /**
22
+ * Genera un hash del contenido del código
23
+ */
24
+ generateContentHash(code, astType) {
25
+ return createHash('sha256').update(`${code}:${astType}`).digest('hex');
26
+ }
27
+ /**
28
+ * Estima el tamaño en memoria de un AST
29
+ */
30
+ estimateASTSize(ast) {
31
+ try {
32
+ return JSON.stringify(ast).length * 2; // UTF-16 characters
33
+ }
34
+ catch {
35
+ return 10000; // Estimación por defecto
36
+ }
37
+ }
38
+ /**
39
+ * Obtiene AST desde cache o lo parsea
40
+ */
41
+ async getOrParseAST(filename, code, astType = 'js') {
42
+ this.totalParses++;
43
+ const contentHash = this.generateContentHash(code, astType);
44
+ const cacheKey = `${filename}:${contentHash}`;
45
+ // Verificar cache
46
+ const cached = this.cache.get(cacheKey);
47
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL) {
48
+ // Actualizar timestamp de uso (LRU)
49
+ cached.timestamp = Date.now();
50
+ this.cacheHits++;
51
+ return {
52
+ ast: cached.ast,
53
+ cached: true,
54
+ };
55
+ }
56
+ // Cache miss - parsear nuevo AST
57
+ this.cacheMisses++;
58
+ const ast = oxc.parseSync(filename, code, {
59
+ sourceType: 'module',
60
+ showSemanticErrors: true,
61
+ astType,
62
+ });
63
+ // Cachear resultado si es válido
64
+ if (ast && !ast.errors?.length) {
65
+ this.addToCache(cacheKey, ast, astType);
66
+ }
67
+ return {
68
+ ast,
69
+ cached: false,
70
+ };
71
+ }
72
+ /**
73
+ * Añade AST al cache con gestión de memoria
74
+ */
75
+ addToCache(cacheKey, ast, astType) {
76
+ try {
77
+ const size = this.estimateASTSize(ast);
78
+ // Aplicar políticas de eviction si es necesario
79
+ this.evictIfNeeded(size);
80
+ const entry = {
81
+ contentHash: cacheKey.split(':')[1] || '',
82
+ ast,
83
+ astType,
84
+ timestamp: Date.now(),
85
+ size,
86
+ };
87
+ this.cache.set(cacheKey, entry);
88
+ this.currentMemoryUsage += size;
89
+ }
90
+ catch (error) {
91
+ console.warn('[ParserASTCache] Error cacheando AST:', error);
92
+ }
93
+ }
94
+ /**
95
+ * Aplica políticas de eviction LRU si es necesario
96
+ */
97
+ evictIfNeeded(newEntrySize) {
98
+ // Verificar límite de entradas
99
+ while (this.cache.size >= this.MAX_CACHE_SIZE) {
100
+ this.evictLRU();
101
+ }
102
+ // Verificar límite de memoria
103
+ while (this.currentMemoryUsage + newEntrySize > this.MAX_CACHE_MEMORY &&
104
+ this.cache.size > 0) {
105
+ this.evictLRU();
106
+ }
107
+ }
108
+ /**
109
+ * Elimina la entrada menos recientemente usada
110
+ */
111
+ evictLRU() {
112
+ let oldestKey = '';
113
+ let oldestTime = Infinity;
114
+ for (const [key, entry] of this.cache) {
115
+ if (entry.timestamp < oldestTime) {
116
+ oldestTime = entry.timestamp;
117
+ oldestKey = key;
118
+ }
119
+ }
120
+ if (oldestKey) {
121
+ const entry = this.cache.get(oldestKey);
122
+ if (entry) {
123
+ this.currentMemoryUsage -= entry.size;
124
+ this.cache.delete(oldestKey);
125
+ }
126
+ }
127
+ }
128
+ /**
129
+ * Limpia entradas expiradas
130
+ */
131
+ cleanExpired() {
132
+ const now = Date.now();
133
+ for (const [key, entry] of this.cache.entries()) {
134
+ if (now - entry.timestamp > this.CACHE_TTL) {
135
+ this.currentMemoryUsage -= entry.size;
136
+ this.cache.delete(key);
137
+ }
138
+ }
139
+ }
140
+ /**
141
+ * Obtiene estadísticas del cache
142
+ */
143
+ getStats() {
144
+ const hitRate = this.totalParses > 0
145
+ ? Math.round((this.cacheHits / this.totalParses) * 100)
146
+ : 0;
147
+ return {
148
+ cacheHits: this.cacheHits,
149
+ cacheMisses: this.cacheMisses,
150
+ hitRate,
151
+ totalParses: this.totalParses,
152
+ cacheSize: this.cache.size,
153
+ maxCacheSize: this.MAX_CACHE_SIZE,
154
+ memoryUsage: this.currentMemoryUsage,
155
+ maxMemoryUsage: this.MAX_CACHE_MEMORY,
156
+ };
157
+ }
158
+ /**
159
+ * Limpia todo el cache
160
+ */
161
+ clear() {
162
+ this.cache.clear();
163
+ this.currentMemoryUsage = 0;
164
+ this.cacheHits = 0;
165
+ this.cacheMisses = 0;
166
+ this.totalParses = 0;
167
+ }
168
+ }
169
+ // Instancia global del cache AST
170
+ const astCache = ParserASTCache.getInstance();
171
+ /**
172
+ * Parses the given JavaScript code using Acorn and returns the Abstract Syntax Tree (AST).
173
+ *
174
+ * @param {string} data - The JavaScript code to be parsed.
175
+ * @returns {Promise<Object|null>} The parsed AST object if successful, or null if an error occurs.
176
+ * @throws {Error} If there is an error during parsing, it logs the error details and stack trace.
177
+ */
178
+ export const parser = async (filename, code, astType = 'js') => {
179
+ const { ast } = await astCache.getOrParseAST(filename, code, astType);
180
+ return ast;
181
+ };
182
+ export const getCodeFile = async (filename) => {
183
+ try {
184
+ // validar si existe el archivo
185
+ await fs.access(filename);
186
+ const code = await readFile(filename, 'utf-8');
187
+ return { code, error: null };
188
+ }
189
+ catch (error) {
190
+ return { code: null, error };
191
+ }
192
+ };
193
+ // ✨ NUEVAS FUNCIONES: Exportar funcionalidades del cache AST para uso externo
194
+ export const getParserCacheStats = () => {
195
+ return astCache.getStats();
196
+ };
197
+ export const clearParserCache = () => {
198
+ astCache.clear();
199
+ };
200
+ export const cleanExpiredParserCache = () => {
201
+ astCache.cleanExpired();
202
+ };
203
+ //# sourceMappingURL=parser.js.map
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Performance Monitor - Sistema centralizado de monitoreo de optimizaciones
3
+ * Reúne todas las métricas de cache y performance del VersaCompiler
4
+ */
5
+ import { clearBrowserSyncCache, getBrowserSyncCacheStats, } from '../servicios/browserSync.js';
6
+ import { cleanExpiredMinificationCache, clearMinificationCache, getMinificationCacheStats, } from './minify.js';
7
+ import { getModuleResolutionMetrics } from './module-resolution-optimizer.js';
8
+ import { cleanExpiredParserCache, clearParserCache, getParserCacheStats, } from './parser.js';
9
+ import { TransformOptimizer } from './transform-optimizer.js';
10
+ import { cleanExpiredVueHMRCache, clearVueHMRCache, getVueHMRCacheStats, } from './vuejs.js';
11
+ export class PerformanceMonitor {
12
+ static instance;
13
+ static getInstance() {
14
+ if (!PerformanceMonitor.instance) {
15
+ PerformanceMonitor.instance = new PerformanceMonitor();
16
+ }
17
+ return PerformanceMonitor.instance;
18
+ }
19
+ /**
20
+ * Obtiene todas las estadísticas de performance de manera unificada
21
+ */
22
+ getAllStats() {
23
+ const vueHMRCache = getVueHMRCacheStats();
24
+ const parserCache = getParserCacheStats();
25
+ const browserSyncCache = getBrowserSyncCacheStats();
26
+ const minificationCache = getMinificationCacheStats();
27
+ const transformOptimizer = TransformOptimizer.getInstance().getStats();
28
+ const moduleResolution = getModuleResolutionMetrics();
29
+ // Calcular resumen general
30
+ const totalCacheHits = (parserCache.cacheHits || 0) +
31
+ (browserSyncCache.cacheHits || 0) +
32
+ (minificationCache.cacheHits || 0) +
33
+ (transformOptimizer.cacheHits || 0) +
34
+ (moduleResolution.cacheHits || 0);
35
+ const totalCacheMisses = (parserCache.cacheMisses || 0) +
36
+ (browserSyncCache.cacheMisses || 0) +
37
+ (minificationCache.cacheMisses || 0) +
38
+ (transformOptimizer.cacheMisses || 0) +
39
+ (moduleResolution.cacheMisses || 0);
40
+ const totalRequests = totalCacheHits + totalCacheMisses;
41
+ const overallHitRate = totalRequests > 0
42
+ ? Math.round((totalCacheHits / totalRequests) * 100)
43
+ : 0;
44
+ const totalMemoryUsage = (parserCache.memoryUsage || 0) +
45
+ (browserSyncCache.memoryUsage || 0) +
46
+ (minificationCache.memoryUsage || 0) +
47
+ (transformOptimizer.memoryUsage || 0);
48
+ const totalCacheEntries = (vueHMRCache.size || 0) +
49
+ (parserCache.cacheSize || 0) +
50
+ (browserSyncCache.cacheSize || 0) +
51
+ (minificationCache.cacheSize || 0) +
52
+ (transformOptimizer.cacheSize || 0) +
53
+ (moduleResolution.cacheSize || 0);
54
+ return {
55
+ vueHMRCache,
56
+ parserCache,
57
+ browserSyncCache,
58
+ minificationCache,
59
+ transformOptimizer,
60
+ moduleResolution,
61
+ summary: {
62
+ totalCacheHits,
63
+ totalCacheMisses,
64
+ overallHitRate,
65
+ totalMemoryUsage,
66
+ totalCacheEntries,
67
+ },
68
+ };
69
+ }
70
+ /**
71
+ * Genera un reporte detallado de performance
72
+ */
73
+ generateReport() {
74
+ const stats = this.getAllStats();
75
+ const formatBytes = (bytes) => {
76
+ if (bytes === 0)
77
+ return '0 B';
78
+ const k = 1024;
79
+ const sizes = ['B', 'KB', 'MB', 'GB'];
80
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
81
+ return (parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]);
82
+ };
83
+ const report = `
84
+ 🚀 VERSACOMPILER PERFORMANCE REPORT
85
+ =====================================
86
+
87
+ 📊 RESUMEN GENERAL
88
+ Hit Rate Total: ${stats.summary.overallHitRate}%
89
+ Cache Hits: ${stats.summary.totalCacheHits}
90
+ Cache Misses: ${stats.summary.totalCacheMisses}
91
+ Memoria Total: ${formatBytes(stats.summary.totalMemoryUsage)}
92
+ Entradas Cache: ${stats.summary.totalCacheEntries}
93
+
94
+ 🎯 VUE HMR CACHE
95
+ Size: ${stats.vueHMRCache.size}/${stats.vueHMRCache.maxSize}
96
+ TTL: ${Math.round(stats.vueHMRCache.ttl / 1000 / 60)}min
97
+
98
+ 📝 PARSER AST CACHE
99
+ Hit Rate: ${stats.parserCache.hitRate}%
100
+ Cache Hits: ${stats.parserCache.cacheHits}
101
+ Cache Misses: ${stats.parserCache.cacheMisses}
102
+ Size: ${stats.parserCache.cacheSize}/${stats.parserCache.maxCacheSize}
103
+ Memoria: ${formatBytes(stats.parserCache.memoryUsage)}/${formatBytes(stats.parserCache.maxMemoryUsage)}
104
+
105
+ 🌐 BROWSERSYNC FILE CACHE
106
+ Hit Rate: ${stats.browserSyncCache.hitRate}%
107
+ Cache Hits: ${stats.browserSyncCache.cacheHits}
108
+ Cache Misses: ${stats.browserSyncCache.cacheMisses}
109
+ Size: ${stats.browserSyncCache.cacheSize}/${stats.browserSyncCache.maxCacheSize}
110
+ Memoria: ${formatBytes(stats.browserSyncCache.memoryUsage)}/${formatBytes(stats.browserSyncCache.maxMemoryUsage)}
111
+
112
+ 🗜️ MINIFICATION CACHE
113
+ Hit Rate: ${stats.minificationCache.hitRate}%
114
+ Cache Hits: ${stats.minificationCache.cacheHits}
115
+ Cache Misses: ${stats.minificationCache.cacheMisses}
116
+ Size: ${stats.minificationCache.cacheSize}/${stats.minificationCache.maxCacheSize}
117
+ Memoria: ${formatBytes(stats.minificationCache.memoryUsage)}/${formatBytes(stats.minificationCache.maxMemoryUsage)}
118
+ Compresión Promedio: ${stats.minificationCache.avgCompressionRatio}%
119
+
120
+ 🔄 TRANSFORM OPTIMIZER
121
+ Hit Rate: ${stats.transformOptimizer.hitRate}%
122
+ Cache Hits: ${stats.transformOptimizer.cacheHits}
123
+ Cache Misses: ${stats.transformOptimizer.cacheMisses}
124
+ Transformaciones: ${stats.transformOptimizer.totalTransforms}
125
+ Size: ${stats.transformOptimizer.cacheSize}
126
+ Memoria: ${formatBytes(stats.transformOptimizer.memoryUsage)}
127
+
128
+ 📦 MODULE RESOLUTION
129
+ Hit Rate: ${stats.moduleResolution.cacheHitRate?.toFixed(1)}%
130
+ Cache Hits: ${stats.moduleResolution.cacheHits}
131
+ Cache Misses: ${stats.moduleResolution.cacheMisses}
132
+ Resoluciones: ${stats.moduleResolution.totalResolutions}
133
+ Índice Módulos: ${stats.moduleResolution.moduleIndexSize}
134
+ Índice Alias: ${stats.moduleResolution.aliasIndexSize}
135
+ Tiempo Promedio: ${stats.moduleResolution.averageResolveTime?.toFixed(2)}ms
136
+
137
+ =====================================
138
+ `;
139
+ return report;
140
+ }
141
+ /**
142
+ * Limpia todos los caches
143
+ */
144
+ clearAllCaches() {
145
+ clearVueHMRCache();
146
+ clearParserCache();
147
+ clearBrowserSyncCache();
148
+ clearMinificationCache();
149
+ TransformOptimizer.getInstance().clear();
150
+ console.log('🧹 Todos los caches han sido limpiados');
151
+ }
152
+ /**
153
+ * Limpia entradas expiradas de todos los caches
154
+ */
155
+ cleanExpiredCaches() {
156
+ cleanExpiredVueHMRCache();
157
+ cleanExpiredParserCache();
158
+ cleanExpiredMinificationCache();
159
+ console.log('🧹 Entradas expiradas limpiadas de todos los caches');
160
+ }
161
+ /**
162
+ * Configura limpieza automática periódica
163
+ */
164
+ setupAutomaticCleanup(intervalMinutes = 30) {
165
+ setInterval(() => {
166
+ this.cleanExpiredCaches();
167
+ console.log(`🔄 Limpieza automática ejecutada cada ${intervalMinutes} minutos`);
168
+ }, intervalMinutes * 60 * 1000);
169
+ }
170
+ /**
171
+ * Obtiene métricas simplificadas para logging
172
+ */
173
+ getSimpleMetrics() {
174
+ const stats = this.getAllStats();
175
+ return {
176
+ hitRate: stats.summary.overallHitRate,
177
+ totalHits: stats.summary.totalCacheHits,
178
+ totalMisses: stats.summary.totalCacheMisses,
179
+ memoryUsage: stats.summary.totalMemoryUsage,
180
+ cacheEntries: stats.summary.totalCacheEntries,
181
+ };
182
+ }
183
+ }
184
+ // Exportar instancia singleton
185
+ export const performanceMonitor = PerformanceMonitor.getInstance();
186
+ // Funciones de conveniencia
187
+ export const getAllPerformanceStats = () => performanceMonitor.getAllStats();
188
+ export const generatePerformanceReport = () => performanceMonitor.generateReport();
189
+ export const clearAllCaches = () => performanceMonitor.clearAllCaches();
190
+ export const cleanExpiredCaches = () => performanceMonitor.cleanExpiredCaches();
191
+ export const getSimpleMetrics = () => performanceMonitor.getSimpleMetrics();
192
+ //# sourceMappingURL=performance-monitor.js.map
@@ -0,0 +1,39 @@
1
+ import { env } from 'node:process';
2
+ import { logger } from '../servicios/logger.js';
3
+ import { TailwindNode } from '../wrappers/tailwind-node.js';
4
+ export async function generateTailwindCSS() {
5
+ if (env.tailwindcss === 'false' ||
6
+ env.tailwindcss === undefined ||
7
+ env.TAILWIND === 'false') {
8
+ return false;
9
+ }
10
+ try {
11
+ const tailwindcssConfig = JSON.parse(env.tailwindcss);
12
+ if (!tailwindcssConfig ||
13
+ !tailwindcssConfig.input ||
14
+ !tailwindcssConfig.output ||
15
+ !tailwindcssConfig.bin) {
16
+ return false;
17
+ }
18
+ const tnode = await new TailwindNode({
19
+ binPath: tailwindcssConfig.bin,
20
+ input: tailwindcssConfig.input,
21
+ output: tailwindcssConfig.output,
22
+ minify: env.isProd === 'true',
23
+ });
24
+ return await tnode.run();
25
+ }
26
+ catch (err) {
27
+ // Si es un error de JSON parse, devolver false en lugar de lanzar error
28
+ const errorMessage = err instanceof Error
29
+ ? err.stderr || err.message
30
+ : String(err);
31
+ logger.error('❌ :Error al compilar Tailwind:', errorMessage);
32
+ if (err instanceof SyntaxError && err.message.includes('JSON')) {
33
+ return false;
34
+ }
35
+ // Para otros errores (como errores de ejecución de TailwindCSS), loggear y relanzar
36
+ throw err;
37
+ }
38
+ }
39
+ //# sourceMappingURL=tailwindcss.js.map