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/router.ts ADDED
@@ -0,0 +1,744 @@
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 fs from 'fs';
18
+ import path from 'path';
19
+ import { RouteConfig, BackendRouteConfig, HightMiddleware, WebSocketHandler, WebSocketContext } from './types';
20
+ import { WebSocketServer as WSServer, WebSocket } from 'ws';
21
+ import { IncomingMessage } from 'http';
22
+ import { URL } from 'url';
23
+ import Console from "./api/console"
24
+ import {FrameworkAdapterFactory} from "./adapters/factory";
25
+ import {HightJSRequest} from "./api/http";
26
+
27
+ // --- Roteamento do Frontend ---
28
+
29
+ // Guarda todas as rotas de PÁGINA (React) encontradas
30
+ // A rota agora também armazena o caminho do arquivo para ser usado como um ID único no cliente
31
+ let allRoutes: (RouteConfig & { componentPath: string })[] = [];
32
+
33
+ // Guarda o layout se existir
34
+ let layoutComponent: { componentPath: string; metadata?: any } | null = null;
35
+
36
+ // Guarda o componente 404 personalizado se existir
37
+ let notFoundComponent: { componentPath: string } | null = null;
38
+
39
+ // Cache de arquivos carregados para limpeza
40
+ let loadedRouteFiles: Set<string> = new Set();
41
+ let loadedLayoutFiles: Set<string> = new Set();
42
+ let loadedNotFoundFiles: Set<string> = new Set();
43
+
44
+ /**
45
+ * Limpa o cache do require para um arquivo específico
46
+ * @param filePath Caminho do arquivo para limpar
47
+ */
48
+ function clearRequireCache(filePath: string) {
49
+ try {
50
+ const resolvedPath = require.resolve(filePath);
51
+ delete require.cache[resolvedPath];
52
+
53
+ // Também limpa arquivos temporários relacionados (apenas se existir no cache)
54
+ const tempFile = filePath.replace(/\.(tsx|ts|jsx|js)$/, '.temp.$1');
55
+ const tempResolvedPath = require.cache[require.resolve(tempFile)];
56
+ if (tempResolvedPath) {
57
+ delete require.cache[require.resolve(tempFile)];
58
+ }
59
+ } catch {
60
+ // Arquivo pode não estar no cache ou não ser resolvível
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Limpa todo o cache de rotas carregadas
66
+ */
67
+ export function clearAllRouteCache() {
68
+ // Limpa cache das rotas
69
+ loadedRouteFiles.forEach(filePath => {
70
+ clearRequireCache(filePath);
71
+ });
72
+ loadedRouteFiles.clear();
73
+
74
+ // Limpa cache do layout
75
+ loadedLayoutFiles.forEach(filePath => {
76
+ clearRequireCache(filePath);
77
+ });
78
+ loadedLayoutFiles.clear();
79
+
80
+ // Limpa cache do notFound
81
+ loadedNotFoundFiles.forEach(filePath => {
82
+ clearRequireCache(filePath);
83
+ });
84
+ loadedNotFoundFiles.clear();
85
+ }
86
+
87
+ /**
88
+ * Limpa o cache de um arquivo específico e recarrega as rotas se necessário
89
+ * @param changedFilePath Caminho do arquivo que foi alterado
90
+ */
91
+ export function clearFileCache(changedFilePath: string) {
92
+ const absolutePath = path.isAbsolute(changedFilePath) ? changedFilePath : path.resolve(changedFilePath);
93
+
94
+ // Limpa o cache do arquivo específico
95
+ clearRequireCache(absolutePath);
96
+
97
+ // Remove das listas de arquivos carregados
98
+ loadedRouteFiles.delete(absolutePath);
99
+ loadedLayoutFiles.delete(absolutePath);
100
+ loadedNotFoundFiles.delete(absolutePath);
101
+ }
102
+
103
+ /**
104
+ * Carrega o layout.tsx se existir no diretório web
105
+ * @param webDir O diretório web onde procurar o layout
106
+ * @returns O layout carregado ou null se não existir
107
+ */
108
+ export function loadLayout(webDir: string): { componentPath: string; metadata?: any } | null {
109
+ const layoutPath = path.join(webDir, 'layout.tsx');
110
+ const layoutPathTs = path.join(webDir, 'layout.ts');
111
+ const layoutPathJsx = path.join(webDir, 'layout.jsx');
112
+ const layoutPathJs = path.join(webDir, 'layout.js');
113
+
114
+ const layoutFile = fs.existsSync(layoutPath) ? layoutPath :
115
+ fs.existsSync(layoutPathTs) ? layoutPathTs :
116
+ fs.existsSync(layoutPathJsx) ? layoutPathJsx :
117
+ fs.existsSync(layoutPathJs) ? layoutPathJs : null;
118
+
119
+ if (layoutFile) {
120
+ const absolutePath = path.resolve(layoutFile);
121
+ const componentPath = path.relative(process.cwd(), layoutFile).replace(/\\/g, '/');
122
+
123
+ try {
124
+ // HACK: Cria uma versão temporária do layout SEM imports de CSS para carregar no servidor
125
+ const layoutContent = fs.readFileSync(layoutFile, 'utf8');
126
+ const tempContent = layoutContent
127
+ .replace(/import\s+['"][^'"]*\.css['"];?/g, '// CSS import removido para servidor')
128
+ .replace(/import\s+['"][^'"]*\.scss['"];?/g, '// SCSS import removido para servidor')
129
+ .replace(/import\s+['"][^'"]*\.sass['"];?/g, '// SASS import removido para servidor');
130
+
131
+ const tempFile = layoutFile.replace(/\.(tsx|ts|jsx|js)$/, '.temp.$1');
132
+ fs.writeFileSync(tempFile, tempContent);
133
+
134
+ // Otimização: limpa cache apenas se existir
135
+ try {
136
+ const resolvedPath = require.resolve(tempFile);
137
+ if (require.cache[resolvedPath]) {
138
+ delete require.cache[resolvedPath];
139
+ }
140
+ } catch {}
141
+
142
+ const layoutModule = require(tempFile);
143
+
144
+ // Remove o arquivo temporário
145
+ fs.unlinkSync(tempFile);
146
+
147
+ const metadata = layoutModule.metadata || null;
148
+
149
+ // Registra o arquivo como carregado
150
+ loadedLayoutFiles.add(absolutePath);
151
+
152
+ layoutComponent = { componentPath, metadata };
153
+ return layoutComponent;
154
+ } catch (error) {
155
+ Console.error(`Error loading layout ${layoutFile}:`, error);
156
+ layoutComponent = { componentPath };
157
+ return layoutComponent;
158
+ }
159
+ }
160
+
161
+ layoutComponent = null;
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * Retorna o layout atual se carregado
167
+ */
168
+ export function getLayout(): { componentPath: string; metadata?: any } | null {
169
+ return layoutComponent;
170
+ }
171
+
172
+ /**
173
+ * Carrega dinamicamente todas as rotas de frontend do diretório do usuário.
174
+ * @param routesDir O diretório onde as rotas de página estão localizadas.
175
+ * @returns A lista de rotas de página que foram carregadas.
176
+ */
177
+ export function loadRoutes(routesDir: string): (RouteConfig & { componentPath: string })[] {
178
+ if (!fs.existsSync(routesDir)) {
179
+ Console.warn(`Frontend routes directory not found at ${routesDir}. No page will be loaded.`);
180
+ allRoutes = [];
181
+ return allRoutes;
182
+ }
183
+
184
+ // Otimização: usa função recursiva manual para evitar overhead do recursive: true
185
+ const routeFiles: string[] = [];
186
+ const scanDirectory = (dir: string, baseDir: string = '') => {
187
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
188
+ for (const entry of entries) {
189
+ const relativePath = baseDir ? path.join(baseDir, entry.name) : entry.name;
190
+
191
+ if (entry.isDirectory()) {
192
+ // Pula diretório backend inteiro
193
+ if (entry.name === 'backend') continue;
194
+ scanDirectory(path.join(dir, entry.name), relativePath);
195
+ } else if (entry.isFile()) {
196
+ // Filtra apenas arquivos .ts/.tsx/.js/.jsx
197
+ if (entry.name.endsWith('.ts') || entry.name.endsWith('.tsx') ||
198
+ entry.name.endsWith('.js') || entry.name.endsWith('.jsx')) {
199
+ routeFiles.push(relativePath);
200
+ }
201
+ }
202
+ }
203
+ };
204
+
205
+ scanDirectory(routesDir);
206
+
207
+ const loaded: (RouteConfig & { componentPath: string })[] = [];
208
+ const cwdPath = process.cwd();
209
+
210
+ // Otimização: processa arquivos em lote
211
+ for (const file of routeFiles) {
212
+ const filePath = path.join(routesDir, file);
213
+ const absolutePath = path.resolve(filePath);
214
+
215
+ try {
216
+ // Otimização: limpa cache apenas se já existir
217
+ const resolvedPath = require.resolve(filePath);
218
+ if (require.cache[resolvedPath]) {
219
+ delete require.cache[resolvedPath];
220
+ }
221
+
222
+ const routeModule = require(filePath);
223
+ if (routeModule.default?.pattern && routeModule.default?.component) {
224
+ // Otimização: calcula componentPath apenas uma vez
225
+ const componentPath = path.relative(cwdPath, filePath).replace(/\\/g, '/');
226
+ loaded.push({ ...routeModule.default, componentPath });
227
+ loadedRouteFiles.add(absolutePath);
228
+ }
229
+ } catch (error) {
230
+ Console.error(`Error loading page route ${filePath}:`, error);
231
+ }
232
+ }
233
+
234
+ allRoutes = loaded;
235
+ return allRoutes;
236
+ }
237
+
238
+ /**
239
+ * Encontra a rota de página correspondente para uma URL.
240
+ * @param pathname O caminho da URL (ex: "/users/123").
241
+ * @returns Um objeto com a rota e os parâmetros, ou null se não encontrar.
242
+ */
243
+ export function findMatchingRoute(pathname: string) {
244
+ for (const route of allRoutes) {
245
+ if (!route.pattern) continue;
246
+
247
+ const regexPattern = route.pattern
248
+ // [[...param]] → opcional catch-all
249
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
250
+ // [...param] → obrigatório catch-all
251
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
252
+ // /[[param]] → opcional com barra também opcional
253
+ .replace(/\/\[\[(\w+)\]\]/g, '(?:/(?<$1>[^/]+))?')
254
+ // [[param]] → segmento opcional (sem barra anterior)
255
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
256
+ // [param] → segmento obrigatório
257
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
258
+
259
+ // permite / opcional no final
260
+ const regex = new RegExp(`^${regexPattern}/?$`);
261
+ const match = pathname.match(regex);
262
+
263
+ if (match) {
264
+ return {
265
+ route,
266
+ params: match.groups || {}
267
+ };
268
+ }
269
+ }
270
+
271
+ return null;
272
+ }
273
+
274
+
275
+ // --- Roteamento do Backend ---
276
+
277
+ // Guarda todas as rotas de API encontradas
278
+ let allBackendRoutes: BackendRouteConfig[] = [];
279
+
280
+ // Cache de middlewares carregados por diretório
281
+ let loadedMiddlewares: Map<string, HightMiddleware[]> = new Map();
282
+
283
+ /**
284
+ * Carrega middlewares de um diretório específico
285
+ * @param dir O diretório onde procurar por middleware.ts
286
+ * @returns Array de middlewares encontrados
287
+ */
288
+ function loadMiddlewareFromDirectory(dir: string): HightMiddleware[] {
289
+ const middlewares: HightMiddleware[] = [];
290
+
291
+ // Procura por middleware.ts, middleware.tsx, middleware.js ou middleware.jsx
292
+ const middlewarePath = path.join(dir, 'middleware.ts');
293
+ const middlewarePathTsx = path.join(dir, 'middleware.tsx');
294
+ const middlewarePathJs = path.join(dir, 'middleware.js');
295
+ const middlewarePathJsx = path.join(dir, 'middleware.jsx');
296
+
297
+ const middlewareFile = fs.existsSync(middlewarePath) ? middlewarePath :
298
+ fs.existsSync(middlewarePathTsx) ? middlewarePathTsx :
299
+ fs.existsSync(middlewarePathJs) ? middlewarePathJs :
300
+ fs.existsSync(middlewarePathJsx) ? middlewarePathJsx : null;
301
+
302
+ if (middlewareFile) {
303
+ try {
304
+ const absolutePath = path.resolve(middlewareFile);
305
+ clearRequireCache(absolutePath);
306
+
307
+ const middlewareModule = require(middlewareFile);
308
+
309
+ // Suporte para export default (função única) ou export { middleware1, middleware2 }
310
+ if (typeof middlewareModule.default === 'function') {
311
+ middlewares.push(middlewareModule.default);
312
+ } else if (middlewareModule.default && Array.isArray(middlewareModule.default)) {
313
+ middlewares.push(...middlewareModule.default);
314
+ } else {
315
+ // Procura por exports nomeados que sejam funções
316
+ Object.keys(middlewareModule).forEach(key => {
317
+ if (key !== 'default' && typeof middlewareModule[key] === 'function') {
318
+ middlewares.push(middlewareModule[key]);
319
+ }
320
+ });
321
+ }
322
+
323
+ } catch (error) {
324
+ Console.error(`Error loading middleware ${middlewareFile}:`, error);
325
+ }
326
+ }
327
+
328
+ return middlewares;
329
+ }
330
+
331
+ /**
332
+ * Coleta middlewares do diretório específico da rota (não herda dos pais)
333
+ * @param routeFilePath Caminho completo do arquivo de rota
334
+ * @param backendRoutesDir Diretório raiz das rotas de backend
335
+ * @returns Array com middlewares apenas do diretório da rota
336
+ */
337
+ function collectMiddlewaresForRoute(routeFilePath: string, backendRoutesDir: string): HightMiddleware[] {
338
+ const relativePath = path.relative(backendRoutesDir, routeFilePath);
339
+ const routeDir = path.dirname(path.join(backendRoutesDir, relativePath));
340
+
341
+ // Carrega middlewares APENAS do diretório específico da rota (não herda dos pais)
342
+ if (!loadedMiddlewares.has(routeDir)) {
343
+ const middlewares = loadMiddlewareFromDirectory(routeDir);
344
+ loadedMiddlewares.set(routeDir, middlewares);
345
+ }
346
+
347
+ return loadedMiddlewares.get(routeDir) || [];
348
+ }
349
+
350
+ /**
351
+ * Carrega dinamicamente todas as rotas de API do diretório de backend.
352
+ * @param backendRoutesDir O diretório onde as rotas de API estão localizadas.
353
+ */
354
+ export function loadBackendRoutes(backendRoutesDir: string) {
355
+ if (!fs.existsSync(backendRoutesDir)) {
356
+ // É opcional ter uma API, então não mostramos um aviso se a pasta não existir.
357
+ allBackendRoutes = [];
358
+ return;
359
+ }
360
+
361
+ // Limpa cache de middlewares para recarregar
362
+ loadedMiddlewares.clear();
363
+
364
+ // Otimização: usa função recursiva manual e coleta middlewares durante o scan
365
+ const routeFiles: string[] = [];
366
+ const middlewareFiles: Map<string, string> = new Map(); // dir -> filepath
367
+
368
+ const scanDirectory = (dir: string, baseDir: string = '') => {
369
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
370
+
371
+ for (const entry of entries) {
372
+ const relativePath = baseDir ? path.join(baseDir, entry.name) : entry.name;
373
+
374
+ if (entry.isDirectory()) {
375
+ scanDirectory(path.join(dir, entry.name), relativePath);
376
+ } else if (entry.isFile()) {
377
+ const isSupported = entry.name.endsWith('.ts') || entry.name.endsWith('.tsx') ||
378
+ entry.name.endsWith('.js') || entry.name.endsWith('.jsx');
379
+ if (!isSupported) continue;
380
+
381
+ // Identifica middlewares durante o scan
382
+ if (entry.name.startsWith('middleware')) {
383
+ const dirPath = path.dirname(path.join(backendRoutesDir, relativePath));
384
+ middlewareFiles.set(dirPath, path.join(backendRoutesDir, relativePath));
385
+ } else {
386
+ routeFiles.push(relativePath);
387
+ }
388
+ }
389
+ }
390
+ };
391
+
392
+ scanDirectory(backendRoutesDir);
393
+
394
+ // Otimização: pré-carrega todos os middlewares em um único passe
395
+ for (const [dirPath, middlewarePath] of middlewareFiles) {
396
+ try {
397
+ const resolvedPath = require.resolve(middlewarePath);
398
+ if (require.cache[resolvedPath]) {
399
+ delete require.cache[resolvedPath];
400
+ }
401
+
402
+ const middlewareModule = require(middlewarePath);
403
+ const middlewares: HightMiddleware[] = [];
404
+
405
+ if (typeof middlewareModule.default === 'function') {
406
+ middlewares.push(middlewareModule.default);
407
+ } else if (Array.isArray(middlewareModule.default)) {
408
+ middlewares.push(...middlewareModule.default);
409
+ } else {
410
+ // Exports nomeados
411
+ for (const key in middlewareModule) {
412
+ if (key !== 'default' && typeof middlewareModule[key] === 'function') {
413
+ middlewares.push(middlewareModule[key]);
414
+ }
415
+ }
416
+ }
417
+
418
+ if (middlewares.length > 0) {
419
+ loadedMiddlewares.set(dirPath, middlewares);
420
+ }
421
+ } catch (error) {
422
+ Console.error(`Error loading middleware ${middlewarePath}:`, error);
423
+ }
424
+ }
425
+
426
+ // Otimização: processa rotas com cache já limpo
427
+ const loaded: BackendRouteConfig[] = [];
428
+ for (const file of routeFiles) {
429
+ const filePath = path.join(backendRoutesDir, file);
430
+
431
+ try {
432
+ // Otimização: limpa cache apenas se existir
433
+ const resolvedPath = require.resolve(filePath);
434
+ if (require.cache[resolvedPath]) {
435
+ delete require.cache[resolvedPath];
436
+ }
437
+
438
+ const routeModule = require(filePath);
439
+ if (routeModule.default?.pattern) {
440
+ const routeConfig = { ...routeModule.default };
441
+ // Se a rota NÃO tem middleware definido, usa os da pasta
442
+ if (!routeConfig.hasOwnProperty('middleware')) {
443
+ const routeDir = path.dirname(path.resolve(filePath));
444
+ const folderMiddlewares = loadedMiddlewares.get(routeDir);
445
+ if (folderMiddlewares && folderMiddlewares.length > 0) {
446
+ routeConfig.middleware = folderMiddlewares;
447
+ }
448
+ }
449
+
450
+ loaded.push(routeConfig);
451
+ }
452
+ } catch (error) {
453
+ Console.error(`Error loading API route ${filePath}:`, error);
454
+ }
455
+ }
456
+
457
+ allBackendRoutes = loaded;
458
+ }
459
+
460
+ /**
461
+ * Encontra a rota de API correspondente para uma URL e método HTTP.
462
+ * @param pathname O caminho da URL (ex: "/api/users/123").
463
+ * @param method O método HTTP da requisição (GET, POST, etc.).
464
+ * @returns Um objeto com a rota e os parâmetros, ou null se não encontrar.
465
+ */
466
+ export function findMatchingBackendRoute(pathname: string, method: string) {
467
+ for (const route of allBackendRoutes) {
468
+ // Verifica se a rota tem um handler para o método HTTP atual
469
+ if (!route.pattern || !route[method.toUpperCase() as keyof BackendRouteConfig]) continue;
470
+ const regexPattern = route.pattern
471
+ // [[...param]] → opcional catch-all
472
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
473
+ // [...param] → obrigatório catch-all
474
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
475
+ // [[param]] → segmento opcional
476
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
477
+ // [param] → segmento obrigatório
478
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
479
+
480
+ const regex = new RegExp(`^${regexPattern}/?$`);
481
+ const match = pathname.match(regex);
482
+
483
+ if (match) {
484
+ return {
485
+ route,
486
+ params: match.groups || {}
487
+ };
488
+ }
489
+ }
490
+ return null;
491
+ }
492
+
493
+ /**
494
+ * Carrega o notFound.tsx se existir no diretório web
495
+ * @param webDir O diretório web onde procurar o notFound
496
+ * @returns O notFound carregado ou null se não existir
497
+ */
498
+ export function loadNotFound(webDir: string): { componentPath: string } | null {
499
+ const notFoundPath = path.join(webDir, 'notFound.tsx');
500
+ const notFoundPathTs = path.join(webDir, 'notFound.ts');
501
+ const notFoundPathJsx = path.join(webDir, 'notFound.jsx');
502
+ const notFoundPathJs = path.join(webDir, 'notFound.js');
503
+
504
+ const notFoundFile = fs.existsSync(notFoundPath) ? notFoundPath :
505
+ fs.existsSync(notFoundPathTs) ? notFoundPathTs :
506
+ fs.existsSync(notFoundPathJsx) ? notFoundPathJsx :
507
+ fs.existsSync(notFoundPathJs) ? notFoundPathJs : null;
508
+
509
+ if (notFoundFile) {
510
+ const absolutePath = path.resolve(notFoundFile);
511
+ const componentPath = path.relative(process.cwd(), notFoundFile).replace(/\\/g, '/');
512
+
513
+ try {
514
+ // Otimização: limpa cache apenas se existir
515
+ try {
516
+ const resolvedPath = require.resolve(notFoundFile);
517
+ if (require.cache[resolvedPath]) {
518
+ delete require.cache[resolvedPath];
519
+ }
520
+ } catch {}
521
+
522
+ // Registra o arquivo como carregado
523
+ loadedNotFoundFiles.add(absolutePath);
524
+
525
+ notFoundComponent = { componentPath };
526
+ return notFoundComponent;
527
+ } catch (error) {
528
+ Console.error(`Error loading notFound ${notFoundFile}:`, error);
529
+ notFoundComponent = { componentPath };
530
+ return notFoundComponent;
531
+ }
532
+ }
533
+
534
+ notFoundComponent = null;
535
+ return null;
536
+ }
537
+
538
+ /**
539
+ * Retorna o componente 404 atual se carregado
540
+ */
541
+ export function getNotFound(): { componentPath: string } | null {
542
+ return notFoundComponent;
543
+ }
544
+
545
+ // --- WebSocket Functions ---
546
+
547
+ // Guarda todas as rotas WebSocket encontradas
548
+ let allWebSocketRoutes: { pattern: string; handler: WebSocketHandler; middleware?: HightMiddleware[] }[] = [];
549
+
550
+ // Conexões WebSocket ativas
551
+ let wsConnections: Set<WebSocket> = new Set();
552
+
553
+ /**
554
+ * Processa e registra rotas WebSocket encontradas nas rotas backend
555
+ */
556
+ export function processWebSocketRoutes() {
557
+ allWebSocketRoutes = [];
558
+
559
+ for (const route of allBackendRoutes) {
560
+ if (route.WS) {
561
+ const wsRoute = {
562
+ pattern: route.pattern,
563
+ handler: route.WS,
564
+ middleware: route.middleware
565
+ };
566
+
567
+ allWebSocketRoutes.push(wsRoute);
568
+ }
569
+ }
570
+ }
571
+
572
+ /**
573
+ * Encontra a rota WebSocket correspondente para uma URL
574
+ */
575
+ export function findMatchingWebSocketRoute(pathname: string) {
576
+ for (const route of allWebSocketRoutes) {
577
+ if (!route.pattern) continue;
578
+
579
+ const regexPattern = route.pattern
580
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
581
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
582
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
583
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
584
+
585
+ const regex = new RegExp(`^${regexPattern}/?$`);
586
+ const match = pathname.match(regex);
587
+
588
+ if (match) {
589
+ return {
590
+ route,
591
+ params: match.groups || {}
592
+ };
593
+ }
594
+ }
595
+ return null;
596
+ }
597
+
598
+ /**
599
+ * Trata uma nova conexão WebSocket
600
+ */
601
+ function handleWebSocketConnection(ws: WebSocket, req: IncomingMessage, hwebReq: HightJSRequest) {
602
+ if (!req.url) return;
603
+
604
+ const url = new URL(req.url, `http://${req.headers.host}`);
605
+ const pathname = url.pathname;
606
+
607
+ const matchedRoute = findMatchingWebSocketRoute(pathname);
608
+ if (!matchedRoute) {
609
+ ws.close(1000, 'Route not found');
610
+ return;
611
+ }
612
+
613
+ const params = extractWebSocketParams(pathname, matchedRoute.route.pattern);
614
+ const query = Object.fromEntries(url.searchParams.entries());
615
+
616
+ const context: WebSocketContext = {
617
+ hightReq: hwebReq,
618
+ ws,
619
+ req,
620
+ url,
621
+ params,
622
+ query,
623
+ send: (data: any) => {
624
+ if (ws.readyState === WebSocket.OPEN) {
625
+ const message = typeof data === 'string' ? data : JSON.stringify(data);
626
+ ws.send(message);
627
+ }
628
+ },
629
+ close: (code?: number, reason?: string) => {
630
+ ws.close(code || 1000, reason);
631
+ },
632
+ broadcast: (data: any, exclude?: WebSocket[]) => {
633
+ const message = typeof data === 'string' ? data : JSON.stringify(data);
634
+ const excludeSet = new Set(exclude || []);
635
+ wsConnections.forEach(connection => {
636
+ if (connection.readyState === WebSocket.OPEN && !excludeSet.has(connection)) {
637
+ connection.send(message);
638
+ }
639
+ });
640
+ }
641
+ };
642
+
643
+ try {
644
+ matchedRoute.route.handler(context);
645
+ } catch (error) {
646
+ console.error('Error in WebSocket handler:', error);
647
+ ws.close(1011, 'Internal server error');
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Extrai parâmetros da URL para WebSocket
653
+ */
654
+ function extractWebSocketParams(pathname: string, pattern: string): Record<string, string> {
655
+ const params: Record<string, string> = {};
656
+
657
+ const regexPattern = pattern
658
+ .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
659
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
660
+ .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
661
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
662
+
663
+ const regex = new RegExp(`^${regexPattern}/?$`);
664
+ const match = pathname.match(regex);
665
+
666
+ if (match && match.groups) {
667
+ Object.assign(params, match.groups);
668
+ }
669
+
670
+ return params;
671
+ }
672
+
673
+ /**
674
+ * Configura WebSocket upgrade no servidor HTTP existente
675
+ * @param server Servidor HTTP (Express, Fastify ou Native)
676
+ * @param hotReloadManager Instância do gerenciador de hot-reload para coordenação
677
+ */
678
+ export function setupWebSocketUpgrade(server: any, hotReloadManager?: any) {
679
+ // NÃO remove listeners existentes para preservar hot-reload
680
+ // Em vez disso, coordena com o sistema existente
681
+
682
+ // Verifica se já existe um listener de upgrade
683
+ const existingListeners = server.listeners('upgrade');
684
+
685
+ // Se não há listeners, ou se o hot-reload ainda não foi configurado, adiciona o nosso
686
+ if (existingListeners.length === 0) {
687
+ server.on('upgrade', (request: any, socket: any, head: Buffer) => {
688
+
689
+ handleWebSocketUpgrade(request, socket, head, hotReloadManager);
690
+ });
691
+ }
692
+ }
693
+
694
+ function handleWebSocketUpgrade(request: any, socket: any, head: Buffer, hotReloadManager?: any) {
695
+ const adapter = FrameworkAdapterFactory.getCurrentAdapter()
696
+ if (!adapter) {
697
+ console.error('❌ Framework adapter not detected. Unable to process WebSocket upgrade.');
698
+ socket.destroy();
699
+ return;
700
+ }
701
+ const genericReq = adapter.parseRequest(request);
702
+ const hwebReq = new HightJSRequest(genericReq);
703
+ const { pathname } = new URL(request.url, `http://${request.headers.host}`);
704
+
705
+ // Prioridade 1: Hot reload (sistema interno)
706
+ if (pathname === '/hweb-hotreload/') {
707
+
708
+ if (hotReloadManager) {
709
+ hotReloadManager.handleUpgrade(request, socket, head);
710
+ } else {
711
+ socket.destroy();
712
+ }
713
+ return;
714
+ }
715
+
716
+ // Prioridade 2: Rotas WebSocket do usuário
717
+ const matchedRoute = findMatchingWebSocketRoute(pathname);
718
+ if (matchedRoute) {
719
+ // Faz upgrade para WebSocket usando noServer
720
+ const wss = new WSServer({
721
+ noServer: true,
722
+ perMessageDeflate: false, // Melhor performance
723
+ maxPayload: 1024 * 1024 // Limite de 1MB
724
+ });
725
+
726
+ wss.handleUpgrade(request, socket, head, (ws) => {
727
+ wsConnections.add(ws);
728
+
729
+ ws.on('close', () => {
730
+ wsConnections.delete(ws);
731
+ });
732
+
733
+ ws.on('error', (error) => {
734
+ wsConnections.delete(ws);
735
+ });
736
+
737
+ // Processa a conexão
738
+ handleWebSocketConnection(ws, request, hwebReq);
739
+ });
740
+ return;
741
+ }
742
+
743
+ socket.destroy();
744
+ }