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