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
@@ -0,0 +1,294 @@
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.Levels = exports.Colors = exports.DynamicLine = void 0;
7
+ /*
8
+ * This file is part of the HightJS Project.
9
+ * Copyright (c) 2025 itsmuzin
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ */
23
+ const boxen_1 = __importDefault(require("boxen"));
24
+ const node_readline_1 = __importDefault(require("node:readline"));
25
+ /**
26
+ * Um "handle" para uma linha dinâmica. As instâncias desta classe
27
+ * são retornadas por `Console.dynamicLine()` e usadas para controlar
28
+ * o conteúdo da linha.
29
+ */
30
+ class DynamicLine {
31
+ constructor(initialContent) {
32
+ // A ID é usada internamente pela classe Console para rastrear esta linha.
33
+ this._id = Symbol();
34
+ // Registra esta nova linha na classe Console para que ela seja renderizada.
35
+ Console['registerDynamicLine'](this._id, initialContent);
36
+ }
37
+ /**
38
+ * Atualiza o conteúdo da linha no console.
39
+ * @param newContent O novo texto a ser exibido.
40
+ */
41
+ update(newContent) {
42
+ Console['updateDynamicLine'](this._id, newContent);
43
+ }
44
+ /**
45
+ * Finaliza a linha, opcionalmente com um texto final, e a torna estática.
46
+ * @param finalContent O texto final a ser exibido.
47
+ */
48
+ end(finalContent) {
49
+ Console['endDynamicLine'](this._id, finalContent);
50
+ }
51
+ }
52
+ exports.DynamicLine = DynamicLine;
53
+ var Colors;
54
+ (function (Colors) {
55
+ Colors["Reset"] = "\u001B[0m";
56
+ Colors["Bright"] = "\u001B[1m";
57
+ Colors["Dim"] = "\u001B[2m";
58
+ Colors["Underscore"] = "\u001B[4m";
59
+ Colors["Blink"] = "\u001B[5m";
60
+ Colors["Reverse"] = "\u001B[7m";
61
+ Colors["Hidden"] = "\u001B[8m";
62
+ Colors["FgBlack"] = "\u001B[30m";
63
+ Colors["FgRed"] = "\u001B[31m";
64
+ Colors["FgGreen"] = "\u001B[32m";
65
+ Colors["FgYellow"] = "\u001B[33m";
66
+ Colors["FgBlue"] = "\u001B[34m";
67
+ Colors["FgMagenta"] = "\u001B[35m";
68
+ Colors["FgCyan"] = "\u001B[36m";
69
+ Colors["FgWhite"] = "\u001B[37m";
70
+ Colors["FgGray"] = "\u001B[90m";
71
+ Colors["BgBlack"] = "\u001B[40m";
72
+ Colors["BgRed"] = "\u001B[41m";
73
+ Colors["BgGreen"] = "\u001B[42m";
74
+ Colors["BgYellow"] = "\u001B[43m";
75
+ Colors["BgBlue"] = "\u001B[44m";
76
+ Colors["BgMagenta"] = "\u001B[45m";
77
+ Colors["BgCyan"] = "\u001B[46m";
78
+ Colors["BgWhite"] = "\u001B[47m";
79
+ Colors["BgGray"] = "\u001B[100m";
80
+ })(Colors || (exports.Colors = Colors = {}));
81
+ var Levels;
82
+ (function (Levels) {
83
+ Levels["ERROR"] = "ERROR";
84
+ Levels["WARN"] = "WARN";
85
+ Levels["INFO"] = "INFO";
86
+ Levels["DEBUG"] = "DEBUG";
87
+ Levels["SUCCESS"] = "SUCCESS";
88
+ })(Levels || (exports.Levels = Levels = {}));
89
+ class Console {
90
+ // --- MÉTODOS PRIVADOS PARA GERENCIAR A RENDERIZAÇÃO ---
91
+ /**
92
+ * Limpa todas as linhas dinâmicas da tela e as redesenha com o conteúdo atualizado.
93
+ * Observação: usamos lastRenderedLines para saber quantas linhas mover
94
+ * o cursor para cima (isso evita mover para cima demais quando uma nova
95
+ * linha foi registrada).
96
+ */
97
+ static redrawDynamicLines() {
98
+ const stream = process.stdout;
99
+ // Se anteriormente renderizamos N linhas, movemos o cursor para cima N
100
+ // para chegar ao topo do bloco dinâmico. Se N for 0, não movemos.
101
+ if (this.lastRenderedLines > 0) {
102
+ try {
103
+ node_readline_1.default.moveCursor(stream, 0, -this.lastRenderedLines);
104
+ }
105
+ catch (_e) {
106
+ // Em terminais estranhos a movimentação pode falhar — ignoramos.
107
+ }
108
+ }
109
+ // Posiciona no início da linha e limpa tudo abaixo (removendo o bloco antigo).
110
+ node_readline_1.default.cursorTo(stream, 0);
111
+ node_readline_1.default.clearScreenDown(stream);
112
+ // Reescreve as linhas com o conteúdo atualizado
113
+ if (this.activeLines.length > 0) {
114
+ stream.write(this.activeLines.map(l => l.content).join('\n') + '\n');
115
+ }
116
+ // Atualiza o contador de linhas que agora estão renderizadas.
117
+ this.lastRenderedLines = this.activeLines.length;
118
+ }
119
+ /**
120
+ * Envolve a escrita de texto estático (logs normais) para não interferir
121
+ * com as linhas dinâmicas.
122
+ */
123
+ static writeStatic(content) {
124
+ const stream = process.stdout;
125
+ // Se há um bloco dinâmico na tela, removemos (limpamos) ele antes de
126
+ // escrever o conteúdo estático — assim evitamos misturar a saída.
127
+ if (this.lastRenderedLines > 0) {
128
+ try {
129
+ node_readline_1.default.moveCursor(stream, 0, -this.lastRenderedLines);
130
+ }
131
+ catch (_e) { }
132
+ node_readline_1.default.cursorTo(stream, 0);
133
+ node_readline_1.default.clearScreenDown(stream);
134
+ }
135
+ // Garante que o conteúdo termine com quebra de linha.
136
+ if (!content.endsWith('\n'))
137
+ content += '\n';
138
+ stream.write(content);
139
+ // Depois de escrever o log estático, redesenhamos o bloco dinâmico abaixo dele.
140
+ if (this.activeLines.length > 0) {
141
+ stream.write(this.activeLines.map(l => l.content).join('\n') + '\n');
142
+ this.lastRenderedLines = this.activeLines.length;
143
+ }
144
+ else {
145
+ this.lastRenderedLines = 0;
146
+ }
147
+ }
148
+ // --- MÉTODOS CHAMADOS PELA CLASSE DynamicLine ---
149
+ static registerDynamicLine(id, content) {
150
+ // Adiciona a nova linha à lista de linhas ativas
151
+ this.activeLines.push({ id, content });
152
+ // Redesenha todo o bloco (usa lastRenderedLines internamente)
153
+ this.redrawDynamicLines();
154
+ }
155
+ static updateDynamicLine(id, newContent) {
156
+ const line = this.activeLines.find(l => l.id === id);
157
+ if (line) {
158
+ line.content = newContent;
159
+ this.redrawDynamicLines();
160
+ }
161
+ }
162
+ static endDynamicLine(id, finalContent) {
163
+ const lineIndex = this.activeLines.findIndex(l => l.id === id);
164
+ if (lineIndex > -1) {
165
+ // Remove a linha da lista de ativas.
166
+ this.activeLines.splice(lineIndex, 1);
167
+ // Escreve o conteúdo final como uma linha estática.
168
+ // writeStatic cuidará de limpar e redesenhar as linhas dinâmicas
169
+ // restantes no lugar certo.
170
+ this.writeStatic(finalContent + '\n');
171
+ }
172
+ }
173
+ // --- MÉTODOS DE LOG PÚBLICOS (MODIFICADOS) ---
174
+ static error(...args) { this.log(Levels.ERROR, ...args); }
175
+ static warn(...args) { this.log(Levels.WARN, ...args); }
176
+ static info(...args) { this.log(Levels.INFO, ...args); }
177
+ static success(...args) { this.log(Levels.SUCCESS, ...args); }
178
+ static debug(...args) { this.log(Levels.DEBUG, ...args); }
179
+ static logCustomLevel(levelName, without = true, color, ...args) {
180
+ if (without) {
181
+ this.logWithout(levelName, color, ...args);
182
+ }
183
+ else {
184
+ this.log(levelName, color, ...args);
185
+ }
186
+ }
187
+ static logWithout(level, colors, ...args) {
188
+ const color = colors ? colors : level === Levels.ERROR ? Colors.BgRed : level === Levels.WARN ? Colors.BgYellow : level === Levels.INFO ? Colors.BgMagenta : level === Levels.SUCCESS ? Colors.BgGreen : Colors.BgCyan;
189
+ let output = "";
190
+ for (const arg of args) {
191
+ let msg = (arg instanceof Error) ? arg.stack : (typeof arg === 'string') ? arg : JSON.stringify(arg, null, 2);
192
+ if (msg)
193
+ output += ` ${color} ${level} ${Colors.Reset} ${msg}\n`;
194
+ }
195
+ this.writeStatic(output);
196
+ }
197
+ static log(level, colors, ...args) {
198
+ const color = colors || level === Levels.ERROR ? Colors.BgRed : level === Levels.WARN ? Colors.BgYellow : level === Levels.INFO ? Colors.BgMagenta : level === Levels.SUCCESS ? Colors.BgGreen : Colors.BgCyan;
199
+ let output = "\n";
200
+ for (const arg of args) {
201
+ let msg = (arg instanceof Error) ? arg.stack : (typeof arg === 'string') ? arg : JSON.stringify(arg, null, 2);
202
+ if (msg)
203
+ output += ` ${color} ${level} ${Colors.Reset} ${msg}\n`;
204
+ }
205
+ this.writeStatic(output);
206
+ }
207
+ // --- OUTROS MÉTODOS ---
208
+ static async ask(question, defaultValue) {
209
+ // Garantimos que o bloco dinâmico atual seja temporariamente removido
210
+ // (redesenhado depois) para não poluir o prompt.
211
+ const stream = process.stdout;
212
+ if (this.lastRenderedLines > 0) {
213
+ try {
214
+ node_readline_1.default.moveCursor(stream, 0, -this.lastRenderedLines);
215
+ }
216
+ catch (_e) { }
217
+ node_readline_1.default.cursorTo(stream, 0);
218
+ node_readline_1.default.clearScreenDown(stream);
219
+ }
220
+ const readlineInterface = node_readline_1.default.createInterface({ input: process.stdin, output: process.stdout });
221
+ const coloredQuestion = ` ${Colors.FgMagenta}${question}${Colors.Reset}`;
222
+ const defaultValuePart = defaultValue ? ` [${Colors.Reset}${Colors.FgCyan}${defaultValue}${Colors.Reset}]` : '';
223
+ const fullPrompt = `${coloredQuestion}${defaultValuePart}:\n > `;
224
+ return new Promise(resolve => {
225
+ readlineInterface.question(fullPrompt, ans => {
226
+ readlineInterface.close();
227
+ const value = ans.trim();
228
+ // Redesenha as linhas dinâmicas após o prompt
229
+ this.redrawDynamicLines();
230
+ resolve(value === '' && defaultValue !== undefined ? defaultValue : value);
231
+ });
232
+ });
233
+ }
234
+ static async confirm(message, defaultYes = false) {
235
+ const suffix = defaultYes ? 'yes' : 'no';
236
+ while (true) {
237
+ const ans = (await this.ask(message + " (yes/no)", suffix)).toLowerCase();
238
+ if (!ans)
239
+ return defaultYes;
240
+ if (['y', 'yes'].includes(ans))
241
+ return true;
242
+ if (['n', 'no'].includes(ans))
243
+ return false;
244
+ this.warn('Resposta inválida, digite y ou n.');
245
+ }
246
+ }
247
+ static table(data) {
248
+ let rows;
249
+ if (Array.isArray(data)) {
250
+ rows = data.map(row => ({ Field: String(row.Field), Value: String(row.Value) }));
251
+ }
252
+ else {
253
+ rows = Object.entries(data).map(([Field, Value]) => ({ Field, Value: String(Value) }));
254
+ }
255
+ const fieldLen = Math.max(...rows.map(r => r.Field.length), 'Field'.length);
256
+ const valueLen = Math.max(...rows.map(r => r.Value.length), 'Value'.length);
257
+ const sep = `+${'-'.repeat(fieldLen + 2)}+${'-'.repeat(valueLen + 2)}+`;
258
+ let output = sep + '\n';
259
+ output += `| ${Colors.FgGreen}${'Field'.padEnd(fieldLen)}${Colors.Reset} | ${Colors.FgGreen}${'Value'.padEnd(valueLen)}${Colors.Reset} |\n`;
260
+ output += sep + '\n';
261
+ for (const row of rows) {
262
+ output += `| ${row.Field.padEnd(fieldLen)} | ${row.Value.padEnd(valueLen)} |\n`;
263
+ }
264
+ output += sep + '\n';
265
+ this.writeStatic(output);
266
+ }
267
+ static box(content, options) {
268
+ const defaultOptions = {
269
+ padding: 1,
270
+ margin: 1,
271
+ borderStyle: 'round',
272
+ borderColor: 'whiteBright',
273
+ titleAlignment: 'left',
274
+ };
275
+ const finalOptions = { ...defaultOptions, ...options };
276
+ const boxedContent = (0, boxen_1.default)(content, finalOptions);
277
+ this.writeStatic(boxedContent + '\n');
278
+ }
279
+ /**
280
+ * Cria e retorna um controlador para uma linha dinâmica no console.
281
+ * @param initialContent O conteúdo inicial a ser exibido.
282
+ * @returns Uma instância de DynamicLine para controlar a linha.
283
+ */
284
+ static dynamicLine(initialContent) {
285
+ return new DynamicLine(initialContent);
286
+ }
287
+ }
288
+ // Armazena o estado de todas as linhas dinâmicas ativas
289
+ Console.activeLines = [];
290
+ // Quantas linhas foram efetivamente renderizadas na última operação.
291
+ // Usamos esse contador para evitar off-by-one ao mover o cursor para
292
+ // redesenhar o bloco dinâmico.
293
+ Console.lastRenderedLines = 0;
294
+ exports.default = Console;
@@ -0,0 +1,180 @@
1
+ import { GenericRequest, GenericResponse, CookieOptions } from '../types/framework';
2
+ /**
3
+ * Abstração sobre a requisição HTTP de entrada.
4
+ * Funciona com qualquer framework web (Express, Fastify, etc.)
5
+ */
6
+ export declare class HightJSRequest {
7
+ /** A requisição genérica parseada pelo adapter */
8
+ private readonly _req;
9
+ constructor(req: GenericRequest);
10
+ private validateAndSanitizeRequest;
11
+ /**
12
+ * Retorna o método HTTP da requisição (GET, POST, etc.)
13
+ */
14
+ get method(): string;
15
+ /**
16
+ * Retorna a URL completa da requisição
17
+ */
18
+ get url(): string;
19
+ /**
20
+ * Retorna todos os headers da requisição
21
+ */
22
+ get headers(): Record<string, string | string[]>;
23
+ /**
24
+ * Retorna um header específico com validação
25
+ */
26
+ header(name: string): string | string[] | undefined;
27
+ /**
28
+ * Retorna todos os query parameters
29
+ */
30
+ get query(): Record<string, any>;
31
+ /**
32
+ * Retorna todos os parâmetros de rota
33
+ */
34
+ get params(): Record<string, string>;
35
+ /**
36
+ * Retorna todos os cookies
37
+ */
38
+ get cookies(): Record<string, string>;
39
+ /**
40
+ * Retorna um cookie específico com validação
41
+ */
42
+ cookie(name: string): string | undefined;
43
+ /**
44
+ * Retorna o corpo (body) da requisição, já parseado como JSON com validação
45
+ */
46
+ json<T = any>(): Promise<T>;
47
+ /**
48
+ * Retorna o corpo da requisição como texto
49
+ */
50
+ text(): Promise<string>;
51
+ /**
52
+ * Retorna o corpo da requisição como FormData (para uploads)
53
+ */
54
+ formData(): Promise<any>;
55
+ /**
56
+ * Retorna a requisição original do framework
57
+ */
58
+ get raw(): any;
59
+ /**
60
+ * Verifica se a requisição tem um content-type específico
61
+ */
62
+ is(type: string): boolean;
63
+ /**
64
+ * Verifica se a requisição é AJAX/XHR
65
+ */
66
+ get isAjax(): boolean;
67
+ /**
68
+ * Retorna o IP do cliente com validação melhorada
69
+ */
70
+ get ip(): string;
71
+ private isValidIP;
72
+ /**
73
+ * Retorna o User-Agent
74
+ */
75
+ get userAgent(): string | undefined;
76
+ }
77
+ /**
78
+ * Abstração para construir a resposta HTTP.
79
+ * Funciona com qualquer framework web (Express, Fastify, etc.)
80
+ */
81
+ export declare class HightJSResponse {
82
+ private _status;
83
+ private _headers;
84
+ private _cookies;
85
+ private _body;
86
+ private _sent;
87
+ /**
88
+ * Define o status HTTP da resposta
89
+ */
90
+ status(code: number): HightJSResponse;
91
+ /**
92
+ * Define um header da resposta
93
+ */
94
+ header(name: string, value: string): HightJSResponse;
95
+ /**
96
+ * Define múltiplos headers
97
+ */
98
+ headers(headers: Record<string, string>): HightJSResponse;
99
+ /**
100
+ * Define um cookie
101
+ */
102
+ cookie(name: string, value: string, options?: CookieOptions): HightJSResponse;
103
+ /**
104
+ * Remove um cookie
105
+ */
106
+ clearCookie(name: string, options?: CookieOptions): HightJSResponse;
107
+ /**
108
+ * Envia resposta JSON
109
+ */
110
+ json(data: any): HightJSResponse;
111
+ /**
112
+ * Envia resposta de texto
113
+ */
114
+ text(data: string): HightJSResponse;
115
+ /**
116
+ * Envia resposta HTML
117
+ */
118
+ html(data: string): HightJSResponse;
119
+ /**
120
+ * Envia qualquer tipo de dados
121
+ */
122
+ send(data: any): HightJSResponse;
123
+ /**
124
+ * Redireciona para uma URL
125
+ */
126
+ redirect(url: string, status?: number): HightJSResponse;
127
+ /**
128
+ * Método interno para aplicar a resposta ao objeto de resposta do framework
129
+ */
130
+ _applyTo(res: GenericResponse): void;
131
+ /**
132
+ * Método de compatibilidade com versão anterior (Express)
133
+ */
134
+ _send(res: any): void;
135
+ /**
136
+ * Cria uma resposta JSON
137
+ */
138
+ static json(data: any, options?: {
139
+ status?: number;
140
+ headers?: Record<string, string>;
141
+ }): HightJSResponse;
142
+ /**
143
+ * Cria uma resposta de texto
144
+ */
145
+ static text(data: string, options?: {
146
+ status?: number;
147
+ headers?: Record<string, string>;
148
+ }): HightJSResponse;
149
+ /**
150
+ * Cria uma resposta HTML
151
+ */
152
+ static html(data: string, options?: {
153
+ status?: number;
154
+ headers?: Record<string, string>;
155
+ }): HightJSResponse;
156
+ /**
157
+ * Cria um redirecionamento
158
+ */
159
+ static redirect(url: string, status?: number): HightJSResponse;
160
+ /**
161
+ * Cria uma resposta 404
162
+ */
163
+ static notFound(message?: string): HightJSResponse;
164
+ /**
165
+ * Cria uma resposta 500
166
+ */
167
+ static error(message?: string): HightJSResponse;
168
+ /**
169
+ * Cria uma resposta 400
170
+ */
171
+ static badRequest(message?: string): HightJSResponse;
172
+ /**
173
+ * Cria uma resposta 401
174
+ */
175
+ static unauthorized(message?: string): HightJSResponse;
176
+ /**
177
+ * Cria uma resposta 403
178
+ */
179
+ static forbidden(message?: string): HightJSResponse;
180
+ }