versacompiler 2.0.0 → 2.0.2

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,822 @@
1
+ /**
2
+ * Module Resolution Optimizer
3
+ *
4
+ * Optimiza la resolución de módulos mediante:
5
+ * - Sistema de indexación O(1) para búsquedas de módulos
6
+ * - Caché LRU para resoluciones repetidas
7
+ * - Indexación de alias para búsquedas rápidas
8
+ * - Batch processing para múltiples resoluciones
9
+ * - Monitoreo de performance y métricas
10
+ */
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
13
+ import { dirname, join, relative } from 'node:path';
14
+ import { cwd, env } from 'node:process';
15
+ import { logger } from '../servicios/logger.js';
16
+ import { EXCLUDED_MODULES } from '../utils/excluded-modules.js';
17
+ /**
18
+ * Sistema de optimización de resolución de módulos
19
+ * Implementa indexación, caché y búsquedas O(1)
20
+ */
21
+ export class ModuleResolutionOptimizer {
22
+ static instance;
23
+ // Índice principal de módulos para búsquedas O(1)
24
+ moduleIndex = new Map();
25
+ // Caché LRU para resoluciones repetidas
26
+ resolutionCache = new Map();
27
+ cacheOrder = [];
28
+ // Índice de alias optimizado
29
+ aliasIndex = [];
30
+ // Caché de rutas de node_modules descubiertas
31
+ nodeModulesCache = new Map();
32
+ // Métricas de rendimiento
33
+ metrics = {
34
+ totalResolutions: 0,
35
+ cacheHits: 0,
36
+ cacheMisses: 0,
37
+ averageResolveTime: 0,
38
+ indexLookups: 0,
39
+ filesystemAccess: 0,
40
+ aliasMatches: 0,
41
+ };
42
+ // Configuración
43
+ maxCacheSize = 500;
44
+ cacheMaxAge = 5 * 60 * 1000; // 5 minutos
45
+ indexRefreshInterval = 10 * 60 * 1000; // 10 minutos // Lista de módulos excluidos - usar la lista centralizada
46
+ excludedModules = EXCLUDED_MODULES;
47
+ lastIndexUpdate = 0;
48
+ constructor() {
49
+ this.initializeIndexes();
50
+ this.setupPeriodicRefresh();
51
+ }
52
+ static getInstance() {
53
+ if (!ModuleResolutionOptimizer.instance) {
54
+ ModuleResolutionOptimizer.instance =
55
+ new ModuleResolutionOptimizer();
56
+ }
57
+ return ModuleResolutionOptimizer.instance;
58
+ }
59
+ /**
60
+ * Inicializa los índices de módulos y alias
61
+ */
62
+ initializeIndexes() {
63
+ const startTime = performance.now();
64
+ try {
65
+ this.buildModuleIndex();
66
+ this.buildAliasIndex();
67
+ this.lastIndexUpdate = Date.now();
68
+ const indexTime = performance.now() - startTime;
69
+ if (env.VERBOSE === 'true') {
70
+ logger.info(`🚀 Índices de resolución construidos en ${indexTime.toFixed(2)}ms`);
71
+ logger.info(`📦 ${this.moduleIndex.size} módulos indexados`);
72
+ logger.info(`🔗 ${this.aliasIndex.length} alias indexados`);
73
+ }
74
+ }
75
+ catch (error) {
76
+ logger.error('Error inicializando índices de resolución:', error);
77
+ }
78
+ }
79
+ /**
80
+ * Construye el índice principal de módulos para búsquedas O(1)
81
+ */
82
+ buildModuleIndex() {
83
+ const nodeModulesPath = join(cwd(), 'node_modules');
84
+ if (!existsSync(nodeModulesPath)) {
85
+ return;
86
+ }
87
+ try {
88
+ const modules = this.discoverModules(nodeModulesPath);
89
+ for (const moduleData of modules) {
90
+ this.moduleIndex.set(moduleData.name, {
91
+ fullPath: moduleData.fullPath,
92
+ entryPoint: moduleData.entryPoint,
93
+ packageJson: moduleData.packageJson,
94
+ isESM: moduleData.isESM,
95
+ hasExports: moduleData.hasExports,
96
+ optimizedEntry: moduleData.optimizedEntry,
97
+ lastModified: moduleData.lastModified,
98
+ });
99
+ }
100
+ if (env.VERBOSE === 'true') {
101
+ logger.info(`📚 Índice de módulos construido: ${this.moduleIndex.size} entradas`);
102
+ }
103
+ }
104
+ catch (error) {
105
+ logger.error('Error construyendo índice de módulos:', error);
106
+ }
107
+ }
108
+ /**
109
+ * Descubre módulos disponibles en node_modules con información optimizada
110
+ */
111
+ discoverModules(nodeModulesPath) {
112
+ const modules = [];
113
+ try {
114
+ const entries = readdirSync(nodeModulesPath);
115
+ this.metrics.filesystemAccess++;
116
+ for (const entry of entries) {
117
+ const modulePath = join(nodeModulesPath, entry);
118
+ try {
119
+ if (entry.startsWith('/dist/examples')) {
120
+ // Scoped packages
121
+ const scopedModules = readdirSync(modulePath);
122
+ this.metrics.filesystemAccess++;
123
+ for (const scopedModule of scopedModules) {
124
+ const scopedPath = join(modulePath, scopedModule);
125
+ const moduleData = this.analyzeModule(`${entry}/${scopedModule}`, scopedPath);
126
+ if (moduleData) {
127
+ modules.push(moduleData);
128
+ }
129
+ }
130
+ }
131
+ else {
132
+ // Regular packages
133
+ const moduleData = this.analyzeModule(entry, modulePath);
134
+ if (moduleData) {
135
+ modules.push(moduleData);
136
+ }
137
+ }
138
+ }
139
+ catch {
140
+ // Ignorar módulos que no se puedan analizar
141
+ continue;
142
+ }
143
+ }
144
+ }
145
+ catch (error) {
146
+ logger.error('Error descubriendo módulos:', error);
147
+ }
148
+ return modules;
149
+ }
150
+ /**
151
+ * Analiza un módulo individual y extrae información relevante
152
+ */
153
+ analyzeModule(name, modulePath) {
154
+ try {
155
+ const packageJsonPath = join(modulePath, 'package.json');
156
+ if (!existsSync(packageJsonPath)) {
157
+ return null;
158
+ }
159
+ const stats = statSync(packageJsonPath);
160
+ this.metrics.filesystemAccess++;
161
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
162
+ this.metrics.filesystemAccess++;
163
+ const isESM = packageJson.type === 'module';
164
+ const hasExports = !!packageJson.exports;
165
+ // Determinar entry point optimizado
166
+ let entryPoint = this.determineOptimalEntryPoint(packageJson);
167
+ let optimizedEntry;
168
+ // Buscar versión ESM/browser optimizada
169
+ if (entryPoint) {
170
+ optimizedEntry = this.findOptimalESMVersion(modulePath, entryPoint);
171
+ }
172
+ return {
173
+ name,
174
+ fullPath: modulePath,
175
+ entryPoint: entryPoint || 'index.js',
176
+ packageJson,
177
+ isESM,
178
+ hasExports,
179
+ optimizedEntry,
180
+ lastModified: stats.mtime.getTime(),
181
+ };
182
+ }
183
+ catch {
184
+ return null;
185
+ }
186
+ } /**
187
+ * Determina el entry point óptimo basado en package.json
188
+ */
189
+ determineOptimalEntryPoint(packageJson) {
190
+ // Prioridad: module > exports > browser > main
191
+ let entryPoint = null;
192
+ if (packageJson.module) {
193
+ entryPoint = packageJson.module;
194
+ }
195
+ else if (packageJson.exports) {
196
+ if (typeof packageJson.exports === 'string') {
197
+ entryPoint = packageJson.exports;
198
+ }
199
+ else if (packageJson.exports['.']) {
200
+ const dotExport = packageJson.exports['.'];
201
+ if (typeof dotExport === 'string') {
202
+ entryPoint = dotExport;
203
+ }
204
+ else if (typeof dotExport === 'object') {
205
+ entryPoint =
206
+ dotExport.import ||
207
+ dotExport.browser ||
208
+ dotExport.default;
209
+ }
210
+ }
211
+ }
212
+ else if (packageJson.browser &&
213
+ typeof packageJson.browser === 'string') {
214
+ entryPoint = packageJson.browser;
215
+ }
216
+ else {
217
+ entryPoint = packageJson.main || null;
218
+ }
219
+ // ✨ NUEVA VALIDACIÓN POST-RESOLUCIÓN
220
+ // Verificar si el archivo resuelto cumple con criterios de desarrollo
221
+ if (entryPoint) {
222
+ entryPoint = this.validateAndOptimizeEntryPoint(entryPoint, packageJson);
223
+ }
224
+ return entryPoint;
225
+ }
226
+ /**
227
+ * ✨ NUEVA FUNCIÓN: Valida y optimiza el entry point basado en criterios de desarrollo
228
+ */
229
+ validateAndOptimizeEntryPoint(entryPoint, packageJson) {
230
+ const isProd = env.isProd === 'true';
231
+ const fileName = entryPoint.toLowerCase();
232
+ // Si estamos en desarrollo, evitar archivos .min o .prod
233
+ if (!isProd &&
234
+ (fileName.includes('.min.') || fileName.includes('.prod.'))) {
235
+ // Buscar alternativas mejores en el package.json
236
+ const alternatives = this.findDevelopmentAlternatives(entryPoint, packageJson);
237
+ if (alternatives) {
238
+ return alternatives;
239
+ }
240
+ }
241
+ // Priorizar versiones browser y esm para mejor compatibilidad
242
+ if (fileName.includes('runtime') && !fileName.includes('browser')) {
243
+ const browserAlternative = this.findBrowserAlternative(entryPoint, packageJson);
244
+ if (browserAlternative) {
245
+ return browserAlternative;
246
+ }
247
+ }
248
+ return entryPoint;
249
+ } /**
250
+ * ✨ NUEVA FUNCIÓN: Busca alternativas de desarrollo (no minificadas)
251
+ */
252
+ findDevelopmentAlternatives(entryPoint, packageJson) {
253
+ // Crear versión de desarrollo basada en el entry point actual
254
+ let devVersion = entryPoint
255
+ .replace('.min.', '.')
256
+ .replace('.prod.', '.');
257
+ // Si hay exports, buscar en diferentes condiciones
258
+ if (packageJson.exports && typeof packageJson.exports === 'object') {
259
+ const dotExport = packageJson.exports['.'];
260
+ if (dotExport && typeof dotExport === 'object') {
261
+ // Buscar versiones development, import, browser
262
+ const candidates = [
263
+ dotExport.development,
264
+ dotExport.import,
265
+ dotExport.browser,
266
+ dotExport.default,
267
+ ].filter(Boolean);
268
+ for (const candidate of candidates) {
269
+ if (typeof candidate === 'string' &&
270
+ !candidate.includes('.min.') &&
271
+ !candidate.includes('.prod.')) {
272
+ return candidate;
273
+ }
274
+ }
275
+ }
276
+ } // Si browser field es un objeto, buscar alternativas
277
+ if (packageJson.browser && typeof packageJson.browser === 'object') {
278
+ for (const value of Object.values(packageJson.browser)) {
279
+ if (typeof value === 'string' &&
280
+ !value.includes('.min.') &&
281
+ !value.includes('.prod.') &&
282
+ (value.includes('browser') || value.includes('esm'))) {
283
+ return value;
284
+ }
285
+ }
286
+ }
287
+ return devVersion !== entryPoint ? devVersion : null;
288
+ }
289
+ /**
290
+ * ✨ NUEVA FUNCIÓN: Busca alternativas browser para versiones runtime
291
+ */
292
+ findBrowserAlternative(entryPoint, packageJson) {
293
+ // Primero intentar con exports
294
+ if (packageJson.exports && typeof packageJson.exports === 'object') {
295
+ const dotExport = packageJson.exports['.'];
296
+ if (dotExport && typeof dotExport === 'object') {
297
+ // Buscar specific browser+esm combinations
298
+ const browserKeys = Object.keys(dotExport).filter(key => key.includes('browser') &&
299
+ (key.includes('esm') || key.includes('module')));
300
+ if (browserKeys.length > 0) {
301
+ const firstBrowserKey = browserKeys[0];
302
+ if (firstBrowserKey &&
303
+ typeof dotExport[firstBrowserKey] === 'string') {
304
+ return dotExport[firstBrowserKey];
305
+ }
306
+ }
307
+ // Fallback a browser general
308
+ if (dotExport.browser &&
309
+ typeof dotExport.browser === 'string') {
310
+ return dotExport.browser;
311
+ }
312
+ }
313
+ }
314
+ // Buscar en directorio dist versiones browser
315
+ const baseName = entryPoint.replace(/\.[^/.]+$/, '');
316
+ const browserCandidates = [
317
+ baseName.replace('runtime', 'esm-browser'),
318
+ baseName.replace('runtime', 'browser'),
319
+ baseName.replace('runtime.esm-bundler', 'esm-browser'),
320
+ entryPoint.replace('runtime', 'esm-browser'),
321
+ entryPoint.replace('runtime', 'browser'),
322
+ ];
323
+ // Para Vue específicamente
324
+ if (entryPoint.includes('vue.runtime.esm-bundler')) {
325
+ browserCandidates.unshift('dist/vue.esm-browser.js', 'dist/vue.browser.esm.js');
326
+ }
327
+ return (browserCandidates.find(candidate => candidate !== entryPoint) ||
328
+ null);
329
+ }
330
+ /**
331
+ * Busca versión ESM/browser optimizada (simplificada del module-resolver)
332
+ */
333
+ findOptimalESMVersion(moduleDir, entryPoint) {
334
+ const dir = dirname(entryPoint);
335
+ const baseName = entryPoint.split('/').pop() || '';
336
+ const nameWithoutExt = baseName.replace(/\.[^/.]+$/, '');
337
+ const searchDir = join(moduleDir, dir);
338
+ if (!existsSync(searchDir)) {
339
+ return undefined;
340
+ }
341
+ try {
342
+ const files = readdirSync(searchDir);
343
+ this.metrics.filesystemAccess++;
344
+ // Patrones de prioridad para versiones optimizadas
345
+ const patterns = [
346
+ `${nameWithoutExt}.esm-browser.js`,
347
+ `${nameWithoutExt}.esm.js`,
348
+ `${nameWithoutExt}.module.js`,
349
+ `${nameWithoutExt}.browser.js`,
350
+ ];
351
+ for (const pattern of patterns) {
352
+ if (files.includes(pattern)) {
353
+ return join(dir, pattern);
354
+ }
355
+ }
356
+ }
357
+ catch {
358
+ // Ignorar errores de filesystem
359
+ }
360
+ return undefined;
361
+ }
362
+ /**
363
+ * Construye el índice de alias optimizado para búsquedas rápidas
364
+ */
365
+ buildAliasIndex() {
366
+ if (!env.PATH_ALIAS) {
367
+ return;
368
+ }
369
+ try {
370
+ const pathAlias = JSON.parse(env.PATH_ALIAS);
371
+ this.aliasIndex = [];
372
+ // Convertir alias a índice con prioridad
373
+ for (const [alias, target] of Object.entries(pathAlias)) {
374
+ const pattern = alias.replace('/*', '');
375
+ const priority = pattern.length; // Patrones más largos tienen prioridad
376
+ this.aliasIndex.push({
377
+ pattern,
378
+ target: Array.isArray(target) ? target : [target],
379
+ regex: new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=/|$)`),
380
+ priority,
381
+ });
382
+ }
383
+ // Ordenar por prioridad (patrones más largos primero)
384
+ this.aliasIndex.sort((a, b) => b.priority - a.priority);
385
+ if (env.VERBOSE === 'true') {
386
+ logger.info(`🔗 Índice de alias construido: ${this.aliasIndex.length} patrones`);
387
+ }
388
+ }
389
+ catch (error) {
390
+ logger.error('Error construyendo índice de alias:', error);
391
+ }
392
+ }
393
+ /**
394
+ * Resuelve un módulo utilizando el sistema optimizado
395
+ */
396
+ async resolveModule(moduleName, fromFile) {
397
+ const startTime = performance.now();
398
+ this.metrics.totalResolutions++;
399
+ // Verificar si está excluido
400
+ if (this.excludedModules.has(moduleName)) {
401
+ return {
402
+ path: null,
403
+ cached: false,
404
+ resolveTime: performance.now() - startTime,
405
+ };
406
+ }
407
+ // Crear clave de caché
408
+ const cacheKey = this.createCacheKey(moduleName, fromFile);
409
+ // Verificar caché
410
+ const cached = this.getFromCache(cacheKey);
411
+ if (cached !== undefined) {
412
+ this.metrics.cacheHits++;
413
+ return {
414
+ path: cached,
415
+ cached: true,
416
+ resolveTime: performance.now() - startTime,
417
+ fromCache: true,
418
+ };
419
+ }
420
+ this.metrics.cacheMisses++;
421
+ // Resolver módulo
422
+ let resolvedPath = null;
423
+ try {
424
+ // 1. Verificar si es subpath de módulo (ej: 'vue/dist/vue.esm-bundler')
425
+ if (moduleName.includes('/')) {
426
+ resolvedPath = await this.resolveSubPath(moduleName);
427
+ }
428
+ else {
429
+ // 2. Búsqueda O(1) en el índice
430
+ resolvedPath = this.resolveFromIndex(moduleName);
431
+ }
432
+ // 3. Si no se encuentra en índice, intentar resolución tradicional
433
+ if (!resolvedPath) {
434
+ resolvedPath = this.fallbackResolve(moduleName);
435
+ }
436
+ // Convertir a ruta relativa desde node_modules
437
+ if (resolvedPath) {
438
+ resolvedPath = this.getNodeModulesRelativePath(resolvedPath);
439
+ }
440
+ }
441
+ catch (error) {
442
+ if (env.VERBOSE === 'true') {
443
+ logger.warn(`Error resolviendo ${moduleName}:`, error);
444
+ }
445
+ }
446
+ // Guardar en caché
447
+ this.setCache(cacheKey, resolvedPath);
448
+ const resolveTime = performance.now() - startTime;
449
+ this.updateMetrics(resolveTime);
450
+ return {
451
+ path: resolvedPath,
452
+ cached: false,
453
+ resolveTime,
454
+ };
455
+ }
456
+ /**
457
+ * Busca módulo en el índice (O(1))
458
+ */
459
+ resolveFromIndex(moduleName) {
460
+ this.metrics.indexLookups++;
461
+ const moduleInfo = this.moduleIndex.get(moduleName);
462
+ if (!moduleInfo) {
463
+ return null;
464
+ }
465
+ // Usar versión optimizada si está disponible
466
+ const entryPoint = moduleInfo.optimizedEntry || moduleInfo.entryPoint;
467
+ return join(moduleInfo.fullPath, entryPoint);
468
+ }
469
+ /**
470
+ * Resuelve subpaths de módulos (ej: 'vue/dist/vue.esm-bundler')
471
+ */
472
+ async resolveSubPath(moduleName) {
473
+ const [packageName, ...subPathParts] = moduleName.split('/');
474
+ const subPath = subPathParts.join('/');
475
+ if (!packageName) {
476
+ return null;
477
+ }
478
+ this.metrics.indexLookups++;
479
+ const moduleInfo = this.moduleIndex.get(packageName);
480
+ if (!moduleInfo) {
481
+ return null;
482
+ }
483
+ // Verificar exports field para subpaths
484
+ if (moduleInfo.hasExports && moduleInfo.packageJson.exports) {
485
+ const exportKey = `./${subPath}`;
486
+ const exportPath = moduleInfo.packageJson.exports[exportKey];
487
+ if (exportPath) {
488
+ if (typeof exportPath === 'string') {
489
+ return join(moduleInfo.fullPath, exportPath);
490
+ }
491
+ else if (typeof exportPath === 'object') {
492
+ const importPath = exportPath.import || exportPath.default;
493
+ if (typeof importPath === 'string') {
494
+ return join(moduleInfo.fullPath, importPath);
495
+ }
496
+ }
497
+ }
498
+ }
499
+ // Fallback: resolver directamente el subpath
500
+ const directPath = join(moduleInfo.fullPath, subPath);
501
+ if (existsSync(directPath)) {
502
+ this.metrics.filesystemAccess++;
503
+ return directPath;
504
+ }
505
+ // Intentar con extensiones comunes
506
+ const extensions = ['.mjs', '.js', '.cjs'];
507
+ for (const ext of extensions) {
508
+ const pathWithExt = directPath + ext;
509
+ if (existsSync(pathWithExt)) {
510
+ this.metrics.filesystemAccess++;
511
+ return pathWithExt;
512
+ }
513
+ }
514
+ return null;
515
+ }
516
+ /**
517
+ * Resolución de fallback cuando no se encuentra en índice
518
+ */
519
+ fallbackResolve(moduleName) {
520
+ const nodeModulesPath = join(cwd(), 'node_modules', moduleName);
521
+ const packagePath = join(nodeModulesPath, 'package.json');
522
+ if (!existsSync(packagePath)) {
523
+ this.metrics.filesystemAccess++;
524
+ return null;
525
+ }
526
+ try {
527
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
528
+ this.metrics.filesystemAccess++;
529
+ const entryPoint = this.determineOptimalEntryPoint(packageJson) || 'index.js';
530
+ const finalPath = join(nodeModulesPath, entryPoint);
531
+ if (existsSync(finalPath)) {
532
+ this.metrics.filesystemAccess++;
533
+ return finalPath;
534
+ }
535
+ }
536
+ catch {
537
+ // Ignorar errores
538
+ }
539
+ return null;
540
+ }
541
+ /**
542
+ * Encuentra alias que coincida con el path dado
543
+ */
544
+ findMatchingAlias(path) {
545
+ this.metrics.aliasMatches++;
546
+ for (const alias of this.aliasIndex) {
547
+ if (alias.regex.test(path)) {
548
+ return alias;
549
+ }
550
+ }
551
+ return null;
552
+ } /**
553
+ * Resuelve un alias a su ruta correspondiente
554
+ */
555
+ resolveAlias(path) {
556
+ const alias = this.findMatchingAlias(path);
557
+ if (!alias || !env.PATH_DIST) {
558
+ return null;
559
+ }
560
+ const relativePath = path.replace(alias.pattern, '');
561
+ const targetPath = alias.target[0];
562
+ if (!targetPath) {
563
+ return null;
564
+ } // Construir ruta final
565
+ let finalPath;
566
+ const pathDist = env.PATH_DIST.replace('./', '');
567
+ // Manejar caso especial: alias exacto sin wildcard (como #config -> config/index.js)
568
+ if (relativePath === '' && !targetPath.includes('*')) {
569
+ // Es un alias exacto, usar el target tal como está
570
+ if (targetPath.startsWith('/')) {
571
+ finalPath = join('/', pathDist, targetPath.substring(1));
572
+ }
573
+ else {
574
+ const cleanTarget = targetPath.replace('./', '');
575
+ if (cleanTarget.startsWith('src/')) {
576
+ const targetWithoutSrc = cleanTarget.replace('src/', '');
577
+ finalPath = join('/', pathDist, targetWithoutSrc);
578
+ }
579
+ else {
580
+ finalPath = join('/', pathDist, cleanTarget);
581
+ }
582
+ }
583
+ }
584
+ else if (targetPath.startsWith('/')) {
585
+ // Si el target empieza con /, es una ruta absoluta desde la raíz del proyecto
586
+ // Para targets como "/src/*", mapear directamente al PATH_DIST
587
+ // Remover el primer directorio si es diferente de PATH_DIST
588
+ const targetWithoutSlash = targetPath
589
+ .substring(1)
590
+ .replace('/*', '');
591
+ if (targetWithoutSlash === 'src' ||
592
+ targetWithoutSlash.startsWith('src/')) {
593
+ // Para "/src/*" mapear directamente a "/pathDist/relativePath"
594
+ finalPath = join('/', pathDist, relativePath);
595
+ }
596
+ else {
597
+ // Para otros casos como "/examples/*", también mapear directamente
598
+ finalPath = join('/', pathDist, relativePath);
599
+ }
600
+ }
601
+ else {
602
+ // Si es una ruta relativa, construir basándose en el target
603
+ const cleanTarget = targetPath.replace('./', '').replace('/*', '');
604
+ // Si el target ya incluye el directorio de distribución, no duplicar
605
+ if (cleanTarget === pathDist) {
606
+ finalPath = join('/', pathDist, relativePath);
607
+ }
608
+ else if (cleanTarget.startsWith(pathDist + '/')) {
609
+ // Si el target ya contiene PATH_DIST como prefijo
610
+ finalPath = join('/', cleanTarget, relativePath);
611
+ }
612
+ else {
613
+ // Caso normal: mapear manteniendo la estructura relativa al target
614
+ if (cleanTarget.startsWith('src/')) {
615
+ // Para "src/components/*" -> "/pathDist/components/*"
616
+ const targetWithoutSrc = cleanTarget.replace('src/', '');
617
+ finalPath = join('/', pathDist, targetWithoutSrc, relativePath);
618
+ }
619
+ else {
620
+ // Para casos como "examples/*" -> "/pathDist/*"
621
+ // No incluir el directorio raíz en la ruta final
622
+ const isRootDirectory = [
623
+ 'examples',
624
+ 'src',
625
+ 'app',
626
+ 'lib',
627
+ ].includes(cleanTarget);
628
+ if (isRootDirectory) {
629
+ finalPath = join('/', pathDist, relativePath);
630
+ }
631
+ else {
632
+ // Para subdirectorios específicos, mantener la estructura
633
+ finalPath = join('/', pathDist, cleanTarget, relativePath);
634
+ }
635
+ }
636
+ }
637
+ }
638
+ return finalPath.replace(/\\/g, '/');
639
+ }
640
+ /**
641
+ * Gestión de caché LRU
642
+ */
643
+ getFromCache(key) {
644
+ const entry = this.resolutionCache.get(key);
645
+ if (!entry) {
646
+ return undefined;
647
+ }
648
+ // Verificar expiración
649
+ if (Date.now() - entry.timestamp > this.cacheMaxAge) {
650
+ this.resolutionCache.delete(key);
651
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
652
+ return undefined;
653
+ }
654
+ // Actualizar orden LRU
655
+ entry.hits++;
656
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
657
+ this.cacheOrder.push(key);
658
+ return entry.result;
659
+ }
660
+ setCache(key, result) {
661
+ // Implementar límite de caché LRU
662
+ if (this.resolutionCache.size >= this.maxCacheSize) {
663
+ const oldestKey = this.cacheOrder.shift();
664
+ if (oldestKey) {
665
+ this.resolutionCache.delete(oldestKey);
666
+ }
667
+ }
668
+ this.resolutionCache.set(key, {
669
+ result,
670
+ timestamp: Date.now(),
671
+ hits: 0,
672
+ });
673
+ this.cacheOrder.push(key);
674
+ }
675
+ createCacheKey(moduleName, fromFile) {
676
+ const hash = createHash('md5');
677
+ hash.update(moduleName);
678
+ if (fromFile) {
679
+ hash.update(fromFile);
680
+ }
681
+ return hash.digest('hex');
682
+ }
683
+ /**
684
+ * Convierte ruta absoluta a ruta relativa desde node_modules
685
+ */
686
+ getNodeModulesRelativePath(fullPath) {
687
+ const idx = fullPath.indexOf('node_modules');
688
+ if (idx !== -1) {
689
+ return '/' + fullPath.substring(idx).replace(/\\/g, '/');
690
+ }
691
+ // Para rutas que no están en node_modules
692
+ const rel = relative(cwd(), fullPath).replace(/\\/g, '/');
693
+ return rel.startsWith('/') ? rel : '/' + rel;
694
+ }
695
+ /**
696
+ * Actualiza métricas de rendimiento
697
+ */
698
+ updateMetrics(resolveTime) {
699
+ this.metrics.averageResolveTime =
700
+ (this.metrics.averageResolveTime *
701
+ (this.metrics.totalResolutions - 1) +
702
+ resolveTime) /
703
+ this.metrics.totalResolutions;
704
+ }
705
+ /**
706
+ * Configura actualización periódica de índices
707
+ */
708
+ setupPeriodicRefresh() {
709
+ setInterval(() => {
710
+ if (Date.now() - this.lastIndexUpdate > this.indexRefreshInterval) {
711
+ if (env.VERBOSE === 'true') {
712
+ logger.info('🔄 Actualizando índices de resolución de módulos');
713
+ }
714
+ this.refreshIndexes();
715
+ }
716
+ }, this.indexRefreshInterval);
717
+ }
718
+ /**
719
+ * Actualiza los índices manteniendo el caché válido
720
+ */
721
+ refreshIndexes() {
722
+ try {
723
+ const oldSize = this.moduleIndex.size;
724
+ this.buildModuleIndex();
725
+ this.buildAliasIndex();
726
+ this.lastIndexUpdate = Date.now();
727
+ if (env.VERBOSE === 'true') {
728
+ logger.info(`📚 Índices actualizados: ${oldSize} → ${this.moduleIndex.size} módulos`);
729
+ }
730
+ }
731
+ catch (error) {
732
+ logger.error('Error actualizando índices:', error);
733
+ }
734
+ }
735
+ /**
736
+ * Limpia caché expirado
737
+ */
738
+ clearExpiredCache() {
739
+ const now = Date.now();
740
+ const keysToDelete = [];
741
+ for (const [key, entry] of this.resolutionCache.entries()) {
742
+ if (now - entry.timestamp > this.cacheMaxAge) {
743
+ keysToDelete.push(key);
744
+ }
745
+ }
746
+ for (const key of keysToDelete) {
747
+ this.resolutionCache.delete(key);
748
+ this.cacheOrder = this.cacheOrder.filter(k => k !== key);
749
+ }
750
+ if (env.VERBOSE === 'true' && keysToDelete.length > 0) {
751
+ logger.info(`🧹 Limpiado caché expirado: ${keysToDelete.length} entradas`);
752
+ }
753
+ }
754
+ /**
755
+ * Obtiene métricas de rendimiento
756
+ */
757
+ getMetrics() {
758
+ return {
759
+ ...this.metrics,
760
+ cacheSize: this.resolutionCache.size,
761
+ moduleIndexSize: this.moduleIndex.size,
762
+ aliasIndexSize: this.aliasIndex.length,
763
+ cacheHitRate: this.metrics.totalResolutions > 0
764
+ ? (this.metrics.cacheHits / this.metrics.totalResolutions) *
765
+ 100
766
+ : 0,
767
+ };
768
+ }
769
+ /**
770
+ * Resetea métricas de rendimiento
771
+ */
772
+ resetMetrics() {
773
+ this.metrics = {
774
+ totalResolutions: 0,
775
+ cacheHits: 0,
776
+ cacheMisses: 0,
777
+ averageResolveTime: 0,
778
+ indexLookups: 0,
779
+ filesystemAccess: 0,
780
+ aliasMatches: 0,
781
+ };
782
+ }
783
+ /**
784
+ * Forzar reconstrucción de índices
785
+ */
786
+ forceRefresh() {
787
+ this.initializeIndexes();
788
+ this.resolutionCache.clear();
789
+ this.cacheOrder = [];
790
+ if (env.VERBOSE === 'true') {
791
+ logger.info('🔄 Índices de resolución reconstruidos forzosamente');
792
+ }
793
+ }
794
+ /**
795
+ * Limpia todos los cachés y índices
796
+ */
797
+ cleanup() {
798
+ this.moduleIndex.clear();
799
+ this.resolutionCache.clear();
800
+ this.cacheOrder = [];
801
+ this.aliasIndex = [];
802
+ this.nodeModulesCache.clear();
803
+ if (env.VERBOSE === 'true') {
804
+ logger.info('🧹 Sistema de resolución de módulos limpiado');
805
+ }
806
+ }
807
+ }
808
+ // Funciones de compatibilidad con el sistema existente
809
+ export async function getOptimizedModulePath(moduleName, fromFile) {
810
+ const optimizer = ModuleResolutionOptimizer.getInstance();
811
+ const result = await optimizer.resolveModule(moduleName, fromFile);
812
+ return result.path;
813
+ }
814
+ export function getOptimizedAliasPath(path) {
815
+ const optimizer = ModuleResolutionOptimizer.getInstance();
816
+ return optimizer.resolveAlias(path);
817
+ }
818
+ export function getModuleResolutionMetrics() {
819
+ const optimizer = ModuleResolutionOptimizer.getInstance();
820
+ return optimizer.getMetrics();
821
+ }
822
+ //# sourceMappingURL=module-resolution-optimizer.js.map