hightjs 0.5.0 → 0.5.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.
package/src/builder.js ADDED
@@ -0,0 +1,631 @@
1
+ /*
2
+ * This file is part of the HightJS Project.
3
+ * Copyright (c) 2025 itsmuzin
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ const esbuild = require('esbuild');
18
+ const path = require('path');
19
+ const Console = require("./api/console").default
20
+ const fs = require('fs');
21
+ const {readdir, stat} = require("node:fs/promises");
22
+ const {rm} = require("fs-extra");
23
+ // Lista de módulos nativos do Node.js para marcar como externos (apenas os built-ins do Node)
24
+ const nodeBuiltIns = [
25
+ 'assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns',
26
+ 'domain', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode',
27
+ 'querystring', 'readline', 'stream', 'string_decoder', 'tls', 'tty', 'url',
28
+ 'util', 'v8', 'vm', 'zlib', 'module', 'worker_threads', 'perf_hooks'
29
+ ];
30
+
31
+ /**
32
+ * Plugin para processar CSS com PostCSS e Tailwind
33
+ */
34
+ const postcssPlugin = {
35
+ name: 'postcss-plugin',
36
+ setup(build) {
37
+ build.onLoad({ filter: /\.css$/ }, async (args) => {
38
+ const fs = require('fs');
39
+ const path = require('path');
40
+
41
+ try {
42
+ // Lê o CSS original
43
+ let css = await fs.promises.readFile(args.path, 'utf8');
44
+
45
+ // Verifica se tem PostCSS config no projeto
46
+ const projectDir = process.cwd();
47
+ const postcssConfigPath = path.join(projectDir, 'postcss.config.js');
48
+ const postcssConfigMjsPath = path.join(projectDir, 'postcss.config.mjs');
49
+
50
+ let processedCss = css;
51
+
52
+ if (fs.existsSync(postcssConfigPath) || fs.existsSync(postcssConfigMjsPath)) {
53
+ try {
54
+ // Importa PostCSS do projeto (não do SDK)
55
+ const postcssPath = path.join(projectDir, 'node_modules', 'postcss');
56
+ const postcss = require(postcssPath);
57
+
58
+ // Carrega a config do PostCSS
59
+ const configPath = fs.existsSync(postcssConfigPath) ? postcssConfigPath : postcssConfigMjsPath;
60
+ delete require.cache[require.resolve(configPath)];
61
+ const config = require(configPath);
62
+ const postcssConfig = config.default || config;
63
+
64
+ // Resolve plugins do projeto
65
+ const plugins = [];
66
+
67
+ if (postcssConfig.plugins) {
68
+ if (Array.isArray(postcssConfig.plugins)) {
69
+ // Formato array: ["@tailwindcss/postcss"]
70
+ plugins.push(...postcssConfig.plugins.map(plugin => {
71
+ if (typeof plugin === 'string') {
72
+ try {
73
+ // Tenta resolver do node_modules do projeto primeiro
74
+ return require.resolve(plugin, { paths: [projectDir] });
75
+ } catch {
76
+ // Fallback para require direto
77
+ return require(plugin);
78
+ }
79
+ }
80
+ return plugin;
81
+ }));
82
+ } else {
83
+ // Formato objeto: { tailwindcss: {}, autoprefixer: {} }
84
+ for (const [pluginName, pluginOptions] of Object.entries(postcssConfig.plugins)) {
85
+ try {
86
+ // Resolve o plugin do projeto
87
+ const resolvedPath = require.resolve(pluginName, { paths: [projectDir] });
88
+ const pluginModule = require(resolvedPath);
89
+ plugins.push(pluginModule(pluginOptions || {}));
90
+ } catch (error) {
91
+ Console.warn(`Unable to load plugin ${pluginName}:`, error.message);
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ // Processa o CSS com PostCSS
98
+ const result = await postcss(plugins)
99
+ .process(css, {
100
+ from: args.path,
101
+ to: args.path.replace(/\.css$/, '.processed.css')
102
+ });
103
+
104
+ processedCss = result.css;
105
+
106
+ } catch (postcssError) {
107
+ Console.warn(`Error processing CSS with PostCSS:`, postcssError.message);
108
+ Console.warn(`Using raw CSS without processing.`);
109
+ }
110
+ }
111
+
112
+ return {
113
+ contents: `
114
+ const css = ${JSON.stringify(processedCss)};
115
+ if (typeof document !== 'undefined') {
116
+ const style = document.createElement('style');
117
+ style.textContent = css;
118
+ document.head.appendChild(style);
119
+ }
120
+ export default css;
121
+ `,
122
+ loader: 'js'
123
+ };
124
+
125
+ } catch (error) {
126
+ Console.error(`Erro ao processar CSS ${args.path}:`, error);
127
+ return {
128
+ contents: `export default "";`,
129
+ loader: 'js'
130
+ };
131
+ }
132
+ });
133
+ }
134
+ };
135
+
136
+ /**
137
+ * Plugin para resolver dependências npm no frontend
138
+ */
139
+ const npmDependenciesPlugin = {
140
+ name: 'npm-dependencies',
141
+ setup(build) {
142
+ // Permite que dependências npm sejam bundladas (não marcadas como external)
143
+ build.onResolve({ filter: /^[^./]/ }, (args) => {
144
+ // Se for um módulo built-in do Node.js, marca como external
145
+ if (nodeBuiltIns.includes(args.path)) {
146
+ return { path: args.path, external: true };
147
+ }
148
+
149
+ // Para dependências npm (axios, lodash, react, react-dom, etc), deixa o esbuild resolver normalmente
150
+ // Isso permite que sejam bundladas no frontend
151
+ return null;
152
+ });
153
+ }
154
+ };
155
+
156
+ /**
157
+ * Plugin para garantir que React seja corretamente resolvido
158
+ */
159
+ const reactResolvePlugin = {
160
+ name: 'react-resolve',
161
+ setup(build) {
162
+ // Força o uso de uma única instância do React do projeto
163
+ build.onResolve({ filter: /^react$/ }, (args) => {
164
+ const reactPath = require.resolve('react', { paths: [process.cwd()] });
165
+ return {
166
+ path: reactPath
167
+ };
168
+ });
169
+
170
+ build.onResolve({ filter: /^react-dom$/ }, (args) => {
171
+ const reactDomPath = require.resolve('react-dom', { paths: [process.cwd()] });
172
+ return {
173
+ path: reactDomPath
174
+ };
175
+ });
176
+
177
+ build.onResolve({ filter: /^react\/jsx-runtime$/ }, (args) => {
178
+ const jsxRuntimePath = require.resolve('react/jsx-runtime', { paths: [process.cwd()] });
179
+ return {
180
+ path: jsxRuntimePath
181
+ };
182
+ });
183
+
184
+ // Também resolve react-dom/client para React 18+
185
+ build.onResolve({ filter: /^react-dom\/client$/ }, (args) => {
186
+ const clientPath = require.resolve('react-dom/client', { paths: [process.cwd()] });
187
+ return {
188
+ path: clientPath
189
+ };
190
+ });
191
+ }
192
+ };
193
+
194
+ /**
195
+ * Plugin para adicionar suporte a HMR (Hot Module Replacement)
196
+ */
197
+ const hmrPlugin = {
198
+ name: 'hmr-plugin',
199
+ setup(build) {
200
+ // Adiciona runtime de HMR para arquivos TSX/JSX
201
+ build.onLoad({ filter: /\.(tsx|jsx)$/ }, async (args) => {
202
+ // Ignora arquivos de node_modules
203
+ if (args.path.includes('node_modules')) {
204
+ return null;
205
+ }
206
+
207
+ const fs = require('fs');
208
+ const contents = await fs.promises.readFile(args.path, 'utf8');
209
+
210
+ // Adiciona código de HMR apenas em componentes de rota
211
+ if (args.path.includes('/routes/') || args.path.includes('\\routes\\')) {
212
+ const hmrCode = `
213
+ // HMR Runtime
214
+ if (typeof window !== 'undefined' && window.__HWEB_HMR__) {
215
+ const moduleId = ${JSON.stringify(args.path)};
216
+ if (!window.__HWEB_HMR_MODULES__) {
217
+ window.__HWEB_HMR_MODULES__ = new Map();
218
+ }
219
+ window.__HWEB_HMR_MODULES__.set(moduleId, module.exports);
220
+ }
221
+ `;
222
+ return {
223
+ contents: contents + '\n' + hmrCode,
224
+ loader: 'tsx'
225
+ };
226
+ }
227
+
228
+ return null;
229
+ });
230
+ }
231
+ };
232
+
233
+ /**
234
+ * Plugin para suportar importação de arquivos Markdown (.md)
235
+ */
236
+ const markdownPlugin = {
237
+ name: 'markdown-plugin',
238
+ setup(build) {
239
+ build.onLoad({ filter: /\.md$/ }, async (args) => {
240
+ const fs = require('fs');
241
+ const content = await fs.promises.readFile(args.path, 'utf8');
242
+
243
+ return {
244
+ contents: `export default ${JSON.stringify(content)};`,
245
+ loader: 'js'
246
+ };
247
+ });
248
+ }
249
+ };
250
+
251
+ /**
252
+ * Plugin para suportar importação de arquivos de imagem e outros assets
253
+ */
254
+ const assetsPlugin = {
255
+ name: 'assets-plugin',
256
+ setup(build) {
257
+ // Suporte para imagens (PNG, JPG, JPEG, GIF, SVG, WEBP, etc)
258
+ build.onLoad({ filter: /\.(png|jpe?g|gif|webp|avif|ico|bmp|tiff?)$/i }, async (args) => {
259
+ const fs = require('fs');
260
+ const buffer = await fs.promises.readFile(args.path);
261
+ const base64 = buffer.toString('base64');
262
+ const ext = path.extname(args.path).slice(1).toLowerCase();
263
+
264
+ // Mapeamento de extensões para MIME types
265
+ const mimeTypes = {
266
+ 'png': 'image/png',
267
+ 'jpg': 'image/jpeg',
268
+ 'jpeg': 'image/jpeg',
269
+ 'gif': 'image/gif',
270
+ 'webp': 'image/webp',
271
+ 'avif': 'image/avif',
272
+ 'ico': 'image/x-icon',
273
+ 'bmp': 'image/bmp',
274
+ 'tif': 'image/tiff',
275
+ 'tiff': 'image/tiff'
276
+ };
277
+
278
+ const mimeType = mimeTypes[ext] || 'application/octet-stream';
279
+
280
+ return {
281
+ contents: `export default "data:${mimeType};base64,${base64}";`,
282
+ loader: 'js'
283
+ };
284
+ });
285
+
286
+ // Suporte especial para SVG (pode ser usado como string ou data URL)
287
+ build.onLoad({ filter: /\.svg$/i }, async (args) => {
288
+ const fs = require('fs');
289
+ const content = await fs.promises.readFile(args.path, 'utf8');
290
+ const base64 = Buffer.from(content).toString('base64');
291
+
292
+ return {
293
+ contents: `
294
+ export default "data:image/svg+xml;base64,${base64}";
295
+ export const svgContent = ${JSON.stringify(content)};
296
+ `,
297
+ loader: 'js'
298
+ };
299
+ });
300
+
301
+ // Suporte para arquivos JSON
302
+ build.onLoad({ filter: /\.json$/i }, async (args) => {
303
+ const fs = require('fs');
304
+ const content = await fs.promises.readFile(args.path, 'utf8');
305
+
306
+ return {
307
+ contents: `export default ${content};`,
308
+ loader: 'js'
309
+ };
310
+ });
311
+
312
+ // Suporte para arquivos de texto (.txt)
313
+ build.onLoad({ filter: /\.txt$/i }, async (args) => {
314
+ const fs = require('fs');
315
+ const content = await fs.promises.readFile(args.path, 'utf8');
316
+
317
+ return {
318
+ contents: `export default ${JSON.stringify(content)};`,
319
+ loader: 'js'
320
+ };
321
+ });
322
+
323
+ // Suporte para arquivos de fonte (WOFF, WOFF2, TTF, OTF, EOT)
324
+ build.onLoad({ filter: /\.(woff2?|ttf|otf|eot)$/i }, async (args) => {
325
+ const fs = require('fs');
326
+ const buffer = await fs.promises.readFile(args.path);
327
+ const base64 = buffer.toString('base64');
328
+ const ext = path.extname(args.path).slice(1).toLowerCase();
329
+
330
+ const mimeTypes = {
331
+ 'woff': 'font/woff',
332
+ 'woff2': 'font/woff2',
333
+ 'ttf': 'font/ttf',
334
+ 'otf': 'font/otf',
335
+ 'eot': 'application/vnd.ms-fontobject'
336
+ };
337
+
338
+ const mimeType = mimeTypes[ext] || 'application/octet-stream';
339
+
340
+ return {
341
+ contents: `export default "data:${mimeType};base64,${base64}";`,
342
+ loader: 'js'
343
+ };
344
+ });
345
+
346
+ // Suporte para arquivos de áudio (MP3, WAV, OGG, etc)
347
+ build.onLoad({ filter: /\.(mp3|wav|ogg|m4a|aac|flac)$/i }, async (args) => {
348
+ const fs = require('fs');
349
+ const buffer = await fs.promises.readFile(args.path);
350
+ const base64 = buffer.toString('base64');
351
+ const ext = path.extname(args.path).slice(1).toLowerCase();
352
+
353
+ const mimeTypes = {
354
+ 'mp3': 'audio/mpeg',
355
+ 'wav': 'audio/wav',
356
+ 'ogg': 'audio/ogg',
357
+ 'm4a': 'audio/mp4',
358
+ 'aac': 'audio/aac',
359
+ 'flac': 'audio/flac'
360
+ };
361
+
362
+ const mimeType = mimeTypes[ext] || 'audio/mpeg';
363
+
364
+ return {
365
+ contents: `export default "data:${mimeType};base64,${base64}";`,
366
+ loader: 'js'
367
+ };
368
+ });
369
+
370
+ // Suporte para arquivos de vídeo (MP4, WEBM, OGV)
371
+ build.onLoad({ filter: /\.(mp4|webm|ogv)$/i }, async (args) => {
372
+ const fs = require('fs');
373
+ const buffer = await fs.promises.readFile(args.path);
374
+ const base64 = buffer.toString('base64');
375
+ const ext = path.extname(args.path).slice(1).toLowerCase();
376
+
377
+ const mimeTypes = {
378
+ 'mp4': 'video/mp4',
379
+ 'webm': 'video/webm',
380
+ 'ogv': 'video/ogg'
381
+ };
382
+
383
+ const mimeType = mimeTypes[ext] || 'video/mp4';
384
+
385
+ return {
386
+ contents: `export default "data:${mimeType};base64,${base64}";`,
387
+ loader: 'js'
388
+ };
389
+ });
390
+ }
391
+ };
392
+
393
+ /**
394
+ * Builds with code splitting into multiple chunks based on module types.
395
+ * @param {string} entryPoint - The path to the entry file.
396
+ * @param {string} outdir - The directory for output files.
397
+ * @param {boolean} isProduction - Se está em modo produção ou não.
398
+ * @returns {Promise<void>}
399
+ */
400
+ async function buildWithChunks(entryPoint, outdir, isProduction = false) {
401
+ // limpar diretorio, menos a pasta temp
402
+ await cleanDirectoryExcept(outdir, 'temp');
403
+
404
+ try {
405
+ await esbuild.build({
406
+ entryPoints: [entryPoint],
407
+ bundle: true,
408
+ minify: isProduction,
409
+ sourcemap: !isProduction,
410
+ platform: 'browser',
411
+ outdir: outdir,
412
+ loader: { '.js': 'jsx', '.ts': 'tsx' },
413
+ external: nodeBuiltIns,
414
+ plugins: [postcssPlugin, npmDependenciesPlugin, reactResolvePlugin, markdownPlugin, assetsPlugin],
415
+ format: 'esm', // ESM suporta melhor o code splitting
416
+ jsx: 'automatic',
417
+ define: {
418
+ 'process.env.NODE_ENV': isProduction ? '"production"' : '"development"'
419
+ },
420
+ conditions: ['development'],
421
+ mainFields: ['browser', 'module', 'main'],
422
+ resolveExtensions: ['.tsx', '.ts', '.jsx', '.js'],
423
+ splitting: true,
424
+ chunkNames: 'chunks/[name]-[hash]',
425
+ // Força o nome do entry para main(.js) ou main-[hash].js em prod
426
+ entryNames: isProduction ? 'main-[hash]' : 'main',
427
+ keepNames: true,
428
+ treeShaking: true,
429
+ });
430
+
431
+ } catch (error) {
432
+ console.error('An error occurred while building:', error);
433
+ process.exit(1);
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Watches with code splitting enabled
439
+ * @param {string} entryPoint - The path to the entry file.
440
+ * @param {string} outdir - The directory for output files.
441
+ * @param {Object} hotReloadManager - Manager de hot reload (opcional).
442
+ * @returns {Promise<void>}
443
+ */
444
+ async function watchWithChunks(entryPoint, outdir, hotReloadManager = null) {
445
+ // limpar diretorio
446
+ await cleanDirectoryExcept(outdir, 'temp');
447
+ try {
448
+ // Plugin para notificar quando o build termina
449
+ const buildCompletePlugin = {
450
+ name: 'build-complete',
451
+ setup(build) {
452
+ let isFirstBuild = true;
453
+ build.onEnd((result) => {
454
+ if (hotReloadManager) {
455
+ if (isFirstBuild) {
456
+ isFirstBuild = false;
457
+ hotReloadManager.onBuildComplete(true);
458
+ } else {
459
+ // Notifica o hot reload manager que o build foi concluído
460
+ hotReloadManager.onBuildComplete(result.errors.length === 0);
461
+ }
462
+ }
463
+ });
464
+ }
465
+ };
466
+
467
+ const context = await esbuild.context({
468
+ entryPoints: [entryPoint],
469
+ bundle: true,
470
+ minify: false,
471
+ sourcemap: true,
472
+ platform: 'browser',
473
+ outdir: outdir,
474
+ loader: { '.js': 'jsx', '.ts': 'tsx' },
475
+ external: nodeBuiltIns,
476
+ plugins: [postcssPlugin, npmDependenciesPlugin, reactResolvePlugin, hmrPlugin, buildCompletePlugin, markdownPlugin, assetsPlugin],
477
+ format: 'esm',
478
+ jsx: 'automatic',
479
+ define: {
480
+ 'process.env.NODE_ENV': '"development"'
481
+ },
482
+ conditions: ['development'],
483
+ mainFields: ['browser', 'module', 'main'],
484
+ resolveExtensions: ['.tsx', '.ts', '.jsx', '.js'],
485
+ splitting: true,
486
+ chunkNames: 'chunks/[name]-[hash]',
487
+ entryNames: 'main',
488
+ keepNames: true,
489
+ treeShaking: true,
490
+ });
491
+
492
+ await context.watch();
493
+ } catch (error) {
494
+ console.error(error)
495
+ Console.error('Error starting watch mode with chunks:', error);
496
+ throw error;
497
+ }
498
+ }
499
+
500
+ /**
501
+ * Builds a single entry point into a single output file.
502
+ * @param {string} entryPoint - The path to the entry file.
503
+ * @param {string} outfile - The full path to the output file.
504
+ * @param {boolean} isProduction - Se está em modo produção ou não.
505
+ * @returns {Promise<void>}
506
+ */
507
+ async function build(entryPoint, outfile, isProduction = false) {
508
+ // limpar diretorio do outfile
509
+ const outdir = path.dirname(outfile);
510
+ await cleanDirectoryExcept(outdir, 'temp');
511
+
512
+ try {
513
+ await esbuild.build({
514
+ entryPoints: [entryPoint],
515
+ bundle: true,
516
+ minify: isProduction,
517
+ sourcemap: !isProduction, // Só gera sourcemap em dev
518
+ platform: 'browser',
519
+ outfile: outfile,
520
+ loader: { '.js': 'jsx', '.ts': 'tsx' },
521
+ external: nodeBuiltIns,
522
+ plugins: [postcssPlugin, npmDependenciesPlugin, reactResolvePlugin, markdownPlugin, assetsPlugin],
523
+ format: 'iife',
524
+ globalName: 'HwebApp',
525
+ jsx: 'automatic',
526
+ define: {
527
+ 'process.env.NODE_ENV': isProduction ? '"production"' : '"development"'
528
+ },
529
+ // Configurações específicas para React 19
530
+ conditions: ['development'],
531
+ mainFields: ['browser', 'module', 'main'],
532
+ resolveExtensions: ['.tsx', '.ts', '.jsx', '.js'],
533
+ // Garante que não há duplicação de dependências
534
+ splitting: false,
535
+ // Preserva nomes de funções e comportamento
536
+ keepNames: true,
537
+ // Remove otimizações que podem causar problemas com hooks
538
+ treeShaking: true,
539
+ drop: [], // Não remove nada automaticamente
540
+ });
541
+
542
+ } catch (error) {
543
+ console.error('An error occurred during build:', error);
544
+ process.exit(1);
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Watches an entry point and its dependencies, rebuilding to a single output file.
550
+ * @param {string} entryPoint - The path to the entry file.
551
+ * @param {string} outfile - The full path to the output file.
552
+ * @param {Object} hotReloadManager - Manager de hot reload (opcional).
553
+ * @returns {Promise<void>}
554
+ */
555
+ async function watch(entryPoint, outfile, hotReloadManager = null) {
556
+ try {
557
+ // Plugin para notificar quando o build termina
558
+ const buildCompletePlugin = {
559
+ name: 'build-complete',
560
+ setup(build) {
561
+ let isFirstBuild = true;
562
+ build.onEnd((result) => {
563
+ if (hotReloadManager) {
564
+ if (isFirstBuild) {
565
+ isFirstBuild = false;
566
+ hotReloadManager.onBuildComplete(true);
567
+ } else {
568
+ // Notifica o hot reload manager que o build foi concluído
569
+ hotReloadManager.onBuildComplete(result.errors.length === 0);
570
+ }
571
+ }
572
+ });
573
+ }
574
+ };
575
+
576
+ const context = await esbuild.context({
577
+ entryPoints: [entryPoint],
578
+ bundle: true,
579
+ minify: false,
580
+ sourcemap: true,
581
+ platform: 'browser',
582
+ outfile: outfile,
583
+ loader: { '.js': 'jsx', '.ts': 'tsx' },
584
+ external: nodeBuiltIns,
585
+ format: 'iife',
586
+ globalName: 'HwebApp',
587
+ jsx: 'automatic',
588
+ define: {
589
+ 'process.env.NODE_ENV': '"development"'
590
+ },
591
+ // Configurações específicas para React 19 (mesmo que no build)
592
+ conditions: ['development'],
593
+ mainFields: ['browser', 'module', 'main'],
594
+ resolveExtensions: ['.tsx', '.ts', '.jsx', '.js'],
595
+ // Garante que não há duplicação de dependências
596
+ splitting: false,
597
+ // Preserva nomes de funções e comportamento
598
+ keepNames: true,
599
+ // Remove otimizações que podem causar problemas com hooks
600
+ treeShaking: true,
601
+ });
602
+
603
+ // Configura o watcher do esbuild
604
+ await context.watch();
605
+ } catch (error) {
606
+ Console.error('Error starting watch mode:', error);
607
+ throw error;
608
+ }
609
+ }
610
+ /**
611
+ * Remove todo o conteúdo de um diretório,
612
+ * exceto a pasta (ou pastas) especificada(s) em excludeFolder.
613
+ *
614
+ * @param {string} dirPath - Caminho do diretório a limpar
615
+ * @param {string|string[]} excludeFolder - Nome ou nomes das pastas a manter
616
+ */
617
+ async function cleanDirectoryExcept(dirPath, excludeFolder) {
618
+ const excludes = Array.isArray(excludeFolder) ? excludeFolder : [excludeFolder];
619
+
620
+ const items = await readdir(dirPath);
621
+
622
+ for (const item of items) {
623
+ if (excludes.includes(item)) continue; // pula as pastas excluídas
624
+
625
+ const itemPath = path.join(dirPath, item);
626
+ const info = await stat(itemPath);
627
+
628
+ await rm(itemPath, { recursive: info.isDirectory(), force: true });
629
+ }
630
+ }
631
+ module.exports = { build, watch, buildWithChunks, watchWithChunks };