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,506 @@
1
+ // Opción con librería '/node_modules/resolve/index.js' (npm install resolve)
2
+ import fs, { readFileSync } from 'node:fs';
3
+ import { dirname, join, relative } from 'node:path';
4
+ import { env } from 'node:process';
5
+ // import pkg from '/node_modules/enhanced-resolve/index.cjs';
6
+ // import resolve from '/node_modules/resolve/index.js';
7
+ import { logger } from '../servicios/logger.js';
8
+ // Lista de módulos que deben ser excluidos de la resolución automática de rutas
9
+ // Estos módulos se mantienen con su importación original sin transformar
10
+ const EXCLUDED_MODULES = new Set([
11
+ 'vue/compiler-sfc',
12
+ 'vue/dist/vue.runtime.esm-bundler',
13
+ '@vue/compiler-sfc',
14
+ '@vue/compiler-dom',
15
+ '@vue/runtime-core',
16
+ '@vue/runtime-dom', // Módulos de oxc-parser que tienen dependencias específicas de WASM
17
+ 'oxc-parser',
18
+ 'oxc-parser/wasm',
19
+ 'oxc-minify',
20
+ 'oxc-minify/browser',
21
+ '@oxc-parser/binding-wasm32-wasi',
22
+ '@oxc-minify/binding-wasm32-wasi',
23
+ // Módulos de TypeScript que pueden tener resoluciones complejas
24
+ 'typescript',
25
+ // Agregar más módulos problemáticos aquí según sea necesario
26
+ 'yargs',
27
+ 'yargs/helpers',
28
+ 'yargs-parser',
29
+ 'chalk',
30
+ 'browser-sync',
31
+ 'chokidar',
32
+ 'get-port',
33
+ 'execa',
34
+ 'find-root',
35
+ 'fs-extra',
36
+ ]);
37
+ // function resolveESMWithLibrary(moduleName: string): string | null {
38
+ // try {
39
+ // // Resolver el módulo
40
+ // const resolved = resolve.sync(moduleName, {
41
+ // basedir: process.cwd(),
42
+ // packageFilter: (pkg: any) => {
43
+ // // Priorizar campos ESM
44
+ // if (pkg.module) pkg.main = pkg.module;
45
+ // else if (pkg.exports?.['.']?.import)
46
+ // pkg.main = pkg.exports['.'].import;
47
+ // else if (pkg.exports?.import) pkg.main = pkg.exports.import;
48
+ // return pkg;
49
+ // },
50
+ // });
51
+ // return resolved;
52
+ // } catch (error) {
53
+ // if (env.VERBOSE === 'true')
54
+ // logger.error(
55
+ // `Error resolviendo ${moduleName}:`,
56
+ // error instanceof Error ? error.message : String(error),
57
+ // );
58
+ // return null;
59
+ // }
60
+ // }
61
+ // Opción con '/node_modules/enhanced-resolve/index.cjs' (webpack's resolver)
62
+ // npm install enhanced-resolve
63
+ // const { ResolverFactory } = pkg;
64
+ // const resolver = ResolverFactory.createResolver({
65
+ // fileSystem: {
66
+ // readFile,
67
+ // readlink,
68
+ // stat,
69
+ // readdir,
70
+ // },
71
+ // conditionNames: ['import', 'module', 'default'], // Priorizar ESM
72
+ // extensions: ['.mjs', '.js', '.json'],
73
+ // mainFields: ['module', 'main'], // Priorizar campo 'module'
74
+ // aliasFields: ['browser'],
75
+ // });
76
+ // function resolveESMEnhanced(moduleName: string): Promise<string | null> {
77
+ // return new Promise((resolve, reject) => {
78
+ // resolver.resolve({}, process.cwd(), moduleName, {}, (err, result) => {
79
+ // if (err) reject(err);
80
+ // else resolve(result as string);
81
+ // });
82
+ // });
83
+ // }
84
+ // Función para buscar la mejor versión ESM/browser optimizada de un archivo
85
+ function findOptimalESMVersion(moduleDir, entryPoint) {
86
+ const dir = dirname(entryPoint);
87
+ const baseName = entryPoint.split('/').pop() || '';
88
+ const nameWithoutExt = baseName.replace(/\.[^/.]+$/, '');
89
+ // Directorio donde buscar
90
+ const searchDir = join(moduleDir, dir);
91
+ if (!fs.existsSync(searchDir)) {
92
+ return entryPoint;
93
+ }
94
+ try {
95
+ const files = fs.readdirSync(searchDir); // Patrones de prioridad para buscar versiones optimizadas
96
+ // Prioriza versiones completas de desarrollo para mejor debugging
97
+ const priorityPatterns = [
98
+ // Máxima prioridad: ESM-Browser completo (sin runtime, desarrollo)
99
+ `${nameWithoutExt}.esm-browser.js`,
100
+ // ESM puro sin minificar (desarrollo)
101
+ `${nameWithoutExt}.esm.all.js`,
102
+ `${nameWithoutExt}.esm.js`,
103
+ `${nameWithoutExt}.module.js`,
104
+ // Browser puro sin minificar (desarrollo)
105
+ `${nameWithoutExt}.browser.js`,
106
+ `${nameWithoutExt}.web.js`,
107
+ // UMD sin minificar (desarrollo)
108
+ `${nameWithoutExt}.umd.js`,
109
+ `${nameWithoutExt}.global.js`,
110
+ // Fallback a versiones minificadas sin runtime
111
+ `${nameWithoutExt}.esm-browser.min.js`,
112
+ `${nameWithoutExt}.esm-browser.prod.js`,
113
+ `${nameWithoutExt}.esm.all.min.js`,
114
+ `${nameWithoutExt}.esm.min.js`,
115
+ `${nameWithoutExt}.module.min.js`,
116
+ `${nameWithoutExt}.browser.min.js`,
117
+ `${nameWithoutExt}.browser.prod.js`,
118
+ `${nameWithoutExt}.web.min.js`,
119
+ `${nameWithoutExt}.umd.min.js`,
120
+ `${nameWithoutExt}.global.min.js`,
121
+ `${nameWithoutExt}.min.js`,
122
+ // Último recurso: versiones runtime (solo si no hay alternativas)
123
+ `${nameWithoutExt}.runtime.esm-browser.js`,
124
+ `${nameWithoutExt}.runtime.esm-browser.min.js`,
125
+ `${nameWithoutExt}.runtime.esm-browser.prod.js`,
126
+ ];
127
+ // Buscar archivos que coincidan exactamente con los patrones
128
+ for (const pattern of priorityPatterns) {
129
+ if (files.includes(pattern)) {
130
+ const optimizedPath = join(dir, pattern).replace(/\\/g, '/');
131
+ if (env.VERBOSE === 'true') {
132
+ logger.info(`Versión optimizada encontrada: ${optimizedPath}`);
133
+ }
134
+ return optimizedPath;
135
+ }
136
+ } // Buscar archivos que contengan patrones ESM/browser dinámicamente
137
+ const esmBrowserFiles = files.filter(file => {
138
+ const lowerFile = file.toLowerCase();
139
+ return ((lowerFile.includes('.esm-browser.') || // Prioridad alta: combinación esm-browser
140
+ lowerFile.includes('.esm.') ||
141
+ lowerFile.includes('.module.') ||
142
+ lowerFile.includes('.browser.') ||
143
+ lowerFile.includes('.web.') ||
144
+ lowerFile.includes('.runtime.esm-browser.')) && // Runtime como última opción
145
+ (file.endsWith('.js') || file.endsWith('.mjs')));
146
+ });
147
+ if (esmBrowserFiles.length > 0) {
148
+ // Primera prioridad: archivos que combinan ESM y Browser (sin runtime)
149
+ const esmBrowserCombined = esmBrowserFiles.filter(file => file.toLowerCase().includes('.esm-browser.') &&
150
+ !file.toLowerCase().includes('.runtime.'));
151
+ if (esmBrowserCombined.length > 0) {
152
+ // Dentro de esm-browser, priorizar desarrollo > .prod > .min
153
+ const devFiles = esmBrowserCombined.filter(file => !file.toLowerCase().includes('.prod.') &&
154
+ !file.toLowerCase().includes('.min.'));
155
+ if (devFiles.length > 0 && devFiles[0]) {
156
+ const optimizedPath = join(dir, devFiles[0]).replace(/\\/g, '/');
157
+ if (env.VERBOSE === 'true') {
158
+ logger.info(`Versión ESM-Browser dev encontrada: ${optimizedPath}`);
159
+ }
160
+ return optimizedPath;
161
+ }
162
+ const prodFiles = esmBrowserCombined.filter(file => file.toLowerCase().includes('.prod.'));
163
+ if (prodFiles.length > 0 && prodFiles[0]) {
164
+ const optimizedPath = join(dir, prodFiles[0]).replace(/\\/g, '/');
165
+ if (env.VERBOSE === 'true') {
166
+ logger.info(`Versión ESM-Browser producción encontrada: ${optimizedPath}`);
167
+ }
168
+ return optimizedPath;
169
+ }
170
+ const minFiles = esmBrowserCombined.filter(file => file.toLowerCase().includes('.min.'));
171
+ if (minFiles.length > 0 && minFiles[0]) {
172
+ const optimizedPath = join(dir, minFiles[0]).replace(/\\/g, '/');
173
+ if (env.VERBOSE === 'true') {
174
+ logger.info(`Versión ESM-Browser minificada encontrada: ${optimizedPath}`);
175
+ }
176
+ return optimizedPath;
177
+ }
178
+ if (esmBrowserCombined[0]) {
179
+ const optimizedPath = join(dir, esmBrowserCombined[0]).replace(/\\/g, '/');
180
+ if (env.VERBOSE === 'true') {
181
+ logger.info(`Versión ESM-Browser encontrada: ${optimizedPath}`);
182
+ }
183
+ return optimizedPath;
184
+ }
185
+ }
186
+ // Segunda prioridad: cualquier versión ESM disponible (sin minificar)
187
+ const esmFiles = esmBrowserFiles.filter(file => (file.toLowerCase().includes('.esm.') ||
188
+ file.toLowerCase().includes('.module.')) &&
189
+ !file.toLowerCase().includes('.min.') &&
190
+ !file.toLowerCase().includes('.prod.') &&
191
+ !file.toLowerCase().includes('.runtime.'));
192
+ if (esmFiles.length > 0 && esmFiles[0]) {
193
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
194
+ if (env.VERBOSE === 'true') {
195
+ logger.info(`Versión ESM dev encontrada: ${optimizedPath}`);
196
+ }
197
+ return optimizedPath;
198
+ }
199
+ // Tercera prioridad: archivos minificados de cualquier tipo ESM/browser (sin runtime)
200
+ const minifiedFiles = esmBrowserFiles.filter(file => (file.toLowerCase().includes('.min.') ||
201
+ file.toLowerCase().includes('.prod.')) &&
202
+ !file.toLowerCase().includes('.runtime.'));
203
+ if (minifiedFiles.length > 0) {
204
+ // Priorizar ESM sobre browser sobre UMD
205
+ const esmFiles = minifiedFiles.filter(file => file.toLowerCase().includes('.esm.') ||
206
+ file.toLowerCase().includes('.module.'));
207
+ if (esmFiles.length > 0 && esmFiles[0]) {
208
+ const optimizedPath = join(dir, esmFiles[0]).replace(/\\/g, '/');
209
+ if (env.VERBOSE === 'true') {
210
+ logger.info(`Versión ESM minificada encontrada: ${optimizedPath}`);
211
+ }
212
+ return optimizedPath;
213
+ }
214
+ if (minifiedFiles[0]) {
215
+ const optimizedPath = join(dir, minifiedFiles[0]).replace(/\\/g, '/');
216
+ if (env.VERBOSE === 'true') {
217
+ logger.info(`Versión minificada encontrada: ${optimizedPath}`);
218
+ }
219
+ return optimizedPath;
220
+ }
221
+ }
222
+ // Cuarta prioridad: versiones runtime como último recurso
223
+ const runtimeFiles = esmBrowserFiles.filter(file => file.toLowerCase().includes('.runtime.esm-browser.'));
224
+ if (runtimeFiles.length > 0) {
225
+ // Priorizar desarrollo sobre producción en runtime también
226
+ const devRuntimeFiles = runtimeFiles.filter(file => !file.toLowerCase().includes('.prod.') &&
227
+ !file.toLowerCase().includes('.min.'));
228
+ if (devRuntimeFiles.length > 0 && devRuntimeFiles[0]) {
229
+ const optimizedPath = join(dir, devRuntimeFiles[0]).replace(/\\/g, '/');
230
+ if (env.VERBOSE === 'true') {
231
+ logger.info(`Versión Runtime ESM-Browser dev encontrada: ${optimizedPath}`);
232
+ }
233
+ return optimizedPath;
234
+ }
235
+ if (runtimeFiles[0]) {
236
+ const optimizedPath = join(dir, runtimeFiles[0]).replace(/\\/g, '/');
237
+ if (env.VERBOSE === 'true') {
238
+ logger.info(`Versión Runtime ESM-Browser encontrada: ${optimizedPath}`);
239
+ }
240
+ return optimizedPath;
241
+ }
242
+ }
243
+ // Fallback: cualquier versión browser
244
+ if (esmBrowserFiles[0]) {
245
+ const optimizedPath = join(dir, esmBrowserFiles[0]).replace(/\\/g, '/');
246
+ if (env.VERBOSE === 'true') {
247
+ logger.info(`Versión browser encontrada: ${optimizedPath}`);
248
+ }
249
+ return optimizedPath;
250
+ }
251
+ }
252
+ }
253
+ catch (error) {
254
+ if (env.VERBOSE === 'true') {
255
+ logger.warn(`No se pudo leer directorio ${searchDir}:`, error instanceof Error ? error.message : String(error));
256
+ }
257
+ }
258
+ return entryPoint; // Fallback al entry point original
259
+ }
260
+ // Función mejorada para detectar automáticamente entry points browser-compatible
261
+ function simpleESMResolver(moduleName) {
262
+ try {
263
+ const nodeModulesPath = join(process.cwd(), 'node_modules', moduleName);
264
+ let packagePath;
265
+ let packageJson;
266
+ try {
267
+ packagePath = join(nodeModulesPath, 'package.json');
268
+ if (!fs.existsSync(packagePath)) {
269
+ throw new Error(`No se encontró package.json para ${moduleName}`);
270
+ }
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
276
+ const moduleDir = dirname(packagePath);
277
+ const isESM = packageJson.type === 'module'; // Determinar el entry point ESM/Browser optimizado
278
+ let entryPoint = null;
279
+ // 1. Prioridad máxima: campo module para ESM
280
+ if (packageJson.module) {
281
+ entryPoint = packageJson.module;
282
+ }
283
+ // 2. Revisar exports field con prioridad ESM
284
+ else if (packageJson.exports) {
285
+ if (typeof packageJson.exports === 'string') {
286
+ entryPoint = packageJson.exports;
287
+ }
288
+ else if (packageJson.exports['.']) {
289
+ const dotExport = packageJson.exports['.'];
290
+ if (typeof dotExport === 'string') {
291
+ entryPoint = dotExport;
292
+ }
293
+ else if (typeof dotExport === 'object') {
294
+ // Priorizar import > browser > default para compatibilidad ESM
295
+ // Buscar específicamente patrones esm-browser primero
296
+ const exportKeys = Object.keys(dotExport);
297
+ const esmBrowserKey = exportKeys.find(key => key.includes('browser') &&
298
+ (key.includes('esm') || key.includes('module')));
299
+ if (esmBrowserKey &&
300
+ typeof dotExport[esmBrowserKey] === 'string') {
301
+ entryPoint = dotExport[esmBrowserKey];
302
+ }
303
+ else {
304
+ // Priorizar import > browser > default
305
+ entryPoint =
306
+ (typeof dotExport.import === 'string'
307
+ ? dotExport.import
308
+ : null) ||
309
+ dotExport.browser ||
310
+ (typeof dotExport.default === 'string'
311
+ ? dotExport.default
312
+ : null);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ // 3. Revisar browser field específico
318
+ else if (packageJson.browser) {
319
+ if (typeof packageJson.browser === 'string') {
320
+ entryPoint = packageJson.browser;
321
+ }
322
+ else if (typeof packageJson.browser === 'object') {
323
+ // Si browser es un objeto de mapeo, buscar la entrada principal
324
+ entryPoint =
325
+ packageJson.browser['.'] ||
326
+ packageJson.browser[packageJson.main];
327
+ }
328
+ }
329
+ // 4. Fallback a main field
330
+ else if (packageJson.main) {
331
+ entryPoint = packageJson.main;
332
+ }
333
+ // 5. Fallback por defecto según el tipo de módulo
334
+ if (!entryPoint) {
335
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
336
+ }
337
+ // Asegurarse de que el entry point es una cadena
338
+ if (typeof entryPoint !== 'string') {
339
+ if (env.VERBOSE === 'true')
340
+ logger.warn(`Entry point no es string para ${moduleName}:`, entryPoint);
341
+ entryPoint = isESM ? 'index.js' : 'index.cjs';
342
+ } // Resolver la ruta final
343
+ let finalPath = join(moduleDir, entryPoint);
344
+ // Buscar una versión ESM/browser optimizada
345
+ const optimizedEntry = findOptimalESMVersion(moduleDir, entryPoint);
346
+ if (optimizedEntry && optimizedEntry !== entryPoint) {
347
+ finalPath = join(moduleDir, optimizedEntry);
348
+ }
349
+ // Si es ESM, verificar si hay imports privados que necesiten ser resueltos
350
+ if (isESM && packageJson.imports) {
351
+ const importMap = new Map();
352
+ for (const [key, value] of Object.entries(packageJson.imports)) {
353
+ if (typeof value === 'string') {
354
+ importMap.set(key, join(moduleDir, value));
355
+ }
356
+ else if (typeof value === 'object' && value !== null) {
357
+ // Priorizar la versión browser
358
+ const valueObj = value;
359
+ const browserPath = valueObj.browser || valueObj.default || valueObj.node;
360
+ if (browserPath) {
361
+ importMap.set(key, join(moduleDir, browserPath));
362
+ }
363
+ }
364
+ }
365
+ // Si el archivo existe, leer su contenido y verificar imports privados
366
+ if (fs.existsSync(finalPath)) {
367
+ const content = readFileSync(finalPath, 'utf-8');
368
+ const privateImports = Array.from(content.matchAll(/from\s+['"]([#@][^'"]+)['"]/g));
369
+ if (privateImports.length > 0) {
370
+ if (env.VERBOSE === 'true')
371
+ logger.info(`Módulo ${moduleName} usa imports privados:`, privateImports.map(m => m[1]));
372
+ // Si usa imports privados, asegurarnos de que estén disponibles
373
+ for (const [, importPath] of privateImports) {
374
+ if (!importMap.has(importPath)) {
375
+ if (env.VERBOSE === 'true')
376
+ logger.warn(`Import privado no resuelto: ${importPath} en ${moduleName}`);
377
+ }
378
+ }
379
+ }
380
+ }
381
+ }
382
+ // Verificar que el archivo existe
383
+ if (!fs.existsSync(finalPath)) {
384
+ if (env.VERBOSE === 'true')
385
+ logger.warn(`⚠️ Archivo no existe: ${finalPath}, buscando alternativas...`);
386
+ // Intentar alternativas comunes
387
+ const alternatives = [
388
+ entryPoint,
389
+ entryPoint.replace('.js', '.mjs'),
390
+ entryPoint.replace('.mjs', '.js'),
391
+ entryPoint.replace('.js', '.cjs'),
392
+ 'index.mjs',
393
+ 'index.js',
394
+ 'index.cjs',
395
+ ];
396
+ for (const alt of alternatives) {
397
+ const altPath = join(moduleDir, alt);
398
+ if (fs.existsSync(altPath)) {
399
+ finalPath = altPath;
400
+ break;
401
+ }
402
+ }
403
+ }
404
+ return finalPath;
405
+ }
406
+ catch (error) {
407
+ if (env.VERBOSE === 'true')
408
+ logger.error(`Error resolviendo ${moduleName}: ${error instanceof Error ? error.message : String(error)}`);
409
+ return null;
410
+ }
411
+ }
412
+ // Función utilitaria para obtener rutas absolutas desde la raíz del proyecto
413
+ function getNodeModulesRelativePath(fullPath, _fromFile) {
414
+ if (!fullPath)
415
+ return null;
416
+ const idx = fullPath.indexOf('node_modules');
417
+ if (idx !== -1) {
418
+ // Extraer solo la parte desde node_modules en adelante
419
+ let relativePath = fullPath.substring(idx).replace(/\\/g, '/');
420
+ // Devolver ruta absoluta desde la raíz del proyecto (sin ../)
421
+ // Esto permite que los archivos compilados accedan directamente a node_modules
422
+ return '/' + relativePath;
423
+ }
424
+ // Para rutas que no están en node_modules, convertir a ruta absoluta desde la raíz
425
+ let rel = relative(process.cwd(), fullPath).replace(/\\/g, '/');
426
+ if (!rel)
427
+ rel = '.';
428
+ // Convertir a ruta absoluta desde la raíz
429
+ if (!rel.startsWith('/')) {
430
+ rel = '/' + rel;
431
+ }
432
+ return rel;
433
+ }
434
+ export function getModulePath(moduleName, fromFile) {
435
+ // Verificar si el módulo está en la lista de excluidos
436
+ if (EXCLUDED_MODULES.has(moduleName)) {
437
+ if (env.VERBOSE === 'true')
438
+ logger.info(`Módulo ${moduleName} está en la lista de excluidos, manteniendo importación original`);
439
+ return null; // Retornar null para mantener la importación original
440
+ }
441
+ return getNodeModulesRelativePath(simpleESMResolver(moduleName), fromFile);
442
+ }
443
+ // Nueva función para resolver subpaths de módulos (ej: 'yargs/helpers')
444
+ export function getModuleSubPath(moduleName, fromFile) {
445
+ // Verificar si el módulo está en la lista de excluidos
446
+ if (EXCLUDED_MODULES.has(moduleName)) {
447
+ if (env.VERBOSE === 'true')
448
+ logger.info(`Módulo ${moduleName} está en la lista de excluidos, manteniendo importación original`);
449
+ return null; // Retornar null para mantener la importación original
450
+ } // Si contiene '/', es un subpath
451
+ if (moduleName.includes('/')) {
452
+ const [packageName, ...subPathParts] = moduleName.split('/');
453
+ const subPath = subPathParts.join('/');
454
+ // Verificar que packageName no esté vacío
455
+ if (!packageName) {
456
+ return null;
457
+ }
458
+ try {
459
+ const nodeModulesPath = join(process.cwd(), 'node_modules', packageName);
460
+ const packagePath = join(nodeModulesPath, 'package.json');
461
+ if (!fs.existsSync(packagePath)) {
462
+ return null;
463
+ }
464
+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf-8'));
465
+ const moduleDir = dirname(packagePath);
466
+ // Revisar exports field para subpaths
467
+ if (packageJson.exports &&
468
+ typeof packageJson.exports === 'object') {
469
+ const exportKey = `./${subPath}`;
470
+ let exportPath = packageJson.exports[exportKey];
471
+ if (exportPath) {
472
+ if (typeof exportPath === 'string') {
473
+ return getNodeModulesRelativePath(join(moduleDir, exportPath), fromFile);
474
+ }
475
+ else if (typeof exportPath === 'object') {
476
+ // Priorizar import > default para ESM
477
+ const importPath = exportPath.import || exportPath.default;
478
+ if (typeof importPath === 'string') {
479
+ return getNodeModulesRelativePath(join(moduleDir, importPath), fromFile);
480
+ }
481
+ }
482
+ }
483
+ }
484
+ // Fallback: intentar resolver directamente el subpath
485
+ const directPath = join(moduleDir, subPath);
486
+ if (fs.existsSync(directPath)) {
487
+ return getNodeModulesRelativePath(directPath, fromFile);
488
+ }
489
+ // Intentar con extensiones comunes
490
+ const extensions = ['.mjs', '.js', '.cjs'];
491
+ for (const ext of extensions) {
492
+ const pathWithExt = directPath + ext;
493
+ if (fs.existsSync(pathWithExt)) {
494
+ return getNodeModulesRelativePath(pathWithExt, fromFile);
495
+ }
496
+ }
497
+ }
498
+ catch (error) {
499
+ if (env.VERBOSE === 'true')
500
+ logger.error(`Error resolviendo subpath ${moduleName}:`, error instanceof Error ? error.message : String(error));
501
+ }
502
+ }
503
+ // Si no es un subpath, usar el resolver normal
504
+ return getModulePath(moduleName, fromFile);
505
+ }
506
+ //# sourceMappingURL=module-resolver.js.map
@@ -0,0 +1,48 @@
1
+ import { stdin as input, stdout as output } from 'node:process';
2
+ import * as readline from 'node:readline/promises';
3
+ import { logger } from '../servicios/logger.js';
4
+ export async function promptUser(question, timeout = 30000) {
5
+ const rl = readline.createInterface({ input, output });
6
+ return new Promise((resolve, reject) => {
7
+ let isResolved = false;
8
+ // Timeout para evitar espera infinita
9
+ const timer = setTimeout(() => {
10
+ if (!isResolved) {
11
+ isResolved = true;
12
+ rl.close();
13
+ reject(new Error('Timeout: No se recibió respuesta del usuario'));
14
+ }
15
+ }, timeout);
16
+ // Manejar Ctrl+C
17
+ const handleSigint = () => {
18
+ if (!isResolved) {
19
+ isResolved = true;
20
+ clearTimeout(timer);
21
+ rl.close();
22
+ logger.info('\n🛑 Operación cancelada por el usuario.');
23
+ process.exit(0);
24
+ }
25
+ };
26
+ process.on('SIGINT', handleSigint);
27
+ rl.question(question)
28
+ .then(answer => {
29
+ if (!isResolved) {
30
+ isResolved = true;
31
+ clearTimeout(timer);
32
+ process.removeListener('SIGINT', handleSigint);
33
+ rl.close();
34
+ resolve(answer);
35
+ }
36
+ })
37
+ .catch(error => {
38
+ if (!isResolved) {
39
+ isResolved = true;
40
+ clearTimeout(timer);
41
+ process.removeListener('SIGINT', handleSigint);
42
+ rl.close();
43
+ reject(error);
44
+ }
45
+ });
46
+ });
47
+ }
48
+ //# sourceMappingURL=promptUser.js.map
@@ -0,0 +1,29 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import findRoot from 'find-root';
4
+ import fs from 'fs-extra';
5
+ export function resolveBin(moduleName, { executable = moduleName, paths = [process.cwd()], } = {}) {
6
+ let rootDir;
7
+ try {
8
+ const customRequire = createRequire(__filename);
9
+ const resolved = customRequire.resolve(moduleName, { paths });
10
+ rootDir = findRoot(resolved);
11
+ }
12
+ catch (e) {
13
+ const modJson = require.resolve(`${moduleName}/package.json`, {
14
+ paths,
15
+ });
16
+ rootDir = path.dirname(modJson);
17
+ }
18
+ const packageJsonPath = path.join(rootDir, 'package.json');
19
+ const packageJson = fs.readJsonSync(packageJsonPath);
20
+ if (!packageJson.bin) {
21
+ throw new Error(`no bin found in ${packageJson.name}@${packageJson.version} in path ${packageJsonPath}`);
22
+ }
23
+ const binProp = typeof packageJson.bin === 'string'
24
+ ? packageJson.bin
25
+ : packageJson.bin[executable];
26
+ const binPath = path.join(rootDir, binProp);
27
+ return binPath;
28
+ }
29
+ //# sourceMappingURL=resolve-bin.js.map
@@ -1,48 +1,21 @@
1
- import path from 'node:path';
2
1
  /**
3
2
  * Converts a 24-hour time string to a 12-hour time string with AM/PM.
4
3
  *
5
4
  * @param {number} timing - The value of the timing en miliseconds.
6
5
  * @returns {string} the timing in ms, seconds, minutes or hours.
7
6
  */
8
- export const showTimingForHumans = timing => {
7
+ export const showTimingForHumans = (timing) => {
9
8
  if (timing < 1000) {
10
9
  return `${timing} ms`;
11
- } else if (timing < 60000) {
10
+ }
11
+ else if (timing < 60000) {
12
12
  return `${timing / 1000} s`;
13
- } else if (timing < 3600000) {
13
+ }
14
+ else if (timing < 3600000) {
14
15
  return `${timing / 60000} min`;
15
- } else {
16
+ }
17
+ else {
16
18
  return `${timing / 3600000} h`;
17
19
  }
18
20
  };
19
-
20
- /**
21
- * Mapea una ruta de origen a una ruta de destino en el directorio de distribución.
22
- * @param {string} ruta - La ruta de origen.
23
- * @returns {Promise<string>} - La ruta mapeada en el directorio de distribución.
24
- */
25
- export const mapRuta = async (ruta, PATH_DIST, PATH_SOURCE) =>
26
- path.join(PATH_DIST, path.relative(PATH_SOURCE, ruta));
27
-
28
- /**
29
- * Agrega la extensión .js a las importaciones en la cadena de datos proporcionada.
30
- * @param {string} data - La cadena de entrada que contiene el código JavaScript.
31
- * @returns {Promise<string>} - Una promesa que se resuelve con la cadena modificada con las importaciones actualizadas.
32
- */
33
- export const addImportEndJs = async data => {
34
- const importRegExp =
35
- /(?:import\s+.*?from\s+['"](.*?)['"]|import\(['"](.*?)['"]\))/g; // Manejar importaciones estáticas y dinámicas
36
-
37
- return data.replace(importRegExp, (match, ruta1, ruta2) => {
38
- const ruta = ruta1 || ruta2; // Usar la ruta capturada, ya sea estática o dinámica
39
- if (ruta.endsWith('.vue') || ruta.endsWith('.ts')) {
40
- const fullPath = ruta.replace(/\.(vue|ts)$/, '.js');
41
- return match.replace(ruta, fullPath);
42
- } else if (!ruta.match(/\/.*\.(js|mjs|css)$/) && ruta.includes('/')) {
43
- return match.replace(ruta, `${ruta}.js`);
44
- }
45
-
46
- return match; // Devolver el match original si no se cumple ninguna condición
47
- });
48
- };
21
+ //# sourceMappingURL=utils.js.map