hightjs 0.5.3 → 0.5.4

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