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/index.ts ADDED
@@ -0,0 +1,557 @@
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
+
18
+ import path from 'path';
19
+ import fs from 'fs';
20
+ import {ExpressAdapter} from './adapters/express';
21
+ import {build, buildWithChunks, watch, watchWithChunks} from './builder';
22
+ import {
23
+ BackendHandler,
24
+ BackendRouteConfig,
25
+ HightJSOptions,
26
+ HightMiddleware,
27
+ RequestHandler,
28
+ RouteConfig
29
+ } from './types';
30
+ import {
31
+ findMatchingBackendRoute,
32
+ findMatchingRoute,
33
+ getLayout,
34
+ getNotFound,
35
+ loadBackendRoutes,
36
+ loadLayout,
37
+ loadNotFound,
38
+ loadRoutes,
39
+ processWebSocketRoutes,
40
+ setupWebSocketUpgrade
41
+ } from './router';
42
+ import {render} from './renderer';
43
+ import {HightJSRequest, HightJSResponse} from './api/http';
44
+ import {HotReloadManager} from './hotReload';
45
+ import {FrameworkAdapterFactory} from './adapters/factory';
46
+ import {GenericRequest, GenericResponse} from './types/framework';
47
+ import Console, {Colors} from "./api/console"
48
+
49
+ // Exporta apenas os tipos e classes para o backend
50
+ export { HightJSRequest, HightJSResponse };
51
+ export type { BackendRouteConfig, BackendHandler };
52
+
53
+ // Exporta os adapters para uso manual se necessário
54
+ export { ExpressAdapter } from './adapters/express';
55
+ export { FastifyAdapter } from './adapters/fastify';
56
+ export { FrameworkAdapterFactory } from './adapters/factory';
57
+ export type { GenericRequest, GenericResponse, CookieOptions } from './types/framework';
58
+
59
+ // Exporta os helpers para facilitar integração
60
+ export { app } from './helpers';
61
+
62
+ // Exporta o sistema de WebSocket
63
+ export type { WebSocketContext, WebSocketHandler } from './types';
64
+
65
+ // Exporta os tipos de configuração
66
+ export type { HightConfig, HightConfigFunction } from './types';
67
+
68
+ // Função para verificar se o projeto é grande o suficiente para se beneficiar de chunks
69
+ function isLargeProject(projectDir: string): boolean {
70
+ try {
71
+ const srcDir = path.join(projectDir, 'src');
72
+ if (!fs.existsSync(srcDir)) return false;
73
+
74
+ let totalFiles = 0;
75
+ let totalSize = 0;
76
+
77
+ function scanDirectory(dir: string) {
78
+ const items = fs.readdirSync(dir, { withFileTypes: true });
79
+
80
+ for (const item of items) {
81
+ const fullPath = path.join(dir, item.name);
82
+
83
+ if (item.isDirectory() && item.name !== 'node_modules' && item.name !== '.git') {
84
+ scanDirectory(fullPath);
85
+ } else if (item.isFile() && /\.(tsx?|jsx?|css|scss|less)$/i.test(item.name)) {
86
+ totalFiles++;
87
+ totalSize += fs.statSync(fullPath).size;
88
+ }
89
+ }
90
+ }
91
+
92
+ scanDirectory(srcDir);
93
+
94
+ // Considera projeto grande se:
95
+ // - Mais de 20 arquivos de frontend/style
96
+ // - Ou tamanho total > 500KB
97
+ return totalFiles > 20 || totalSize > 500 * 1024;
98
+ } catch (error) {
99
+ // Em caso de erro, assume que não é um projeto grande
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // Função para gerar o arquivo de entrada para o esbuild
105
+ function createEntryFile(projectDir: string, routes: (RouteConfig & { componentPath: string })[]): string {
106
+ try {
107
+ const tempDir = path.join(projectDir, '.hight', 'temp');
108
+
109
+ fs.mkdirSync(tempDir, { recursive: true });
110
+
111
+ const entryFilePath = path.join(tempDir, 'entry.client.js');
112
+ // Verifica se há layout
113
+ const layout = getLayout();
114
+
115
+ // Verifica se há notFound personalizado
116
+ const notFound = getNotFound();
117
+
118
+ // Gera imports dinâmicos para cada componente
119
+ const imports = routes
120
+ .map((route, index) => {
121
+ const relativePath = path.relative(tempDir, route.componentPath).replace(/\\/g, '/');
122
+ return `import route${index} from '${relativePath}';`;
123
+ })
124
+ .join('\n');
125
+
126
+ // Import do layout se existir
127
+ const layoutImport = layout
128
+ ? `import LayoutComponent from '${path.relative(tempDir, layout.componentPath).replace(/\\/g, '/')}';`
129
+ : '';
130
+
131
+ // Import do notFound se existir
132
+ const notFoundImport = notFound
133
+ ? `import NotFoundComponent from '${path.relative(tempDir, notFound.componentPath).replace(/\\/g, '/')}';`
134
+ : '';
135
+
136
+ // Registra os componentes no window para o cliente acessar
137
+ const componentRegistration = routes
138
+ .map((route, index) => ` '${route.componentPath}': route${index}.component || route${index}.default?.component,`)
139
+ .join('\n');
140
+
141
+ // Registra o layout se existir
142
+ const layoutRegistration = layout
143
+ ? `window.__HWEB_LAYOUT__ = LayoutComponent.default || LayoutComponent;`
144
+ : `window.__HWEB_LAYOUT__ = null;`;
145
+
146
+ // Registra o notFound se existir
147
+ const notFoundRegistration = notFound
148
+ ? `window.__HWEB_NOT_FOUND__ = NotFoundComponent.default || NotFoundComponent;`
149
+ : `window.__HWEB_NOT_FOUND__ = null;`;
150
+
151
+ // Caminho correto para o entry.client.tsx
152
+ const sdkDir = path.dirname(__dirname); // Vai para a pasta pai de src (onde está o hweb-sdk)
153
+ const entryClientPath = path.join(sdkDir, 'src', 'client', 'entry.client.tsx');
154
+ const relativeEntryPath = path.relative(tempDir, entryClientPath).replace(/\\/g, '/');
155
+
156
+ // Import do DefaultNotFound do SDK
157
+ const defaultNotFoundPath = path.join(sdkDir, 'src', 'client', 'DefaultNotFound.tsx');
158
+ const relativeDefaultNotFoundPath = path.relative(tempDir, defaultNotFoundPath).replace(/\\/g, '/');
159
+
160
+ const entryContent = `// Arquivo gerado automaticamente pelo hweb
161
+ ${imports}
162
+ ${layoutImport}
163
+ ${notFoundImport}
164
+ import DefaultNotFound from '${relativeDefaultNotFoundPath}';
165
+
166
+ // Registra os componentes para o cliente
167
+ window.__HWEB_COMPONENTS__ = {
168
+ ${componentRegistration}
169
+ };
170
+
171
+ // Registra o layout se existir
172
+ ${layoutRegistration}
173
+
174
+ // Registra o notFound se existir
175
+ ${notFoundRegistration}
176
+
177
+ // Registra o DefaultNotFound do hweb
178
+ window.__HWEB_DEFAULT_NOT_FOUND__ = DefaultNotFound;
179
+
180
+ // Importa e executa o entry.client.tsx
181
+ import '${relativeEntryPath}';
182
+ `;
183
+
184
+ try {
185
+ fs.writeFileSync(entryFilePath, entryContent);
186
+ } catch (e) {
187
+ console.error("sdfijnsdfnijfsdijnfsdnijsdfnijfsdnijfsdnijfsdn", e)
188
+ }
189
+
190
+ return entryFilePath;
191
+ }catch (e){
192
+ Console.error("Error creating entry file:", e);
193
+ throw e;
194
+ }
195
+ }
196
+
197
+ export default function hweb(options: HightJSOptions) {
198
+ const { dev = true, dir = process.cwd(), port = 3000 } = options;
199
+ // @ts-ignore
200
+ process.hight = options;
201
+ const userWebDir = path.join(dir, 'src', 'web');
202
+ const userWebRoutesDir = path.join(userWebDir, 'routes');
203
+ const userBackendRoutesDir = path.join(dir, 'src', 'backend', 'routes');
204
+
205
+ /**
206
+ * Executa middlewares sequencialmente e depois o handler final
207
+ * @param middlewares Array de middlewares para executar
208
+ * @param finalHandler Handler final da rota
209
+ * @param request Requisição do HightJS
210
+ * @param params Parâmetros da rota
211
+ * @returns Resposta do middleware ou handler final
212
+ */
213
+ async function executeMiddlewareChain(
214
+ middlewares: HightMiddleware[] | undefined,
215
+ finalHandler: BackendHandler,
216
+ request: HightJSRequest,
217
+ params: { [key: string]: string }
218
+ ): Promise<HightJSResponse> {
219
+ if (!middlewares || middlewares.length === 0) {
220
+ // Não há middlewares, executa diretamente o handler final
221
+ return await finalHandler(request, params);
222
+ }
223
+
224
+ let currentIndex = 0;
225
+
226
+ // Função next que será chamada pelos middlewares
227
+ const next = async (): Promise<HightJSResponse> => {
228
+ if (currentIndex < middlewares.length) {
229
+ // Ainda há middlewares para executar
230
+ const currentMiddleware = middlewares[currentIndex];
231
+ currentIndex++;
232
+ return await currentMiddleware(request, params, next);
233
+ } else {
234
+ // Todos os middlewares foram executados, chama o handler final
235
+ return await finalHandler(request, params);
236
+ }
237
+ };
238
+
239
+ // Inicia a cadeia de execução
240
+ return await next();
241
+ }
242
+
243
+ let frontendRoutes: (RouteConfig & { componentPath: string })[] = [];
244
+ let hotReloadManager: HotReloadManager | null = null;
245
+ let entryPoint: string;
246
+ let outfile: string;
247
+
248
+ // Função para regenerar o entry file
249
+ const regenerateEntryFile = () => {
250
+ // Recarrega todas as rotas e componentes
251
+ frontendRoutes = loadRoutes(userWebRoutesDir);
252
+ loadLayout(userWebDir);
253
+ loadNotFound(userWebDir);
254
+
255
+ // Regenera o entry file
256
+ entryPoint = createEntryFile(dir, frontendRoutes);
257
+ };
258
+
259
+ return {
260
+ prepare: async () => {
261
+ const isProduction = !dev;
262
+
263
+ if (!isProduction) {
264
+ // Inicia hot reload apenas em desenvolvimento (com suporte ao main)
265
+ hotReloadManager = new HotReloadManager(dir);
266
+ await hotReloadManager.start();
267
+
268
+ // Adiciona callback para recarregar TUDO quando qualquer arquivo mudar
269
+ hotReloadManager.onBackendApiChange(() => {
270
+
271
+
272
+ loadBackendRoutes(userBackendRoutesDir);
273
+ processWebSocketRoutes(); // Processa rotas WS após recarregar backend
274
+ });
275
+
276
+ // Adiciona callback para regenerar entry file quando frontend mudar
277
+ hotReloadManager.onFrontendChange(() => {
278
+ regenerateEntryFile();
279
+ });
280
+ }
281
+ const now = Date.now();
282
+ const timee = Console.dynamicLine(` ${Colors.BgYellow} router ${Colors.Reset} Loading routes and components`);
283
+ const spinnerFrames1 = ['|', '/', '-', '\\'];
284
+ let frameIndex1 = 0;
285
+
286
+ const spinner1 = setInterval(() => {
287
+ timee.update(` ${Colors.FgYellow}${spinnerFrames1[frameIndex1]}${Colors.Reset} Loading routes and components...`);
288
+ frameIndex1 = (frameIndex1 + 1) % spinnerFrames1.length;
289
+ }, 100); // muda a cada 100ms
290
+ // ORDEM IMPORTANTE: Carrega TUDO antes de criar o arquivo de entrada
291
+ frontendRoutes = loadRoutes(userWebRoutesDir);
292
+ loadBackendRoutes(userBackendRoutesDir);
293
+
294
+ // Processa rotas WebSocket após carregar backend
295
+ processWebSocketRoutes();
296
+
297
+ // Carrega layout.tsx ANTES de criar o entry file
298
+ const layout = loadLayout(userWebDir);
299
+
300
+ const notFound = loadNotFound(userWebDir);
301
+
302
+ const outDir = path.join(dir, '.hight');
303
+ fs.mkdirSync(outDir, {recursive: true});
304
+
305
+ entryPoint = createEntryFile(dir, frontendRoutes);
306
+ clearInterval(spinner1)
307
+ timee.end(` ${Colors.BgGreen} router ${Colors.Reset} Routes and components loaded in ${Date.now() - now}ms`);
308
+
309
+
310
+ if (isProduction) {
311
+ const time = Console.dynamicLine(` ${Colors.BgYellow} build ${Colors.Reset} Starting client build`);
312
+
313
+ // Spinner
314
+ const spinnerFrames = ['|', '/', '-', '\\'];
315
+ let frameIndex = 0;
316
+
317
+ const spinner = setInterval(() => {
318
+ time.update(` ${Colors.FgYellow}${spinnerFrames[frameIndex]}${Colors.Reset} Building...`);
319
+ frameIndex = (frameIndex + 1) % spinnerFrames.length;
320
+ }, 100); // muda a cada 100ms
321
+
322
+ const now = Date.now();
323
+ await buildWithChunks(entryPoint, outDir, isProduction);
324
+ const elapsed = Date.now() - now;
325
+
326
+ clearInterval(spinner); // para o spinner
327
+ time.update(""); // limpa a linha
328
+ time.end(` ${Colors.BgGreen} build ${Colors.Reset} Client build completed in ${elapsed}ms`);
329
+
330
+ // Notifica o hot reload manager que o build foi concluído
331
+ if (hotReloadManager) {
332
+ hotReloadManager.onBuildComplete(true);
333
+ }
334
+
335
+ } else {
336
+ const time = Console.dynamicLine(` ${Colors.BgYellow} watcher ${Colors.Reset} Starting client watch`);
337
+ watchWithChunks(entryPoint, outDir, hotReloadManager!).catch(err => {
338
+ Console.error(`Error starting watch`, err);
339
+ });
340
+ time.end(` ${Colors.BgGreen} watcher ${Colors.Reset} Client Watch started`);
341
+ }
342
+
343
+ },
344
+
345
+ executeInstrumentation: () => {
346
+
347
+ // verificar se dir/src/instrumentation.(tsx/jsx/js/ts) existe com regex
348
+ const instrumentationFile = fs.readdirSync(path.join(dir, 'src')).find(file => /^hightweb\.(tsx|jsx|js|ts)$/.test(file));
349
+ if (instrumentationFile) {
350
+ const instrumentationPath = path.join(dir, 'src', instrumentationFile);
351
+ // dar require, e executar a função principal do arquivo
352
+ const instrumentation = require(instrumentationPath);
353
+
354
+ // Registra o listener de hot reload se existir
355
+ if (instrumentation.hotReloadListener && typeof instrumentation.hotReloadListener === 'function') {
356
+ if (hotReloadManager) {
357
+ hotReloadManager.setHotReloadListener(instrumentation.hotReloadListener);
358
+ }
359
+ }
360
+
361
+ if (typeof instrumentation === 'function') {
362
+ instrumentation();
363
+ } else if (typeof instrumentation.default === 'function') {
364
+ instrumentation.default();
365
+ } else {
366
+ Console.warn(`The instrumentation file ${instrumentationFile} does not export a default function.`);
367
+ }
368
+ }
369
+ },
370
+ getRequestHandler: (): RequestHandler => {
371
+ return async (req: any, res: any) => {
372
+ // Detecta automaticamente o framework e cria o adapter apropriado
373
+ const adapter = FrameworkAdapterFactory.detectFramework(req, res);
374
+ const genericReq = adapter.parseRequest(req);
375
+ const genericRes = adapter.createResponse(res);
376
+
377
+ // Adiciona informações do hweb na requisição genérica
378
+ (genericReq as any).hwebDev = dev;
379
+ (genericReq as any).hotReloadManager = hotReloadManager;
380
+
381
+ const {pathname} = new URL(genericReq.url, `http://${genericReq.headers.host || 'localhost'}`);
382
+ const method = genericReq.method.toUpperCase();
383
+
384
+ // 1. Verifica se é WebSocket upgrade para hot reload
385
+ if (pathname === '/hweb-hotreload/' && genericReq.headers.upgrade === 'websocket' && hotReloadManager) {
386
+ // Framework vai chamar o evento 'upgrade' do servidor HTTP
387
+ return;
388
+ }
389
+
390
+ // 2. Primeiro verifica se é um arquivo estático da pasta public
391
+ if (pathname !== '/' && !pathname.startsWith('/api/') && !pathname.startsWith('/.hight')) {
392
+ const publicDir = path.join(dir, 'public');
393
+ const filePath = path.join(publicDir, pathname);
394
+
395
+ if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
396
+ const ext = path.extname(filePath).toLowerCase();
397
+ const contentTypes: Record<string, string> = {
398
+ '.html': 'text/html',
399
+ '.css': 'text/css',
400
+ '.js': 'application/javascript',
401
+ '.json': 'application/json',
402
+ '.png': 'image/png',
403
+ '.jpg': 'image/jpeg',
404
+ '.jpeg': 'image/jpeg',
405
+ '.gif': 'image/gif',
406
+ '.svg': 'image/svg+xml',
407
+ '.ico': 'image/x-icon',
408
+ '.webp': 'image/webp',
409
+ '.mp4': 'video/mp4',
410
+ '.webm': 'video/webm',
411
+ '.mp3': 'audio/mpeg',
412
+ '.wav': 'audio/wav',
413
+ '.pdf': 'application/pdf',
414
+ '.txt': 'text/plain',
415
+ '.xml': 'application/xml',
416
+ '.zip': 'application/zip'
417
+ };
418
+
419
+ genericRes.header('Content-Type', contentTypes[ext] || 'application/octet-stream');
420
+
421
+ // Para arquivos estáticos, usamos o método nativo do framework
422
+ if (adapter.type === 'express') {
423
+ (res as any).sendFile(filePath);
424
+ } else if (adapter.type === 'fastify') {
425
+ const fileContent = fs.readFileSync(filePath);
426
+ genericRes.send(fileContent);
427
+ } else if (adapter.type === 'native') {
428
+ const fileContent = fs.readFileSync(filePath);
429
+ genericRes.send(fileContent);
430
+ }
431
+ return;
432
+ }
433
+ }
434
+
435
+ // 3. Verifica se é um arquivo estático do .hight
436
+ if (pathname.startsWith('/_hight/')) {
437
+
438
+ const staticPath = path.join(dir, '.hight');
439
+ const filePath = path.join(staticPath, pathname.replace('/_hight/', ''));
440
+
441
+ if (fs.existsSync(filePath)) {
442
+
443
+ const ext = path.extname(filePath).toLowerCase();
444
+ const contentTypes: Record<string, string> = {
445
+ '.js': 'application/javascript',
446
+ '.css': 'text/css',
447
+ '.map': 'application/json'
448
+ };
449
+
450
+ genericRes.header('Content-Type', contentTypes[ext] || 'text/plain');
451
+
452
+ // Para arquivos estáticos, usamos o método nativo do framework
453
+ if (adapter.type === 'express') {
454
+ (res as any).sendFile(filePath);
455
+ } else if (adapter.type === 'fastify') {
456
+ const fileContent = fs.readFileSync(filePath);
457
+ genericRes.send(fileContent);
458
+ } else if (adapter.type === 'native') {
459
+ const fileContent = fs.readFileSync(filePath);
460
+ genericRes.send(fileContent);
461
+ }
462
+ return;
463
+ }
464
+ }
465
+
466
+ // 4. REMOVIDO: Verificação de arquivos React UMD - não precisamos mais
467
+ // O React agora será bundlado diretamente no main.js
468
+
469
+ // 5. Verifica se é uma rota de API (backend)
470
+ const backendMatch = findMatchingBackendRoute(pathname, method);
471
+ if (backendMatch) {
472
+ try {
473
+ const handler = backendMatch.route[method as keyof BackendRouteConfig] as BackendHandler;
474
+ if (handler) {
475
+ const hwebReq = new HightJSRequest(genericReq);
476
+
477
+ // Executa middlewares e depois o handler final
478
+ const hwebRes = await executeMiddlewareChain(
479
+ backendMatch.route.middleware,
480
+ handler,
481
+ hwebReq,
482
+ backendMatch.params
483
+ );
484
+
485
+ // Aplica a resposta usando o adapter correto
486
+ hwebRes._applyTo(genericRes);
487
+ return;
488
+ }
489
+ } catch (error) {
490
+ Console.error(`API route error ${pathname}:`, error);
491
+ genericRes.status(500).text('Internal server error in API');
492
+ return;
493
+ }
494
+ }
495
+
496
+ // 6. Por último, tenta renderizar uma página (frontend) ou 404
497
+ const pageMatch = findMatchingRoute(pathname);
498
+
499
+ if (!pageMatch) {
500
+ // Em vez de enviar texto simples, renderiza a página 404 React
501
+ try {
502
+ // Cria uma "rota falsa" para a página 404
503
+ const notFoundRoute = {
504
+ pattern: '/__404__',
505
+ component: () => null, // Componente vazio, será tratado no cliente
506
+ componentPath: '__404__'
507
+ };
508
+
509
+ const html = await render({
510
+ req: genericReq,
511
+ route: notFoundRoute,
512
+ params: {},
513
+ allRoutes: frontendRoutes
514
+ });
515
+ genericRes.status(404).header('Content-Type', 'text/html').send(html);
516
+ return;
517
+ } catch (error) {
518
+ Console.error(`Error rendering page 404:`, error);
519
+ genericRes.status(404).text('Page not found');
520
+ return;
521
+ }
522
+ }
523
+
524
+ try {
525
+ const html = await render({
526
+ req: genericReq,
527
+ route: pageMatch.route,
528
+ params: pageMatch.params,
529
+ allRoutes: frontendRoutes
530
+ });
531
+ genericRes.status(200).header('Content-Type', 'text/html').send(html);
532
+ } catch (error) {
533
+ Console.error(`Error rendering page ${pathname}:`, error);
534
+ genericRes.status(500).text('Internal server error');
535
+ }
536
+ };
537
+ },
538
+
539
+ // Método para configurar WebSocket upgrade nos servidores Express e Fastify
540
+ setupWebSocket: (server: any) => {
541
+ // Detecta se é um servidor Express ou Fastify
542
+ const isExpressServer = FrameworkAdapterFactory.getCurrentAdapter() instanceof ExpressAdapter;
543
+ const actualServer = isExpressServer ? server : (server.server || server);
544
+
545
+ // Usa o sistema coordenado de WebSocket upgrade que integra hot-reload e rotas de usuário
546
+ setupWebSocketUpgrade(actualServer, hotReloadManager);
547
+ },
548
+
549
+
550
+ stop: () => {
551
+ if (hotReloadManager) {
552
+ hotReloadManager.stop();
553
+ }
554
+ }
555
+ };
556
+ }
557
+
package/src/loaders.js ADDED
@@ -0,0 +1,53 @@
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
+
18
+ const fs = require('fs');
19
+
20
+ /**
21
+ * Registra loaders customizados para Node.js
22
+ * Permite importar arquivos não-JS diretamente no servidor
23
+ */
24
+ function registerLoaders() {
25
+ // Loader para arquivos Markdown (.md)
26
+ require.extensions['.md'] = function (module, filename) {
27
+ const content = fs.readFileSync(filename, 'utf8');
28
+ module.exports = content;
29
+ };
30
+
31
+ // Loader para arquivos de texto (.txt)
32
+ require.extensions['.txt'] = function (module, filename) {
33
+ const content = fs.readFileSync(filename, 'utf8');
34
+ module.exports = content;
35
+ };
36
+
37
+ // Loader para arquivos JSON (já existe nativamente, mas garantimos consistência)
38
+ // require.extensions['.json'] já existe
39
+
40
+ // Loader para imagens - retorna o caminho do arquivo
41
+ const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.bmp', '.svg'];
42
+
43
+ imageExtensions.forEach(ext => {
44
+ require.extensions[ext] = function (module, filename) {
45
+ // No servidor, retornamos o caminho do arquivo
46
+ // O frontend usará o plugin do esbuild para converter em base64
47
+ module.exports = filename;
48
+ };
49
+ });
50
+ }
51
+
52
+ module.exports = { registerLoaders };
53
+