vatts 1.2.0-test.3 → 1.2.0-test.5

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 (2) hide show
  1. package/dist/builder.js +35 -47
  2. package/package.json +1 -1
package/dist/builder.js CHANGED
@@ -36,26 +36,20 @@ const esbuild = require('rollup-plugin-esbuild').default;
36
36
  const jsonPlugin = require("@rollup/plugin-json").default;
37
37
  const { loadTsConfigPaths, resolveTsConfigAlias } = require('./tsconfigPaths');
38
38
  // --- Helper de Detecção de Framework ---
39
- // Helper para determinar o framework principal do projeto
40
39
  function detectFramework(projectDir = process.cwd()) {
41
- // 1. Tenta detectar pelo package.json (mais preciso e evita conflitos)
42
40
  try {
43
41
  const pkgPath = path.join(projectDir, 'package.json');
44
42
  if (fs.existsSync(pkgPath)) {
45
43
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
46
44
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
47
- // Prioridade explicita para React se estiver listado
48
45
  if (deps.react || deps['react-dom'])
49
46
  return 'react';
50
- // Se tiver Vue e não React, é Vue
51
47
  if (deps.vue || deps['nuxt'])
52
48
  return 'vue';
53
49
  }
54
50
  }
55
- catch (e) {
56
- // Ignora erro de leitura
57
- }
58
- return 'react'; // Default fallback
51
+ catch (e) { }
52
+ return 'react';
59
53
  }
60
54
  const tsconfigPathsPlugin = (projectDir = process.cwd()) => {
61
55
  const info = loadTsConfigPaths(projectDir);
@@ -72,7 +66,6 @@ const tsconfigPathsPlugin = (projectDir = process.cwd()) => {
72
66
  }
73
67
  };
74
68
  };
75
- // Lista de módulos nativos do Node.js
76
69
  const nodeBuiltIns = [
77
70
  'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns',
78
71
  'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode',
@@ -89,23 +82,44 @@ const markdownPlugin = () => {
89
82
  if (id.endsWith('.md')) {
90
83
  return {
91
84
  code: `export default ${JSON.stringify(code)};`,
92
- map: null // Null map economiza memória se não precisa debugar markdown
85
+ map: null
93
86
  };
94
87
  }
95
88
  }
96
89
  };
97
90
  };
91
+ /**
92
+ * [CORREÇÃO] Plugin que injeta 'export default {}' se estiver faltando.
93
+ * Resolve o problema de rotas que exportam apenas 'config' mas não o componente.
94
+ */
95
+ const vueScriptFixPlugin = () => {
96
+ return {
97
+ name: 'vatts-vue-script-fix',
98
+ transform(code, id) {
99
+ // Intercepta arquivos virtuais de script TS do Vue
100
+ if (id.includes('?vue&type=script') && id.includes('lang.ts')) {
101
+ // Se o código NÃO tem export default, a gente cria um objeto vazio
102
+ // Isso satisfaz o Rollup/Vue Plugin que espera um componente
103
+ if (!code.includes('export default')) {
104
+ return {
105
+ code: code + '\nexport default {};',
106
+ map: null // Sourcemap null pra simplificar
107
+ };
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ };
113
+ };
98
114
  /**
99
115
  * Plugin para CSS/PostCSS Manual (Otimizado para RAM)
100
116
  */
101
117
  const customPostCssPlugin = (isProduction) => {
102
118
  let cachedProcessor = null;
103
119
  let configLoaded = false;
104
- // Função auxiliar para inicializar o PostCSS apenas uma vez
105
120
  const initPostCss = async (projectDir) => {
106
121
  if (configLoaded)
107
122
  return cachedProcessor;
108
- // CRÍTICO: Garante que o Tailwind saiba que é produção para purgar CSS não usado
109
123
  process.env.NODE_ENV = isProduction ? 'production' : 'development';
110
124
  const postcssConfigPath = path.join(projectDir, 'postcss.config.js');
111
125
  const postcssConfigMjsPath = path.join(projectDir, 'postcss.config.mjs');
@@ -170,7 +184,6 @@ const customPostCssPlugin = (isProduction) => {
170
184
  return {
171
185
  name: 'custom-postcss-plugin',
172
186
  async transform(code, id) {
173
- // Intercepta arquivos CSS e requests virtuais de estilo do Vue (que terminam em .css)
174
187
  if (!id.endsWith('.css'))
175
188
  return null;
176
189
  const processor = await initPostCss(process.cwd());
@@ -180,7 +193,7 @@ const customPostCssPlugin = (isProduction) => {
180
193
  const result = await processor.process(code, {
181
194
  from: id,
182
195
  to: id,
183
- map: false // Mapas inline ou não, melhor manter simples aqui
196
+ map: false
184
197
  });
185
198
  processedCss = result.css;
186
199
  }
@@ -188,16 +201,12 @@ const customPostCssPlugin = (isProduction) => {
188
201
  Console.warn(`PostCSS process error:`, e.message);
189
202
  }
190
203
  }
191
- // Emite o arquivo CSS processado como asset
192
- // Remove query params do Vue (ex: ?vue&type=style...) para gerar um nome de arquivo limpo
193
204
  const cleanName = path.basename(id).split('?')[0];
194
205
  const referenceId = this.emitFile({
195
206
  type: 'asset',
196
207
  name: cleanName,
197
208
  source: processedCss
198
209
  });
199
- // Retorna o módulo JS que injeta o CSS via <link>
200
- // FIX: Retorna um objeto com 'code' e 'map' para evitar o aviso "Sourcemap is likely to be incorrect"
201
210
  return {
202
211
  code: `
203
212
  const cssUrl = String(import.meta.ROLLUP_FILE_URL_${referenceId});
@@ -288,19 +297,16 @@ const smartAssetPlugin = (isProduction) => {
288
297
  };
289
298
  };
290
299
  /**
291
- * Gera a configuração base do Rollup (Agora Async e Estrita)
300
+ * Gera a configuração base do Rollup
292
301
  */
293
302
  async function createRollupConfig(entryPoint, outdir, isProduction) {
294
- // Detecta Framework de forma exclusiva e robusta
295
303
  const framework = detectFramework();
296
304
  const hasVue = framework === 'vue';
297
305
  const hasReact = framework === 'react';
298
- // Define variáveis de ambiente
299
306
  const replaceValues = {
300
307
  'process.env.NODE_ENV': JSON.stringify(isProduction ? 'production' : 'development'),
301
308
  'process.env.PORT': JSON.stringify(process.vatts.port || 3000)
302
309
  };
303
- // --- LÓGICA VUE ESTRITA ---
304
310
  let vuePlugin = null;
305
311
  if (hasVue) {
306
312
  replaceValues['__VUE_OPTIONS_API__'] = JSON.stringify(true);
@@ -331,35 +337,24 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
331
337
  Console.warn("Vue detected but failed to load rollup-plugin-vue:", e.message);
332
338
  }
333
339
  }
334
- // --- CONFIGURAÇÃO DE EXTENSÕES ---
335
- // Fix: Prioriza .vue se for um projeto Vue para evitar que o NodeResolve pegue artefatos gerados (como .vue.js do Volar)
336
- // ao invés do arquivo fonte .vue.
337
340
  let extensions = ['.mjs', '.js', '.json', '.node', '.jsx', '.tsx', '.ts'];
338
341
  if (hasVue) {
339
- // Coloca .vue no INÍCIO da lista
340
342
  extensions = ['.vue', ...extensions];
341
343
  }
342
- // --- CONFIGURAÇÃO DO ESBUILD ---
343
- // SEPARAÇÃO: Regex específico para cada framework.
344
- // FIX ERRO VUE: O Regex do Vue inclui os arquivos virtuais `?vue`,
345
- // mas o loader '.vue': 'ts' foi removido para evitar conflito com o plugin do Vue.
344
+ // REGEX ESSENCIAL: Permite que o ESBuild processe os arquivos virtuais do Vue
346
345
  let esbuildInclude;
347
346
  if (hasVue) {
348
- esbuildInclude = /\.[jt]sx?$|\.vue\?vue/;
347
+ esbuildInclude = /\.[jt]sx?$|\.vue\?vue.*lang\.ts/;
349
348
  }
350
349
  else {
351
- esbuildInclude = /\.[jt]sx?$/; // React/Vanilla: ignora arquivos virtuais do Vue
350
+ esbuildInclude = /\.[jt]sx?$/;
352
351
  }
353
352
  const esbuildLoaders = {
354
353
  '.js': 'jsx',
355
354
  '.ts': 'ts',
356
355
  '.tsx': 'tsx',
357
- // RESTAURADO: .vue para ts. Isso é NECESSÁRIO para processar blocos <script lang="ts">
358
- // Se houver erros do tipo __VLS_, o plugin 'block-volar-artifacts' abaixo deve resolver.
359
356
  '.vue': 'ts'
360
357
  };
361
- // No Vue, partes do arquivo podem virar TS, mas isso é pego pela extensão do arquivo virtual,
362
- // não precisamos forçar no loader geral.
363
358
  return {
364
359
  input: entryPoint,
365
360
  external: nodeBuiltIns,
@@ -376,40 +371,33 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
376
371
  values: replaceValues
377
372
  }),
378
373
  tsconfigPathsPlugin(process.cwd()),
379
- // NOVO: Blocker agressivo para artefatos gerados pelo Volar/TS (.vue.js, .vue.d.ts)
380
- // Isso previne que o build tente empacotar arquivos temporários de tipagem como se fossem código fonte.
381
374
  {
382
375
  name: 'block-volar-artifacts',
383
376
  load(id) {
384
- // Ignora arquivos que terminam em .vue.js, .vue.ts, ou .vue.d.ts
385
- // Esses arquivos frequentemente contêm código "virtual" (__VLS_...) que causa erros em runtime.
386
377
  if (/\.vue\.(js|ts|d\.ts|map)$/.test(id)) {
387
378
  return 'export default {};';
388
379
  }
389
380
  return null;
390
381
  }
391
382
  },
392
- // NOVO: Blocker para artefatos Vue (.vue e .vue.js) em projetos React
393
- // Impede que arquivos compilados do Vue quebrem o build React
394
383
  {
395
384
  name: 'block-vue-artifacts',
396
385
  load(id) {
397
- // Verifica se não estamos no Vue e se o arquivo é um artefato Vue
398
386
  if (!hasVue && (id.endsWith('.vue') || id.endsWith('.vue.js'))) {
399
- // Retorna módulo vazio para "matar" o arquivo e impedir erros de runtime
400
387
  return 'export default {};';
401
388
  }
402
389
  return null;
403
390
  }
404
391
  },
405
392
  nodeResolve({
406
- extensions, // Agora com .vue prioritário se hasVue for true
393
+ extensions,
407
394
  preferBuiltins: true,
408
395
  browser: true,
409
396
  dedupe: hasReact ? ['react', 'react-dom'] : (hasVue ? ['vue'] : [])
410
397
  }),
411
- // CRÍTICO: Injeta plugin do Vue APENAS se for Vue e ANTES de commonjs/esbuild.
412
398
  ...(hasVue && vuePlugin ? [vuePlugin] : []),
399
+ // AQUI ESTÁ A MÁGICA: Plugin que corrige a falta do export default
400
+ ...(hasVue ? [vueScriptFixPlugin()] : []),
413
401
  commonjs({
414
402
  sourceMap: !isProduction,
415
403
  requireReturnsDefault: 'auto',
@@ -421,7 +409,7 @@ async function createRollupConfig(entryPoint, outdir, isProduction) {
421
409
  jsonPlugin(),
422
410
  esbuild({
423
411
  include: esbuildInclude,
424
- exclude: /node_modules/, // Se for React, arquivos .vue serão ignorados pelo regex do include
412
+ exclude: /node_modules/,
425
413
  sourceMap: !isProduction,
426
414
  minify: isProduction,
427
415
  legalComments: 'none',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vatts",
3
- "version": "1.2.0-test.3",
3
+ "version": "1.2.0-test.5",
4
4
  "description": "Vatts.js is a high-level framework for building web applications with ease and speed. It provides a robust set of tools and features to streamline development and enhance productivity.",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "itsmuzin",