versacompiler 1.0.4 → 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.
- package/README.md +357 -145
- package/dist/compiler/compile.js +1120 -0
- package/dist/compiler/error-reporter.js +467 -0
- package/dist/compiler/linter.js +72 -0
- package/dist/{services → compiler}/minify.js +40 -31
- package/dist/compiler/parser.js +30 -0
- package/dist/compiler/tailwindcss.js +39 -0
- package/dist/compiler/transformTStoJS.js +16 -0
- package/dist/compiler/transforms.js +544 -0
- package/dist/compiler/typescript-error-parser.js +282 -0
- package/dist/compiler/typescript-sync-validator.js +230 -0
- package/dist/compiler/typescript-worker-thread.cjs +457 -0
- package/dist/compiler/typescript-worker.js +309 -0
- package/dist/compiler/typescript.js +382 -0
- package/dist/compiler/vuejs.js +296 -0
- package/dist/hrm/VueHRM.js +353 -0
- package/dist/hrm/errorScreen.js +23 -1
- package/dist/hrm/getInstanciaVue.js +313 -0
- package/dist/hrm/initHRM.js +140 -0
- package/dist/main.js +287 -0
- package/dist/servicios/browserSync.js +177 -0
- package/dist/servicios/chokidar.js +178 -0
- package/dist/servicios/logger.js +33 -0
- package/dist/servicios/readConfig.js +429 -0
- package/dist/utils/module-resolver.js +506 -0
- package/dist/utils/promptUser.js +48 -0
- package/dist/utils/resolve-bin.js +29 -0
- package/dist/utils/utils.js +21 -48
- package/dist/wrappers/eslint-node.js +145 -0
- package/dist/wrappers/oxlint-node.js +120 -0
- package/dist/wrappers/tailwind-node.js +92 -0
- package/package.json +62 -15
- package/dist/hrm/devMode.js +0 -249
- package/dist/hrm/instanciaVue.js +0 -35
- package/dist/hrm/setupHMR.js +0 -57
- package/dist/index.js +0 -873
- package/dist/services/acorn.js +0 -29
- package/dist/services/linter.js +0 -55
- package/dist/services/typescript.js +0 -89
- package/dist/services/vueLoader.js +0 -324
- package/dist/services/vuejs.js +0 -259
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import oxc from '/node_modules/oxc-transform/browser.js';
|
|
2
|
+
export function traspileTStoJS(filePath, sourceCode) {
|
|
3
|
+
try {
|
|
4
|
+
const { code: outputText, declaration, errors: diagnostics, } = oxc.transform(filePath, sourceCode);
|
|
5
|
+
return {
|
|
6
|
+
outputText: outputText,
|
|
7
|
+
declaration: declaration || '',
|
|
8
|
+
diagnostics: diagnostics || [],
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
console.error(`Error transpiling ${filePath}:`, error);
|
|
13
|
+
return { outputText: '', declaration: '', diagnostics: [error] };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=transformTStoJS.js.map
|
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { env } from 'node:process';
|
|
3
|
+
import { logger } from '../servicios/logger.js';
|
|
4
|
+
import { getModuleSubPath } from '../utils/module-resolver.js';
|
|
5
|
+
import { analyzeAndFormatMultipleErrors } from './error-reporter.js';
|
|
6
|
+
import { parser } from './parser.js';
|
|
7
|
+
// Módulos built-in de Node.js que no deben ser resueltos
|
|
8
|
+
const NODE_BUILTIN_MODULES = new Set([
|
|
9
|
+
'fs',
|
|
10
|
+
'path',
|
|
11
|
+
'os',
|
|
12
|
+
'crypto',
|
|
13
|
+
'http',
|
|
14
|
+
'https',
|
|
15
|
+
'url',
|
|
16
|
+
'util',
|
|
17
|
+
'events',
|
|
18
|
+
'stream',
|
|
19
|
+
'buffer',
|
|
20
|
+
'child_process',
|
|
21
|
+
'cluster',
|
|
22
|
+
'dgram',
|
|
23
|
+
'dns',
|
|
24
|
+
'net',
|
|
25
|
+
'readline',
|
|
26
|
+
'repl',
|
|
27
|
+
'tls',
|
|
28
|
+
'tty',
|
|
29
|
+
'vm',
|
|
30
|
+
'zlib',
|
|
31
|
+
'assert',
|
|
32
|
+
'module',
|
|
33
|
+
'process',
|
|
34
|
+
'querystring',
|
|
35
|
+
'string_decoder',
|
|
36
|
+
'timers',
|
|
37
|
+
'v8',
|
|
38
|
+
'worker_threads',
|
|
39
|
+
]);
|
|
40
|
+
/**
|
|
41
|
+
* Determina si un moduleRequest es un módulo externo que debe ser resuelto
|
|
42
|
+
* @param moduleRequest - El string del import (ej: 'vue', './local', '/absolute')
|
|
43
|
+
* @param pathAlias - Objeto con los alias definidos
|
|
44
|
+
* @returns true si es un módulo externo que debe resolverse
|
|
45
|
+
*/
|
|
46
|
+
function isExternalModule(moduleRequest, pathAlias) {
|
|
47
|
+
// Descartar rutas relativas y absolutas
|
|
48
|
+
if (moduleRequest.startsWith('./') ||
|
|
49
|
+
moduleRequest.startsWith('../') ||
|
|
50
|
+
moduleRequest.startsWith('/')) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
// Descartar rutas que parecen ser locales (contienen carpetas conocidas del proyecto)
|
|
54
|
+
const localPaths = [
|
|
55
|
+
'public/',
|
|
56
|
+
'src/',
|
|
57
|
+
'dist/',
|
|
58
|
+
'components/',
|
|
59
|
+
'utils/',
|
|
60
|
+
'assets/',
|
|
61
|
+
'styles/',
|
|
62
|
+
];
|
|
63
|
+
if (localPaths.some(localPath => moduleRequest.startsWith(localPath))) {
|
|
64
|
+
return false;
|
|
65
|
+
} // Descartar módulos built-in de Node.js (incluyendo node: prefix)
|
|
66
|
+
const cleanModuleName = moduleRequest.replace(/^node:/, '');
|
|
67
|
+
if (NODE_BUILTIN_MODULES.has(cleanModuleName)) {
|
|
68
|
+
return false;
|
|
69
|
+
} // NUEVA LÓGICA: Verificar PRIMERO si es un módulo excluido antes de verificar alias
|
|
70
|
+
// Esto es importante porque algunos módulos excluidos pueden tener nombres que
|
|
71
|
+
// coinciden con patrones de alias (como @vue/compiler-sfc con @/*)
|
|
72
|
+
const EXCLUDED_MODULES = new Set([
|
|
73
|
+
'vue/compiler-sfc',
|
|
74
|
+
'vue/dist/vue.runtime.esm-bundler',
|
|
75
|
+
'@vue/compiler-sfc',
|
|
76
|
+
'@vue/compiler-dom',
|
|
77
|
+
'@vue/runtime-core',
|
|
78
|
+
'@vue/runtime-dom',
|
|
79
|
+
'oxc-parser',
|
|
80
|
+
'oxc-parser/wasm',
|
|
81
|
+
'oxc-minify',
|
|
82
|
+
'oxc-minify/browser',
|
|
83
|
+
'@oxc-parser/binding-wasm32-wasi',
|
|
84
|
+
'@oxc-minify/binding-wasm32-wasi',
|
|
85
|
+
'typescript/lib/typescript',
|
|
86
|
+
]);
|
|
87
|
+
if (EXCLUDED_MODULES.has(moduleRequest)) {
|
|
88
|
+
return true;
|
|
89
|
+
} // Descartar alias conocidos
|
|
90
|
+
for (const alias of Object.keys(pathAlias)) {
|
|
91
|
+
const aliasPattern = alias.replace('/*', '');
|
|
92
|
+
if (moduleRequest.startsWith(aliasPattern)) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
} // Verificar si parece ser un módulo npm (no contiene extensiones de archivo)
|
|
96
|
+
if (moduleRequest.includes('.js') ||
|
|
97
|
+
moduleRequest.includes('.ts') ||
|
|
98
|
+
moduleRequest.includes('.vue') ||
|
|
99
|
+
moduleRequest.includes('.css') ||
|
|
100
|
+
moduleRequest.includes('.json')) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
// Si llegamos aquí, es probablemente un módulo externo
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
export async function replaceAliasImportStatic(file, code) {
|
|
107
|
+
if (!env.PATH_ALIAS || !env.PATH_DIST) {
|
|
108
|
+
return code;
|
|
109
|
+
}
|
|
110
|
+
const pathAlias = JSON.parse(env.PATH_ALIAS);
|
|
111
|
+
let resultCode = code;
|
|
112
|
+
// Usar regex para transformar imports estáticos
|
|
113
|
+
const importRegex = /import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"`]([^'"`]+)['"`]/g;
|
|
114
|
+
// Crear un array para procesar transformaciones async
|
|
115
|
+
const matches = Array.from(resultCode.matchAll(importRegex));
|
|
116
|
+
for (const match of matches) {
|
|
117
|
+
const [, moduleRequest] = match;
|
|
118
|
+
if (!moduleRequest)
|
|
119
|
+
continue; // Skip if moduleRequest is undefined
|
|
120
|
+
let newPath = null;
|
|
121
|
+
let transformed = false;
|
|
122
|
+
// 1. PRIMERO: Verificar si es un módulo excluido (prioridad máxima)
|
|
123
|
+
if (!transformed && isExternalModule(moduleRequest, pathAlias)) {
|
|
124
|
+
try {
|
|
125
|
+
const modulePath = getModuleSubPath(moduleRequest, file);
|
|
126
|
+
if (modulePath === null) {
|
|
127
|
+
// Si getModuleSubPath retorna null, significa que es un módulo excluido
|
|
128
|
+
// No transformar y continuar con el siguiente import
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (modulePath) {
|
|
132
|
+
newPath = modulePath;
|
|
133
|
+
transformed = true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
if (env.VERBOSE === 'true')
|
|
138
|
+
logger.warn(`Error resolviendo módulo ${moduleRequest}: ${error instanceof Error ? error.message : String(error)}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// 2. Si no es módulo externo/excluido, verificar si es un alias conocido
|
|
142
|
+
if (!transformed) {
|
|
143
|
+
for (const [alias] of Object.entries(pathAlias)) {
|
|
144
|
+
const aliasPattern = alias.replace('/*', '');
|
|
145
|
+
if (moduleRequest.startsWith(aliasPattern)) {
|
|
146
|
+
// Reemplazar el alias con la ruta del target
|
|
147
|
+
const relativePath = moduleRequest.replace(aliasPattern, '');
|
|
148
|
+
// Para alias que apuntan a la raíz (como @/* -> /src/*),
|
|
149
|
+
// solo usamos PATH_DIST + relativePath
|
|
150
|
+
let newImportPath = path.join('/', env.PATH_DIST, relativePath);
|
|
151
|
+
// Normalizar la ruta para eliminar ./ extra y separadores de Windows
|
|
152
|
+
newImportPath = newImportPath
|
|
153
|
+
.replace(/\/\.\//g, '/')
|
|
154
|
+
.replace(/\\/g, '/');
|
|
155
|
+
if (newImportPath.endsWith('.ts') ||
|
|
156
|
+
newImportPath.endsWith('.vue')) {
|
|
157
|
+
newImportPath = newImportPath.replace(/\.(ts|vue)$/, '.js');
|
|
158
|
+
}
|
|
159
|
+
else if (!/\.(js|mjs|css|json)$/.test(newImportPath)) {
|
|
160
|
+
newImportPath += '.js';
|
|
161
|
+
}
|
|
162
|
+
newPath = newImportPath;
|
|
163
|
+
transformed = true;
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// 3. Si no es alias ni módulo externo, verificar si es ruta relativa que necesita extensión .js
|
|
169
|
+
if (!transformed &&
|
|
170
|
+
(moduleRequest.startsWith('./') || moduleRequest.startsWith('../'))) {
|
|
171
|
+
let relativePath = moduleRequest;
|
|
172
|
+
if (relativePath.endsWith('.ts') || relativePath.endsWith('.vue')) {
|
|
173
|
+
relativePath = relativePath.replace(/\.(ts|vue)$/, '.js');
|
|
174
|
+
newPath = relativePath;
|
|
175
|
+
transformed = true;
|
|
176
|
+
}
|
|
177
|
+
else if (!/\.(js|mjs|css|json)$/.test(relativePath)) {
|
|
178
|
+
newPath = relativePath + '.js';
|
|
179
|
+
transformed = true;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
// 4. Reemplazar solo el path en las comillas, no toda la línea
|
|
183
|
+
if (transformed && newPath) {
|
|
184
|
+
// Buscar y reemplazar solo la parte entre comillas
|
|
185
|
+
const pathRegex = new RegExp(`(['"\`])${moduleRequest.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`, 'g');
|
|
186
|
+
resultCode = resultCode.replace(pathRegex, `$1${newPath}$1`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return resultCode;
|
|
190
|
+
}
|
|
191
|
+
async function replaceAliasImportDynamic(code, _imports, file) {
|
|
192
|
+
if (!env.PATH_ALIAS || !env.PATH_DIST) {
|
|
193
|
+
return code;
|
|
194
|
+
}
|
|
195
|
+
const pathAlias = JSON.parse(env.PATH_ALIAS);
|
|
196
|
+
const pathDist = env.PATH_DIST;
|
|
197
|
+
let resultCode = code;
|
|
198
|
+
// Regex para imports dinámicos normales con string (solo comillas simples y dobles)
|
|
199
|
+
const dynamicImportRegex = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
200
|
+
// Regex para template literals (solo backticks)
|
|
201
|
+
const templateLiteralRegex = /import\s*\(\s*`([^`]+)`\s*\)/g;
|
|
202
|
+
// Manejar imports dinámicos normales con string
|
|
203
|
+
const dynamicMatches = Array.from(resultCode.matchAll(dynamicImportRegex));
|
|
204
|
+
for (const match of dynamicMatches) {
|
|
205
|
+
const [, moduleRequest] = match;
|
|
206
|
+
if (!moduleRequest)
|
|
207
|
+
continue; // Skip if moduleRequest is undefined
|
|
208
|
+
let newPath = null;
|
|
209
|
+
let transformed = false;
|
|
210
|
+
// 1. PRIMERO: Verificar si es un módulo excluido (prioridad máxima)
|
|
211
|
+
if (!transformed && isExternalModule(moduleRequest, pathAlias)) {
|
|
212
|
+
try {
|
|
213
|
+
const modulePath = getModuleSubPath(moduleRequest, file);
|
|
214
|
+
if (modulePath === null) {
|
|
215
|
+
// Si getModuleSubPath retorna null, significa que es un módulo excluido
|
|
216
|
+
// No transformar y continuar con el siguiente import
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (modulePath) {
|
|
220
|
+
newPath = modulePath;
|
|
221
|
+
transformed = true;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
if (env.VERBOSE === 'true')
|
|
226
|
+
logger.warn(`Error resolviendo módulo dinámico ${moduleRequest}: ${error instanceof Error ? error.message : String(error)}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// 2. Si no es módulo externo/excluido, verificar si es un alias conocido
|
|
230
|
+
if (!transformed) {
|
|
231
|
+
for (const [alias] of Object.entries(pathAlias)) {
|
|
232
|
+
const aliasPattern = alias.replace('/*', '');
|
|
233
|
+
if (moduleRequest.startsWith(aliasPattern)) {
|
|
234
|
+
// Reemplazar el alias con la ruta del target
|
|
235
|
+
const relativePath = moduleRequest.replace(aliasPattern, '');
|
|
236
|
+
// Para alias que apuntan a la raíz (como @/* -> /src/*),
|
|
237
|
+
// solo usamos PATH_DIST + relativePath
|
|
238
|
+
let newImportPath = path.join('/', pathDist, relativePath);
|
|
239
|
+
// Normalizar la ruta para eliminar ./ extra y separadores de Windows
|
|
240
|
+
newImportPath = newImportPath
|
|
241
|
+
.replace(/\/\.\//g, '/')
|
|
242
|
+
.replace(/\\/g, '/');
|
|
243
|
+
if (newImportPath.endsWith('.ts') ||
|
|
244
|
+
newImportPath.endsWith('.vue')) {
|
|
245
|
+
newImportPath = newImportPath.replace(/\.(ts|vue)$/, '.js');
|
|
246
|
+
}
|
|
247
|
+
else if (!/\.(js|mjs|css|json)$/.test(newImportPath)) {
|
|
248
|
+
newImportPath += '.js';
|
|
249
|
+
}
|
|
250
|
+
newPath = newImportPath;
|
|
251
|
+
transformed = true;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// 3. Si no es alias ni módulo externo, verificar si es ruta relativa que necesita extensión .js
|
|
257
|
+
if (!transformed &&
|
|
258
|
+
(moduleRequest.startsWith('./') || moduleRequest.startsWith('../'))) {
|
|
259
|
+
let relativePath = moduleRequest;
|
|
260
|
+
if (relativePath.endsWith('.ts') || relativePath.endsWith('.vue')) {
|
|
261
|
+
relativePath = relativePath.replace(/\.(ts|vue)$/, '.js');
|
|
262
|
+
newPath = relativePath;
|
|
263
|
+
transformed = true;
|
|
264
|
+
}
|
|
265
|
+
else if (!/\.(js|mjs|css|json)$/.test(relativePath)) {
|
|
266
|
+
newPath = relativePath + '.js';
|
|
267
|
+
transformed = true;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// 4. Reemplazar solo el path en las comillas, no toda la expresión
|
|
271
|
+
if (transformed && newPath) {
|
|
272
|
+
// Buscar y reemplazar solo la parte entre comillas en import()
|
|
273
|
+
const pathRegex = new RegExp(`import\\s*\\(\\s*(['"])${moduleRequest.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1\\s*\\)`, 'g');
|
|
274
|
+
resultCode = resultCode.replace(pathRegex, `import($1${newPath}$1)`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// Manejar template literals - versión mejorada
|
|
278
|
+
resultCode = resultCode.replace(templateLiteralRegex, (match, moduleRequest) => {
|
|
279
|
+
let transformed = false;
|
|
280
|
+
let result = match;
|
|
281
|
+
// 1. PRIMERO: Verificar si es un módulo excluido (prioridad máxima)
|
|
282
|
+
if (!transformed && isExternalModule(moduleRequest, pathAlias)) {
|
|
283
|
+
try {
|
|
284
|
+
const modulePath = getModuleSubPath(moduleRequest, file);
|
|
285
|
+
if (modulePath === null) {
|
|
286
|
+
// Si getModuleSubPath retorna null, significa que es un módulo excluido
|
|
287
|
+
// No transformar y retornar el match original
|
|
288
|
+
return match;
|
|
289
|
+
}
|
|
290
|
+
if (modulePath) {
|
|
291
|
+
result = match.replace(moduleRequest, modulePath);
|
|
292
|
+
transformed = true;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
if (env.VERBOSE === 'true')
|
|
297
|
+
logger.warn(`Error resolviendo módulo template literal ${moduleRequest}: ${error instanceof Error ? error.message : String(error)}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
// 2. Verificar aliases en template literals
|
|
301
|
+
if (!transformed) {
|
|
302
|
+
for (const [alias] of Object.entries(pathAlias)) {
|
|
303
|
+
const aliasPattern = alias.replace('/*', '');
|
|
304
|
+
if (moduleRequest.includes(aliasPattern)) {
|
|
305
|
+
const relativePath = moduleRequest.replace(aliasPattern, '');
|
|
306
|
+
// Para alias que apuntan a la raíz (como @/* -> /src/*),
|
|
307
|
+
// solo usamos PATH_DIST + relativePath
|
|
308
|
+
let newModuleRequest = path.join('/', pathDist, relativePath);
|
|
309
|
+
// Normalizar la ruta para eliminar ./ extra y barras duplicadas
|
|
310
|
+
newModuleRequest = newModuleRequest
|
|
311
|
+
.replace(/\/\.\//g, '/')
|
|
312
|
+
.replace(/\/+/g, '/')
|
|
313
|
+
.replace(/\\/g, '/'); // Normalizar separadores de Windows a Unix
|
|
314
|
+
result = match.replace(moduleRequest, newModuleRequest);
|
|
315
|
+
transformed = true;
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
// 3. Si no es alias ni módulo externo, verificar si necesita transformación de extensión para rutas relativas
|
|
321
|
+
if (!transformed) {
|
|
322
|
+
// Para template literals que contienen rutas relativas, solo transformar extensiones
|
|
323
|
+
let newModuleRequest = moduleRequest;
|
|
324
|
+
if (moduleRequest.includes('./') ||
|
|
325
|
+
moduleRequest.includes('../')) {
|
|
326
|
+
// Transformar extensiones .ts y .vue a .js en template literals relativos
|
|
327
|
+
newModuleRequest = moduleRequest
|
|
328
|
+
.replace(/\.ts(\b|`)/g, '.js$1')
|
|
329
|
+
.replace(/\.vue(\b|`)/g, '.js$1');
|
|
330
|
+
if (newModuleRequest !== moduleRequest) {
|
|
331
|
+
result = match.replace(moduleRequest, newModuleRequest);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return result;
|
|
336
|
+
});
|
|
337
|
+
return resultCode;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Reemplaza alias en strings del código JavaScript (no solo en imports)
|
|
341
|
+
* Maneja casos como: link.href = 'P@/vendor/sweetalert2/sweetalert2.dark.min.css';
|
|
342
|
+
* @param code - El código JavaScript a transformar
|
|
343
|
+
* @returns El código con los alias reemplazados en strings
|
|
344
|
+
*/
|
|
345
|
+
async function replaceAliasInStrings(code) {
|
|
346
|
+
if (!env.PATH_ALIAS || !env.PATH_DIST) {
|
|
347
|
+
return code;
|
|
348
|
+
}
|
|
349
|
+
const pathAlias = JSON.parse(env.PATH_ALIAS);
|
|
350
|
+
const pathDist = env.PATH_DIST;
|
|
351
|
+
let resultCode = code; // Regex para encontrar strings que contengan posibles alias
|
|
352
|
+
// Busca strings entre comillas simples, dobles o backticks que contengan alias
|
|
353
|
+
const stringRegex = /(['"`])([^'"`]+)(['"`])/g;
|
|
354
|
+
// Crear un array para procesar todas las coincidencias
|
|
355
|
+
const matches = Array.from(resultCode.matchAll(stringRegex));
|
|
356
|
+
for (const match of matches) {
|
|
357
|
+
const [fullMatch, openQuote, stringContent, closeQuote] = match;
|
|
358
|
+
// Verificar que las comillas de apertura y cierre coincidan
|
|
359
|
+
if (openQuote !== closeQuote || !stringContent)
|
|
360
|
+
continue; // Verificar si el string contiene algún alias
|
|
361
|
+
let transformed = false;
|
|
362
|
+
let newStringContent = stringContent;
|
|
363
|
+
// Ordenar alias por longitud (más largos primero) para priorizar alias más específicos
|
|
364
|
+
const sortedAliases = Object.entries(pathAlias).sort((a, b) => {
|
|
365
|
+
const aliasA = a[0].replace('/*', '');
|
|
366
|
+
const aliasB = b[0].replace('/*', '');
|
|
367
|
+
return aliasB.length - aliasA.length;
|
|
368
|
+
});
|
|
369
|
+
for (const [alias, target] of sortedAliases) {
|
|
370
|
+
const aliasPattern = alias.replace('/*', '');
|
|
371
|
+
// Verificar coincidencia exacta del alias seguido de '/' o al final del string
|
|
372
|
+
const aliasRegex = new RegExp(`^${aliasPattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?=/|$)`);
|
|
373
|
+
if (aliasRegex.test(stringContent)) {
|
|
374
|
+
// IMPORTANTE: Verificar si es un módulo excluido antes de transformar
|
|
375
|
+
if (isExternalModule(stringContent, pathAlias)) {
|
|
376
|
+
// Para strings que parecen ser módulos externos, verificar si están excluidos
|
|
377
|
+
const EXCLUDED_MODULES = new Set([
|
|
378
|
+
'vue/compiler-sfc',
|
|
379
|
+
'vue/dist/vue.runtime.esm-bundler',
|
|
380
|
+
'@vue/compiler-sfc',
|
|
381
|
+
'@vue/compiler-dom',
|
|
382
|
+
'@vue/runtime-core',
|
|
383
|
+
'@vue/runtime-dom',
|
|
384
|
+
'oxc-parser',
|
|
385
|
+
'oxc-parser/wasm',
|
|
386
|
+
'oxc-minify',
|
|
387
|
+
'oxc-minify/browser',
|
|
388
|
+
'@oxc-parser/binding-wasm32-wasi',
|
|
389
|
+
'@oxc-minify/binding-wasm32-wasi',
|
|
390
|
+
'typescript/lib/typescript',
|
|
391
|
+
]);
|
|
392
|
+
if (EXCLUDED_MODULES.has(stringContent)) {
|
|
393
|
+
// Es un módulo excluido, no transformar
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
} // Reemplazar el alias con la ruta del target
|
|
397
|
+
const relativePath = stringContent.replace(aliasPattern, '');
|
|
398
|
+
// Construir la nueva ruta basada en la configuración del target
|
|
399
|
+
let newPath;
|
|
400
|
+
// El target puede ser un array de strings o un string
|
|
401
|
+
const targetArray = Array.isArray(target) ? target : [target];
|
|
402
|
+
const targetPath = targetArray[0];
|
|
403
|
+
// Debug logs
|
|
404
|
+
if (env.VERBOSE === 'true') {
|
|
405
|
+
console.log(`🔍 DEBUG replaceAliasInStrings:
|
|
406
|
+
- stringContent: "${stringContent}"
|
|
407
|
+
- aliasPattern: "${aliasPattern}"
|
|
408
|
+
- relativePath: "${relativePath}"
|
|
409
|
+
- targetPath: "${targetPath}"
|
|
410
|
+
- pathDist: "${pathDist}"`);
|
|
411
|
+
}
|
|
412
|
+
if (targetPath.startsWith('/')) {
|
|
413
|
+
// Si el target empieza con /, es una ruta absoluta desde la raíz del proyecto
|
|
414
|
+
// Remover /* del final si existe
|
|
415
|
+
const cleanTarget = targetPath.replace('/*', '');
|
|
416
|
+
newPath = path.join(cleanTarget, relativePath);
|
|
417
|
+
if (env.VERBOSE === 'true') {
|
|
418
|
+
console.log(` ✅ Ruta absoluta: cleanTarget="${cleanTarget}", newPath="${newPath}"`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
else {
|
|
422
|
+
// Si es una ruta relativa, verificar si ya apunta al directorio de distribución
|
|
423
|
+
const cleanTarget = targetPath
|
|
424
|
+
.replace('./', '')
|
|
425
|
+
.replace('/*', '');
|
|
426
|
+
const normalizedPathDist = pathDist.replace('./', '');
|
|
427
|
+
if (env.VERBOSE === 'true') {
|
|
428
|
+
console.log(` 🔍 Ruta relativa: cleanTarget="${cleanTarget}", normalizedPathDist="${normalizedPathDist}"`);
|
|
429
|
+
}
|
|
430
|
+
if (cleanTarget === normalizedPathDist) {
|
|
431
|
+
// Si el target es el mismo que PATH_DIST, no duplicar
|
|
432
|
+
newPath = path.join('/', normalizedPathDist, relativePath);
|
|
433
|
+
if (env.VERBOSE === 'true') {
|
|
434
|
+
console.log(` ✅ Sin duplicación: newPath="${newPath}"`);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
// Si es diferente, usar PATH_DIST como base
|
|
439
|
+
newPath = path.join('/', normalizedPathDist, cleanTarget, relativePath);
|
|
440
|
+
if (env.VERBOSE === 'true') {
|
|
441
|
+
console.log(` ✅ Con PATH_DIST: newPath="${newPath}"`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
// Normalizar la ruta para eliminar ./ extra y separadores de Windows
|
|
446
|
+
newPath = newPath
|
|
447
|
+
.replace(/\/\.\//g, '/')
|
|
448
|
+
.replace(/\\/g, '/')
|
|
449
|
+
.replace(/\/+/g, '/');
|
|
450
|
+
// Para archivos estáticos (CSS, JS, imágenes, etc.), mantener la extensión original
|
|
451
|
+
// No agregar .js automáticamente como hacemos con imports
|
|
452
|
+
newStringContent = newPath;
|
|
453
|
+
transformed = true;
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
} // Si se transformó, reemplazar en el código
|
|
457
|
+
if (transformed) {
|
|
458
|
+
const newFullMatch = `${openQuote}${newStringContent}${closeQuote}`;
|
|
459
|
+
// Usar una expresión regular más específica para evitar reemplazos accidentales
|
|
460
|
+
const escapedOriginal = fullMatch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
461
|
+
const specificRegex = new RegExp(escapedOriginal, 'g');
|
|
462
|
+
resultCode = resultCode.replace(specificRegex, newFullMatch);
|
|
463
|
+
if (env.VERBOSE === 'true') {
|
|
464
|
+
logger.info(`Alias en string transformado: ${stringContent} -> ${newStringContent}`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return resultCode;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Elimina la etiqueta "html" de una cadena de plantilla.
|
|
472
|
+
* @param {string} data - La cadena de plantilla de la cual eliminar la etiqueta "html".
|
|
473
|
+
* @returns {Promise<string>} - La cadena de plantilla modificada sin la etiqueta "html".
|
|
474
|
+
*/
|
|
475
|
+
const removehtmlOfTemplateString = async (data) => {
|
|
476
|
+
// Regex más específico que busca la etiqueta html seguida de un template literal
|
|
477
|
+
// Debe estar al inicio de línea o después de espacios/operadores, no después de punto
|
|
478
|
+
const htmlRegExp = /(?:^|[^.])html\s*`/g;
|
|
479
|
+
data = data.replace(htmlRegExp, match => {
|
|
480
|
+
// Preservar el carácter que no es punto antes de html
|
|
481
|
+
const beforeHtml = match.charAt(0) !== 'h' ? match.charAt(0) : '';
|
|
482
|
+
return beforeHtml + '`';
|
|
483
|
+
});
|
|
484
|
+
//remove ""
|
|
485
|
+
const htmlGetterRegExp = /,\s*get\s+html\(\)\s*{\s*return\s*html\s*}/g;
|
|
486
|
+
data = data.replace(htmlGetterRegExp, '');
|
|
487
|
+
return data;
|
|
488
|
+
};
|
|
489
|
+
/**
|
|
490
|
+
* Elimina los comentarios con la etiqueta @preserve de la cadena de datos proporcionada.
|
|
491
|
+
* @param {string} data - La cadena de entrada que contiene el código JavaScript.
|
|
492
|
+
* @returns {Promise<string>} - Una promesa que se resuelve con la cadena modificada sin los comentarios @preserve.
|
|
493
|
+
*/
|
|
494
|
+
const removePreserverComent = async (data) => {
|
|
495
|
+
const preserverRegExp = /\/\*[\s\S]*?@preserve[\s\S]*?\*\/|\/\/.*?@preserve.*?(?=\n|$)/g;
|
|
496
|
+
data = data.replace(preserverRegExp, (match) => match.replace(/@preserve/g, ''));
|
|
497
|
+
return data;
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* Elimina la declaración de importación para 'code-tag' de la cadena de datos proporcionada.
|
|
501
|
+
* @param {string} data - La cadena de entrada que contiene el código JavaScript.
|
|
502
|
+
* @returns {Promise<string>} - Una promesa que se resuelve con la cadena modificada sin la importación de 'code-tag'.
|
|
503
|
+
*/
|
|
504
|
+
const removeCodeTagImport = async (data) => {
|
|
505
|
+
// remove import if exist code-tag
|
|
506
|
+
const codeTagRegExp = /import\s+{.*}\s+from\s+['"].*code-tag.*['"];/g;
|
|
507
|
+
data = data.replace(codeTagRegExp, '');
|
|
508
|
+
return data;
|
|
509
|
+
};
|
|
510
|
+
export async function estandarizaCode(code, file) {
|
|
511
|
+
try {
|
|
512
|
+
const ast = await parser(file, code);
|
|
513
|
+
if (ast && ast.errors && ast.errors.length > 0) {
|
|
514
|
+
// Debug: mostrar la estructura del error para entender mejor qué información tenemos
|
|
515
|
+
if (env.VERBOSE === 'true') {
|
|
516
|
+
console.info('DEBUG - Estructura del error:', JSON.stringify(ast.errors[0], null, 2));
|
|
517
|
+
}
|
|
518
|
+
// Usar el nuevo sistema de reporte de errores
|
|
519
|
+
const detailedErrorReport = analyzeAndFormatMultipleErrors(ast.errors, code, file);
|
|
520
|
+
if (env.VERBOSE === 'true') {
|
|
521
|
+
logger.error(detailedErrorReport);
|
|
522
|
+
}
|
|
523
|
+
// También mantener el mensaje simple para el sistema existente
|
|
524
|
+
const firstError = ast.errors[0];
|
|
525
|
+
throw new Error(firstError?.message || 'Error sin mensaje');
|
|
526
|
+
}
|
|
527
|
+
code = await replaceAliasImportStatic(file, code);
|
|
528
|
+
code = await replaceAliasImportDynamic(code, ast?.module.dynamicImports, file);
|
|
529
|
+
code = await replaceAliasInStrings(code);
|
|
530
|
+
code = await removehtmlOfTemplateString(code);
|
|
531
|
+
code = await removeCodeTagImport(code);
|
|
532
|
+
if (env.isProd === 'true') {
|
|
533
|
+
code = await removePreserverComent(code);
|
|
534
|
+
}
|
|
535
|
+
return { code, error: null };
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
return {
|
|
539
|
+
code: '',
|
|
540
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
//# sourceMappingURL=transforms.js.map
|