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/hotReload.ts DELETED
@@ -1,489 +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 { WebSocket, WebSocketServer } from 'ws';
18
- import * as chokidar from 'chokidar';
19
- import * as path from 'path';
20
- import * as fs from 'fs';
21
- import { IncomingMessage } from 'http';
22
- import * as url from 'url';
23
- import { clearFileCache } from './router';
24
- import Console, {Colors, Levels} from "./api/console"
25
-
26
- interface ClientConnection {
27
- ws: WebSocket;
28
- pingTimer: NodeJS.Timeout;
29
- lastPong: number;
30
- }
31
-
32
- export class HotReloadManager {
33
- private wss: WebSocketServer | null = null;
34
- private watchers: chokidar.FSWatcher[] = [];
35
- private projectDir: string;
36
- private clients: Map<WebSocket, ClientConnection> = new Map();
37
- private backendApiChangeCallback: (() => void) | null = null;
38
- private frontendChangeCallback: (() => void) | null = null;
39
- private isShuttingDown: boolean = false;
40
- private debounceTimers: Map<string, NodeJS.Timeout> = new Map();
41
- private customHotReloadListener: ((file: string) => Promise<void> | void) | null = null;
42
- private isBuilding: boolean = false;
43
- private buildCompleteResolve: (() => void) | null = null;
44
-
45
- constructor(projectDir: string) {
46
- this.projectDir = projectDir;
47
- }
48
-
49
- async start() {
50
- this.setupWatchers();
51
- }
52
-
53
- // Método para integrar com Express
54
- handleUpgrade(request: IncomingMessage, socket: any, head: Buffer) {
55
- if (this.isShuttingDown) {
56
- socket.destroy();
57
- return;
58
- }
59
-
60
- if (!this.wss) {
61
- this.wss = new WebSocketServer({
62
- noServer: true,
63
- perMessageDeflate: false, // Desabilita compressão para melhor performance
64
- maxPayload: 1024 * 1024 // Limite de 1MB por mensagem
65
- });
66
- this.setupWebSocketServer();
67
- }
68
-
69
- this.wss.handleUpgrade(request, socket, head, (ws) => {
70
- this.wss!.emit('connection', ws, request);
71
- });
72
- }
73
-
74
- private setupWebSocketServer() {
75
- if (!this.wss) return;
76
-
77
- this.wss.on('connection', (ws: WebSocket) => {
78
- if (this.isShuttingDown) {
79
- ws.close();
80
- return;
81
- }
82
-
83
- // Setup ping/pong para detectar conexões mortas
84
- const pingTimer = setInterval(() => {
85
- const client = this.clients.get(ws);
86
- if (client && ws.readyState === WebSocket.OPEN) {
87
- // Se não recebeu pong há mais de 60 segundos, desconecta
88
- if (Date.now() - client.lastPong > 60000) {
89
- ws.terminate();
90
- return;
91
- }
92
- ws.ping();
93
- }
94
- }, 30000);
95
-
96
- const clientConnection: ClientConnection = {
97
- ws,
98
- pingTimer,
99
- lastPong: Date.now()
100
- };
101
-
102
- this.clients.set(ws, clientConnection);
103
-
104
- ws.on('pong', () => {
105
- const client = this.clients.get(ws);
106
- if (client) {
107
- client.lastPong = Date.now();
108
- }
109
- });
110
-
111
- ws.on('close', () => {
112
- this.cleanupClient(ws);
113
- });
114
-
115
- ws.on('error', (error) => {
116
- Console.logWithout(Levels.ERROR, Colors.BgRed,`WebSocket error: ${error.message}`);
117
- this.cleanupClient(ws);
118
- });
119
-
120
- });
121
- }
122
-
123
- private cleanupClient(ws: WebSocket) {
124
- const client = this.clients.get(ws);
125
- if (client) {
126
- clearInterval(client.pingTimer);
127
- this.clients.delete(ws);
128
- }
129
- }
130
-
131
- private setupWatchers() {
132
- // Remove watchers antigos e use apenas um watcher global para src
133
- const debouncedChange = this.debounce((filePath: string) => {
134
- this.handleAnySrcChange(filePath);
135
- }, 100);
136
-
137
- const watcher = chokidar.watch([
138
- path.join(this.projectDir, 'src/**/*'),
139
- ], {
140
- ignored: [
141
- /(^|[\/\\])\../, // arquivos ocultos
142
- '**/node_modules/**',
143
- '**/.git/**',
144
- '**/dist/**'
145
- ],
146
- persistent: true,
147
- ignoreInitial: true,
148
- usePolling: false,
149
- awaitWriteFinish: {
150
- stabilityThreshold: 100,
151
- pollInterval: 50
152
- }
153
- });
154
-
155
- watcher.on('change', debouncedChange);
156
- watcher.on('add', debouncedChange);
157
- watcher.on('unlink', (filePath) => {
158
- Console.info(`🗑️ Arquivo removido: ${path.basename(filePath)}`);
159
- clearFileCache(filePath);
160
- this.clearBackendCache(filePath);
161
- this.frontendChangeCallback?.();
162
- this.backendApiChangeCallback?.();
163
- this.notifyClients('src-reload', { file: filePath, event: 'unlink' });
164
- });
165
-
166
- this.watchers.push(watcher);
167
- }
168
-
169
- private debounce(func: Function, wait: number): (...args: any[]) => void {
170
- return (...args: any[]) => {
171
- const key = args[0]; // usa o primeiro argumento como chave
172
-
173
- const existingTimer = this.debounceTimers.get(key);
174
- if (existingTimer) {
175
- clearTimeout(existingTimer);
176
- }
177
-
178
- const timer = setTimeout(() => {
179
- this.debounceTimers.delete(key);
180
- func.apply(this, args);
181
- }, wait);
182
-
183
- this.debounceTimers.set(key, timer);
184
- };
185
- }
186
-
187
- private async handleAnySrcChange(filePath: string) {
188
- Console.logWithout(Levels.INFO, Colors.BgRed,`🔄 Arquivo alterado: ${path.basename(filePath)}`);
189
-
190
- // Detecta se é arquivo de frontend ou backend
191
- const isFrontendFile = filePath.includes(path.join('src', 'web', 'routes')) ||
192
- filePath.includes(path.join('src', 'web', 'components')) ||
193
- filePath.includes('layout.tsx') ||
194
- filePath.includes('not-found.tsx') ||
195
- filePath.endsWith('.tsx') ||
196
- filePath.endsWith('.jsx');
197
-
198
- const isBackendFile = filePath.includes(path.join('src', 'web', 'backend')) ||
199
- (filePath.includes(path.join('src', 'web')) && !isFrontendFile);
200
-
201
- // Limpa o cache do arquivo alterado
202
- clearFileCache(filePath);
203
- this.clearBackendCache(filePath);
204
-
205
- // Se for arquivo de frontend, aguarda o build terminar antes de recarregar
206
- if (isFrontendFile) {
207
- Console.logWithout(Levels.INFO, Colors.BgRed,`📄 Waiting for frontend build...`);
208
-
209
- // Marca que estamos esperando um build
210
- this.isBuilding = true;
211
-
212
- // Cria uma promise que será resolvida quando o build terminar
213
- const buildPromise = new Promise<void>((resolve) => {
214
- this.buildCompleteResolve = resolve;
215
- });
216
-
217
- // Aguarda o build terminar (com timeout de 30 segundos)
218
- const timeoutPromise = new Promise<void>((_, reject) => {
219
- setTimeout(() => reject(new Error('Build timeout')), 30000);
220
- });
221
-
222
- try {
223
- await Promise.race([buildPromise, timeoutPromise]);
224
- Console.logWithout(Levels.INFO, Colors.BgRed,`✅ Build complete, reloading frontend...`);
225
- this.frontendChangeCallback?.();
226
- this.notifyClients('frontend-reload', { file: filePath, event: 'change' });
227
- } catch (error) {
228
- Console.logWithout(Levels.ERROR, Colors.BgRed,`⚠️ Timeout in build, reloading anyway...`);
229
- this.frontendChangeCallback?.();
230
- this.notifyClients('frontend-reload', { file: filePath, event: 'change' });
231
- } finally {
232
- this.isBuilding = false;
233
- this.buildCompleteResolve = null;
234
- }
235
- }
236
-
237
- // Se for arquivo de backend, recarrega o módulo e notifica
238
- if (isBackendFile) {
239
- Console.logWithout(Levels.INFO, Colors.BgRed,`⚙️ Reloading backend...`);
240
- this.backendApiChangeCallback?.();
241
- this.notifyClients('backend-api-reload', { file: filePath, event: 'change' });
242
- }
243
-
244
- // Fallback: se não for nem frontend nem backend detectado, recarrega tudo
245
- if (!isFrontendFile && !isBackendFile) {
246
- Console.logWithout(Levels.INFO, Colors.BgRed,`🔄 Reloading application...`);
247
- this.frontendChangeCallback?.();
248
- this.backendApiChangeCallback?.();
249
- this.notifyClients('src-reload', { file: filePath, event: 'change' });
250
- }
251
-
252
- // Chama listener customizado se definido
253
- if (this.customHotReloadListener) {
254
- try {
255
- await this.customHotReloadListener(filePath);
256
- } catch (error) {
257
- // @ts-ignore
258
- Console.logWithout(Levels.ERROR, `Error in custom listener: ${error.message}`);
259
- }
260
- }
261
- }
262
-
263
- private notifyClients(type: string, data?: any) {
264
- if (this.isShuttingDown || this.clients.size === 0) {
265
- return;
266
- }
267
-
268
- const message = JSON.stringify({ type, data, timestamp: Date.now() });
269
- const deadClients: WebSocket[] = [];
270
-
271
- this.clients.forEach((client, ws) => {
272
- if (ws.readyState === WebSocket.OPEN) {
273
- try {
274
- ws.send(message);
275
- } catch (error) {
276
- Console.logWithout(Levels.ERROR, Colors.BgRed, `Error sending WebSocket message: ${error}`);
277
- deadClients.push(ws);
278
- }
279
- } else {
280
- deadClients.push(ws);
281
- }
282
- });
283
-
284
- // Remove clientes mortos
285
- deadClients.forEach(ws => this.cleanupClient(ws));
286
- }
287
-
288
- private restartServer() {
289
- this.notifyClients('server-restart');
290
- setTimeout(() => {
291
- this.notifyClients('server-ready');
292
- }, 2000);
293
- }
294
-
295
- stop() {
296
- this.isShuttingDown = true;
297
-
298
- // Limpa todos os debounce timers
299
- this.debounceTimers.forEach(timer => clearTimeout(timer));
300
- this.debounceTimers.clear();
301
-
302
- // Para todos os watchers
303
- this.watchers.forEach(watcher => watcher.close());
304
- this.watchers = [];
305
-
306
- // Limpa todos os clientes
307
- this.clients.forEach((client, ws) => {
308
- clearInterval(client.pingTimer);
309
- if (ws.readyState === WebSocket.OPEN) {
310
- ws.close();
311
- }
312
- });
313
- this.clients.clear();
314
-
315
- // Fecha WebSocket server
316
- if (this.wss) {
317
- this.wss.close();
318
- this.wss = null;
319
- }
320
- }
321
-
322
- // Script do cliente otimizado com reconnection backoff
323
- getClientScript(): string {
324
- return `
325
- <script>
326
- (function() {
327
- if (typeof window !== 'undefined') {
328
- let ws;
329
- let reconnectAttempts = 0;
330
- let maxReconnectInterval = 30000;
331
- let reconnectInterval = 1000;
332
- let reconnectTimer;
333
- let isConnected = false;
334
-
335
- function connect() {
336
- const url = window.location; // Objeto com info da URL atual
337
- const protocol = url.protocol === "https:" ? "wss:" : "ws:"; // Usa wss se for https
338
- const wsUrl = protocol + '//' + url.host + '/hweb-hotreload/';
339
- if (ws && (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)) {
340
- return;
341
- }
342
-
343
- try {
344
- ws = new WebSocket(wsUrl);
345
-
346
- ws.onopen = function() {
347
- console.log('🔌 Hot-reload connected');
348
- isConnected = true;
349
- reconnectAttempts = 0;
350
- reconnectInterval = 1000;
351
- clearTimeout(reconnectTimer);
352
- };
353
-
354
- ws.onmessage = function(event) {
355
- try {
356
- const message = JSON.parse(event.data);
357
-
358
- switch(message.type) {
359
- case 'frontend-reload':
360
- window.location.reload();
361
- break;
362
- case 'backend-api-reload':
363
- // Recarrega apenas se necessário
364
- window.location.reload();
365
- break;
366
- case 'server-restart':
367
- console.log('🔄 Server restarting...');
368
- break;
369
- case 'server-ready':
370
- setTimeout(() => window.location.reload(), 500);
371
- break;
372
- case 'frontend-error':
373
- console.error('❌ Frontend error:', message.data);
374
- break;
375
- }
376
- } catch (e) {
377
- console.error('Erro ao processar mensagem do hot-reload:', e);
378
- }
379
- };
380
-
381
- ws.onclose = function(event) {
382
- isConnected = false;
383
-
384
- // Não tenta reconectar se foi fechamento intencional
385
- if (event.code === 1000) {
386
- return;
387
- }
388
-
389
- scheduleReconnect();
390
- };
391
-
392
- ws.onerror = function(error) {
393
- isConnected = false;
394
- // Não loga erros de conexão para evitar spam no console
395
- };
396
-
397
- } catch (error) {
398
- console.error('Error creating WebSocket:', error);
399
- scheduleReconnect();
400
- }
401
- }
402
-
403
- function scheduleReconnect() {
404
- if (reconnectTimer) {
405
- clearTimeout(reconnectTimer);
406
- }
407
-
408
- reconnectAttempts++;
409
-
410
- // Exponential backoff com jitter
411
- const baseInterval = Math.min(reconnectInterval * Math.pow(1.5, reconnectAttempts - 1), maxReconnectInterval);
412
- const jitter = Math.random() * 1000; // Adiciona até 1 segundo de variação
413
- const finalInterval = baseInterval + jitter;
414
-
415
- reconnectTimer = setTimeout(() => {
416
- if (!isConnected) {
417
- connect();
418
- }
419
- }, finalInterval);
420
- }
421
-
422
- // Detecta quando a página está sendo fechada para evitar reconexões desnecessárias
423
- window.addEventListener('beforeunload', function() {
424
- if (ws && ws.readyState === WebSocket.OPEN) {
425
- ws.close(1000, 'Page unloading');
426
- }
427
- clearTimeout(reconnectTimer);
428
- });
429
-
430
- // Detecta quando a aba fica visível novamente para reconectar se necessário
431
- document.addEventListener('visibilitychange', function() {
432
- if (!document.hidden && !isConnected) {
433
- reconnectAttempts = 0; // Reset do contador quando a aba fica ativa
434
- connect();
435
- }
436
- });
437
-
438
- connect();
439
- }
440
- })();
441
- </script>
442
- `;
443
- }
444
-
445
- private clearBackendCache(filePath: string) {
446
- const absolutePath = path.resolve(filePath);
447
- delete require.cache[absolutePath];
448
-
449
- // Limpa dependências relacionadas de forma mais eficiente
450
- const dirname = path.dirname(absolutePath);
451
- Object.keys(require.cache).forEach(key => {
452
- if (key.startsWith(dirname)) {
453
- delete require.cache[key];
454
- }
455
- });
456
- }
457
-
458
- onBackendApiChange(callback: () => void) {
459
- this.backendApiChangeCallback = callback;
460
- }
461
-
462
- onFrontendChange(callback: () => void) {
463
- this.frontendChangeCallback = callback;
464
- }
465
-
466
- setHotReloadListener(listener: (file: string) => Promise<void> | void) {
467
- this.customHotReloadListener = listener;
468
- Console.info('🔌 Hot reload custom listener registered');
469
- }
470
-
471
- removeHotReloadListener() {
472
- this.customHotReloadListener = null;
473
- }
474
-
475
- onBuildComplete(success: boolean) {
476
- if (this.buildCompleteResolve) {
477
- this.buildCompleteResolve();
478
- this.buildCompleteResolve = null;
479
- }
480
- this.isBuilding = false;
481
-
482
- // Notifica os clientes que o build terminou
483
- if (success) {
484
- this.notifyClients('build-complete', { success: true });
485
- } else {
486
- this.notifyClients('build-error', { success: false });
487
- }
488
- }
489
- }