hightjs 0.5.3 → 0.5.5
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/dist/adapters/express.d.ts +7 -0
- package/dist/adapters/express.js +63 -0
- package/dist/adapters/factory.d.ts +23 -0
- package/dist/adapters/factory.js +122 -0
- package/dist/adapters/fastify.d.ts +25 -0
- package/dist/adapters/fastify.js +61 -0
- package/dist/adapters/native.d.ts +8 -0
- package/dist/adapters/native.js +198 -0
- package/dist/api/console.d.ts +94 -0
- package/dist/api/console.js +294 -0
- package/dist/api/http.d.ts +180 -0
- package/dist/api/http.js +469 -0
- package/dist/bin/hightjs.d.ts +2 -0
- package/dist/bin/hightjs.js +214 -0
- package/dist/builder.d.ts +32 -0
- package/dist/builder.js +581 -0
- package/dist/client/DefaultNotFound.d.ts +1 -0
- package/dist/client/DefaultNotFound.js +79 -0
- package/dist/client/client.d.ts +3 -0
- package/dist/client/client.js +24 -0
- package/dist/client/clientRouter.d.ts +58 -0
- package/dist/client/clientRouter.js +132 -0
- package/dist/client/entry.client.d.ts +1 -0
- package/dist/client/entry.client.js +455 -0
- package/dist/components/Link.d.ts +7 -0
- package/dist/components/Link.js +13 -0
- package/dist/global/global.d.ts +117 -0
- package/dist/global/global.js +17 -0
- package/dist/helpers.d.ts +20 -0
- package/dist/helpers.js +583 -0
- package/dist/hotReload.d.ts +32 -0
- package/dist/hotReload.js +545 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +494 -0
- package/dist/loaders.d.ts +1 -0
- package/dist/loaders.js +46 -0
- package/dist/renderer.d.ts +14 -0
- package/dist/renderer.js +380 -0
- package/dist/router.d.ts +101 -0
- package/dist/router.js +659 -0
- package/dist/types/framework.d.ts +37 -0
- package/dist/types/framework.js +2 -0
- package/dist/types.d.ts +192 -0
- package/dist/types.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Request as ExpressRequest, Response as ExpressResponse } from 'express';
|
|
2
|
+
import { GenericRequest, GenericResponse, FrameworkAdapter } from '../types/framework';
|
|
3
|
+
export declare class ExpressAdapter implements FrameworkAdapter {
|
|
4
|
+
type: "express";
|
|
5
|
+
parseRequest(req: ExpressRequest): GenericRequest;
|
|
6
|
+
createResponse(res: ExpressResponse): GenericResponse;
|
|
7
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ExpressAdapter = void 0;
|
|
4
|
+
class ExpressAdapter {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.type = 'express';
|
|
7
|
+
}
|
|
8
|
+
parseRequest(req) {
|
|
9
|
+
return {
|
|
10
|
+
method: req.method,
|
|
11
|
+
url: req.url,
|
|
12
|
+
headers: req.headers,
|
|
13
|
+
body: req.body,
|
|
14
|
+
query: req.query,
|
|
15
|
+
params: req.params,
|
|
16
|
+
cookies: req.cookies || {},
|
|
17
|
+
raw: req,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
createResponse(res) {
|
|
21
|
+
return new ExpressResponseWrapper(res);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
exports.ExpressAdapter = ExpressAdapter;
|
|
25
|
+
class ExpressResponseWrapper {
|
|
26
|
+
constructor(res) {
|
|
27
|
+
this.res = res;
|
|
28
|
+
}
|
|
29
|
+
get raw() {
|
|
30
|
+
return this.res;
|
|
31
|
+
}
|
|
32
|
+
status(code) {
|
|
33
|
+
this.res.status(code);
|
|
34
|
+
return this;
|
|
35
|
+
}
|
|
36
|
+
header(name, value) {
|
|
37
|
+
this.res.setHeader(name, value);
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
cookie(name, value, options) {
|
|
41
|
+
this.res.cookie(name, value, options || {});
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
clearCookie(name, options) {
|
|
45
|
+
// Filter out the deprecated 'expires' option to avoid Express deprecation warning
|
|
46
|
+
const { expires, ...filteredOptions } = options || {};
|
|
47
|
+
this.res.clearCookie(name, filteredOptions);
|
|
48
|
+
return this;
|
|
49
|
+
}
|
|
50
|
+
json(data) {
|
|
51
|
+
this.res.json(data);
|
|
52
|
+
}
|
|
53
|
+
text(data) {
|
|
54
|
+
this.res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
|
55
|
+
this.res.send(data);
|
|
56
|
+
}
|
|
57
|
+
send(data) {
|
|
58
|
+
this.res.send(data);
|
|
59
|
+
}
|
|
60
|
+
redirect(url) {
|
|
61
|
+
this.res.redirect(url);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { FrameworkAdapter } from '../types/framework';
|
|
2
|
+
/**
|
|
3
|
+
* Factory para criar o adapter correto baseado no framework detectado
|
|
4
|
+
*/
|
|
5
|
+
export declare class FrameworkAdapterFactory {
|
|
6
|
+
private static adapter;
|
|
7
|
+
/**
|
|
8
|
+
* Detecta automaticamente o framework baseado na requisição/resposta
|
|
9
|
+
*/
|
|
10
|
+
static detectFramework(req: any, res: any): FrameworkAdapter;
|
|
11
|
+
/**
|
|
12
|
+
* Força o uso de um framework específico
|
|
13
|
+
*/
|
|
14
|
+
static setFramework(framework: 'express' | 'fastify' | 'native'): void;
|
|
15
|
+
/**
|
|
16
|
+
* Reset do adapter (útil para testes)
|
|
17
|
+
*/
|
|
18
|
+
static reset(): void;
|
|
19
|
+
/**
|
|
20
|
+
* Retorna o adapter atual (se já foi detectado)
|
|
21
|
+
*/
|
|
22
|
+
static getCurrentAdapter(): FrameworkAdapter | null;
|
|
23
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.FrameworkAdapterFactory = void 0;
|
|
37
|
+
const express_1 = require("./express");
|
|
38
|
+
const fastify_1 = require("./fastify");
|
|
39
|
+
const native_1 = require("./native");
|
|
40
|
+
const console_1 = __importStar(require("../api/console"));
|
|
41
|
+
/**
|
|
42
|
+
* Factory para criar o adapter correto baseado no framework detectado
|
|
43
|
+
*/
|
|
44
|
+
class FrameworkAdapterFactory {
|
|
45
|
+
/**
|
|
46
|
+
* Detecta automaticamente o framework baseado na requisição/resposta
|
|
47
|
+
*/
|
|
48
|
+
static detectFramework(req, res) {
|
|
49
|
+
// Se já detectamos antes, retorna o mesmo adapter
|
|
50
|
+
if (this.adapter) {
|
|
51
|
+
return this.adapter;
|
|
52
|
+
}
|
|
53
|
+
const msg = console_1.default.dynamicLine(` ${console_1.Colors.FgYellow}● ${console_1.Colors.Reset}Detecting web framework...`);
|
|
54
|
+
// Detecta Express
|
|
55
|
+
if (req.app && req.route && res.locals !== undefined) {
|
|
56
|
+
msg.end(` ${console_1.Colors.FgGreen}● ${console_1.Colors.Reset}Framework detected: Express`);
|
|
57
|
+
this.adapter = new express_1.ExpressAdapter();
|
|
58
|
+
return this.adapter;
|
|
59
|
+
}
|
|
60
|
+
// Detecta Fastify
|
|
61
|
+
if (req.server && req.routerPath !== undefined && res.request) {
|
|
62
|
+
msg.end(` ${console_1.Colors.FgGreen}● ${console_1.Colors.Reset}Framework detected: Fastify`);
|
|
63
|
+
this.adapter = new fastify_1.FastifyAdapter();
|
|
64
|
+
return this.adapter;
|
|
65
|
+
}
|
|
66
|
+
// Detecta HTTP nativo do Node.js
|
|
67
|
+
if (req.method !== undefined && req.url !== undefined && req.headers !== undefined &&
|
|
68
|
+
res.statusCode !== undefined && res.setHeader !== undefined && res.end !== undefined) {
|
|
69
|
+
msg.end(` ${console_1.Colors.FgGreen}● ${console_1.Colors.Reset}Framework detected: HightJS Native (HTTP)`);
|
|
70
|
+
this.adapter = new native_1.NativeAdapter();
|
|
71
|
+
return this.adapter;
|
|
72
|
+
}
|
|
73
|
+
// Fallback mais específico para Express
|
|
74
|
+
if (res.status && res.send && res.json && res.cookie) {
|
|
75
|
+
msg.end(` ${console_1.Colors.FgGreen}● ${console_1.Colors.Reset}Framework detected: Express (fallback)`);
|
|
76
|
+
this.adapter = new express_1.ExpressAdapter();
|
|
77
|
+
return this.adapter;
|
|
78
|
+
}
|
|
79
|
+
// Fallback mais específico para Fastify
|
|
80
|
+
if (res.code && res.send && res.type && res.setCookie) {
|
|
81
|
+
msg.end(` ${console_1.Colors.FgGreen}● ${console_1.Colors.Reset}Framework detected: Fastify (fallback)`);
|
|
82
|
+
this.adapter = new fastify_1.FastifyAdapter();
|
|
83
|
+
return this.adapter;
|
|
84
|
+
}
|
|
85
|
+
// Default para HightJS Native se não conseguir detectar
|
|
86
|
+
msg.end(` ${console_1.Colors.FgYellow}● ${console_1.Colors.Reset}Unable to detect framework. Using HightJS Native as default.`);
|
|
87
|
+
this.adapter = new native_1.NativeAdapter();
|
|
88
|
+
return this.adapter;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Força o uso de um framework específico
|
|
92
|
+
*/
|
|
93
|
+
static setFramework(framework) {
|
|
94
|
+
switch (framework) {
|
|
95
|
+
case 'express':
|
|
96
|
+
this.adapter = new express_1.ExpressAdapter();
|
|
97
|
+
break;
|
|
98
|
+
case 'fastify':
|
|
99
|
+
this.adapter = new fastify_1.FastifyAdapter();
|
|
100
|
+
break;
|
|
101
|
+
case 'native':
|
|
102
|
+
this.adapter = new native_1.NativeAdapter();
|
|
103
|
+
break;
|
|
104
|
+
default:
|
|
105
|
+
throw new Error(`Unsupported framework: ${framework}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Reset do adapter (útil para testes)
|
|
110
|
+
*/
|
|
111
|
+
static reset() {
|
|
112
|
+
this.adapter = null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Retorna o adapter atual (se já foi detectado)
|
|
116
|
+
*/
|
|
117
|
+
static getCurrentAdapter() {
|
|
118
|
+
return this.adapter;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
exports.FrameworkAdapterFactory = FrameworkAdapterFactory;
|
|
122
|
+
FrameworkAdapterFactory.adapter = null;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
interface FastifyRequest {
|
|
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
|
+
}
|
|
10
|
+
interface FastifyReply {
|
|
11
|
+
status(code: number): FastifyReply;
|
|
12
|
+
header(name: string, value: string): FastifyReply;
|
|
13
|
+
setCookie(name: string, value: string, options?: any): FastifyReply;
|
|
14
|
+
clearCookie(name: string, options?: any): FastifyReply;
|
|
15
|
+
type(contentType: string): FastifyReply;
|
|
16
|
+
send(data: any): void;
|
|
17
|
+
redirect(url: string): void;
|
|
18
|
+
}
|
|
19
|
+
import { GenericRequest, GenericResponse, FrameworkAdapter } from '../types/framework';
|
|
20
|
+
export declare class FastifyAdapter implements FrameworkAdapter {
|
|
21
|
+
type: "fastify";
|
|
22
|
+
parseRequest(req: FastifyRequest): GenericRequest;
|
|
23
|
+
createResponse(reply: FastifyReply): GenericResponse;
|
|
24
|
+
}
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FastifyAdapter = void 0;
|
|
4
|
+
class FastifyAdapter {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.type = 'fastify';
|
|
7
|
+
}
|
|
8
|
+
parseRequest(req) {
|
|
9
|
+
return {
|
|
10
|
+
method: req.method,
|
|
11
|
+
url: req.url,
|
|
12
|
+
headers: req.headers,
|
|
13
|
+
body: req.body,
|
|
14
|
+
query: req.query,
|
|
15
|
+
params: req.params,
|
|
16
|
+
cookies: req.cookies || {},
|
|
17
|
+
raw: req
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
createResponse(reply) {
|
|
21
|
+
return new FastifyResponseWrapper(reply);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
exports.FastifyAdapter = FastifyAdapter;
|
|
25
|
+
class FastifyResponseWrapper {
|
|
26
|
+
constructor(reply) {
|
|
27
|
+
this.reply = reply;
|
|
28
|
+
}
|
|
29
|
+
get raw() {
|
|
30
|
+
return this.reply;
|
|
31
|
+
}
|
|
32
|
+
status(code) {
|
|
33
|
+
this.reply.status(code);
|
|
34
|
+
return this;
|
|
35
|
+
}
|
|
36
|
+
header(name, value) {
|
|
37
|
+
this.reply.header(name, value);
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
cookie(name, value, options) {
|
|
41
|
+
this.reply.setCookie(name, value, options);
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
clearCookie(name, options) {
|
|
45
|
+
this.reply.clearCookie(name, options);
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
json(data) {
|
|
49
|
+
this.reply.send(data);
|
|
50
|
+
}
|
|
51
|
+
text(data) {
|
|
52
|
+
this.reply.type('text/plain; charset=utf-8');
|
|
53
|
+
this.reply.send(data);
|
|
54
|
+
}
|
|
55
|
+
send(data) {
|
|
56
|
+
this.reply.send(data);
|
|
57
|
+
}
|
|
58
|
+
redirect(url) {
|
|
59
|
+
this.reply.redirect(url);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'http';
|
|
2
|
+
import { GenericRequest, GenericResponse, FrameworkAdapter } from '../types/framework';
|
|
3
|
+
export declare class NativeAdapter implements FrameworkAdapter {
|
|
4
|
+
type: "native";
|
|
5
|
+
parseRequest(req: IncomingMessage): GenericRequest;
|
|
6
|
+
createResponse(res: ServerResponse): GenericResponse;
|
|
7
|
+
private parseCookies;
|
|
8
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NativeAdapter = void 0;
|
|
4
|
+
const url_1 = require("url");
|
|
5
|
+
// --- Funções Auxiliares de Segurança ---
|
|
6
|
+
/**
|
|
7
|
+
* Remove caracteres de quebra de linha (\r, \n) de uma string para prevenir
|
|
8
|
+
* ataques de HTTP Header Injection (CRLF Injection).
|
|
9
|
+
* @param value O valor a ser sanitizado.
|
|
10
|
+
* @returns A string sanitizada.
|
|
11
|
+
*/
|
|
12
|
+
function sanitizeHeaderValue(value) {
|
|
13
|
+
return String(value).replace(/[\r\n]/g, '');
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Valida se o nome de um cookie contém apenas caracteres permitidos pela RFC 6265.
|
|
17
|
+
* Isso previne a criação de cookies com nomes inválidos ou maliciosos.
|
|
18
|
+
* @param name O nome do cookie a ser validado.
|
|
19
|
+
* @returns `true` se o nome for válido, `false` caso contrário.
|
|
20
|
+
*/
|
|
21
|
+
function isValidCookieName(name) {
|
|
22
|
+
// A RFC 6265 define 'token' como 1 ou mais caracteres que não são controle nem separadores.
|
|
23
|
+
// Separadores: ( ) < > @ , ; : \ " / [ ] ? = { }
|
|
24
|
+
const validCookieNameRegex = /^[a-zA-Z0-9!#$%&'*+-.^_`|~]+$/;
|
|
25
|
+
return validCookieNameRegex.test(name);
|
|
26
|
+
}
|
|
27
|
+
class NativeAdapter {
|
|
28
|
+
constructor() {
|
|
29
|
+
this.type = 'native';
|
|
30
|
+
}
|
|
31
|
+
parseRequest(req) {
|
|
32
|
+
const url = (0, url_1.parse)(req.url || '', true);
|
|
33
|
+
return {
|
|
34
|
+
method: req.method || 'GET',
|
|
35
|
+
url: req.url || '/',
|
|
36
|
+
headers: req.headers,
|
|
37
|
+
// Adicionado fallback para null para maior segurança caso o body parser não tenha rodado.
|
|
38
|
+
body: req.body ?? null,
|
|
39
|
+
// Tipo mais específico para a query.
|
|
40
|
+
query: url.query,
|
|
41
|
+
params: {}, // Será preenchido pelo roteador
|
|
42
|
+
cookies: this.parseCookies(req.headers.cookie || ''),
|
|
43
|
+
raw: req
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
createResponse(res) {
|
|
47
|
+
return new NativeResponseWrapper(res);
|
|
48
|
+
}
|
|
49
|
+
parseCookies(cookieHeader) {
|
|
50
|
+
const cookies = {};
|
|
51
|
+
if (!cookieHeader)
|
|
52
|
+
return cookies;
|
|
53
|
+
cookieHeader.split(';').forEach(cookie => {
|
|
54
|
+
const [name, ...rest] = cookie.trim().split('=');
|
|
55
|
+
if (name && rest.length > 0) {
|
|
56
|
+
try {
|
|
57
|
+
// Tenta decodificar o valor do cookie.
|
|
58
|
+
cookies[name] = decodeURIComponent(rest.join('='));
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
// Prevenção de crash: Ignora cookies com valores malformados (e.g., URI inválida).
|
|
62
|
+
console.error(`Warning: Malformed cookie with name "${name}" was ignored.`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
return cookies;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
exports.NativeAdapter = NativeAdapter;
|
|
70
|
+
class NativeResponseWrapper {
|
|
71
|
+
constructor(res) {
|
|
72
|
+
this.res = res;
|
|
73
|
+
this.statusCode = 200;
|
|
74
|
+
this.headers = {};
|
|
75
|
+
this.cookiesToSet = []; // Array para lidar corretamente com múltiplos cookies.
|
|
76
|
+
this.finished = false;
|
|
77
|
+
}
|
|
78
|
+
get raw() {
|
|
79
|
+
return this.res;
|
|
80
|
+
}
|
|
81
|
+
status(code) {
|
|
82
|
+
this.statusCode = code;
|
|
83
|
+
return this;
|
|
84
|
+
}
|
|
85
|
+
header(name, value) {
|
|
86
|
+
// Medida de segurança CRÍTICA: Previne HTTP Header Injection (CRLF Injection).
|
|
87
|
+
// Sanitiza tanto o nome quanto o valor do header para remover quebras de linha.
|
|
88
|
+
const sanitizedName = sanitizeHeaderValue(name);
|
|
89
|
+
const sanitizedValue = sanitizeHeaderValue(value);
|
|
90
|
+
if (name !== sanitizedName || String(value) !== sanitizedValue) {
|
|
91
|
+
console.warn(`Warning: Potential HTTP Header Injection attempt detected and sanitized. Original header: "${name}"`);
|
|
92
|
+
}
|
|
93
|
+
this.headers[sanitizedName] = sanitizedValue;
|
|
94
|
+
return this;
|
|
95
|
+
}
|
|
96
|
+
cookie(name, value, options) {
|
|
97
|
+
// Medida de segurança: Valida o nome do cookie.
|
|
98
|
+
if (!isValidCookieName(name)) {
|
|
99
|
+
console.error(`Error: Invalid cookie name "${name}". The cookie will not be set.`);
|
|
100
|
+
return this;
|
|
101
|
+
}
|
|
102
|
+
let cookieString = `${name}=${encodeURIComponent(value)}`;
|
|
103
|
+
if (options) {
|
|
104
|
+
// Sanitiza as opções que são strings para prevenir Header Injection.
|
|
105
|
+
if (options.domain)
|
|
106
|
+
cookieString += `; Domain=${sanitizeHeaderValue(options.domain)}`;
|
|
107
|
+
if (options.path)
|
|
108
|
+
cookieString += `; Path=${sanitizeHeaderValue(options.path)}`;
|
|
109
|
+
if (options.expires)
|
|
110
|
+
cookieString += `; Expires=${options.expires.toUTCString()}`;
|
|
111
|
+
if (options.maxAge)
|
|
112
|
+
cookieString += `; Max-Age=${options.maxAge}`;
|
|
113
|
+
if (options.httpOnly)
|
|
114
|
+
cookieString += '; HttpOnly';
|
|
115
|
+
if (options.secure)
|
|
116
|
+
cookieString += '; Secure';
|
|
117
|
+
if (options.sameSite) {
|
|
118
|
+
const sameSiteValue = typeof options.sameSite === 'boolean' ? 'Strict' : options.sameSite;
|
|
119
|
+
cookieString += `; SameSite=${sanitizeHeaderValue(sameSiteValue)}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
this.cookiesToSet.push(cookieString);
|
|
123
|
+
return this;
|
|
124
|
+
}
|
|
125
|
+
clearCookie(name, options) {
|
|
126
|
+
const clearOptions = { ...options, expires: new Date(0), maxAge: 0 };
|
|
127
|
+
return this.cookie(name, '', clearOptions);
|
|
128
|
+
}
|
|
129
|
+
writeHeaders() {
|
|
130
|
+
if (this.finished)
|
|
131
|
+
return;
|
|
132
|
+
this.res.statusCode = this.statusCode;
|
|
133
|
+
Object.entries(this.headers).forEach(([name, value]) => {
|
|
134
|
+
this.res.setHeader(name, value);
|
|
135
|
+
});
|
|
136
|
+
// CORREÇÃO: Envia múltiplos cookies corretamente como headers 'Set-Cookie' separados.
|
|
137
|
+
// O método antigo de juntar com vírgula estava incorreto.
|
|
138
|
+
if (this.cookiesToSet.length > 0) {
|
|
139
|
+
this.res.setHeader('Set-Cookie', this.cookiesToSet);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
json(data) {
|
|
143
|
+
if (this.finished)
|
|
144
|
+
return;
|
|
145
|
+
this.header('Content-Type', 'application/json; charset=utf-8');
|
|
146
|
+
this.writeHeaders();
|
|
147
|
+
const jsonString = JSON.stringify(data);
|
|
148
|
+
this.res.end(jsonString);
|
|
149
|
+
this.finished = true;
|
|
150
|
+
}
|
|
151
|
+
text(data) {
|
|
152
|
+
if (this.finished)
|
|
153
|
+
return;
|
|
154
|
+
this.header('Content-Type', 'text/plain; charset=utf-8');
|
|
155
|
+
this.writeHeaders();
|
|
156
|
+
this.res.end(data);
|
|
157
|
+
this.finished = true;
|
|
158
|
+
}
|
|
159
|
+
send(data) {
|
|
160
|
+
if (this.finished)
|
|
161
|
+
return;
|
|
162
|
+
const existingContentType = this.headers['Content-Type'];
|
|
163
|
+
if (typeof data === 'string') {
|
|
164
|
+
if (!existingContentType) {
|
|
165
|
+
this.header('Content-Type', 'text/plain; charset=utf-8');
|
|
166
|
+
}
|
|
167
|
+
this.writeHeaders();
|
|
168
|
+
this.res.end(data);
|
|
169
|
+
}
|
|
170
|
+
else if (Buffer.isBuffer(data)) {
|
|
171
|
+
this.writeHeaders();
|
|
172
|
+
this.res.end(data);
|
|
173
|
+
}
|
|
174
|
+
else if (data !== null && typeof data === 'object') {
|
|
175
|
+
this.json(data); // Reutiliza o método json para consistência
|
|
176
|
+
return; // O método json já finaliza a resposta
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
if (!existingContentType) {
|
|
180
|
+
this.header('Content-Type', 'text/plain; charset=utf-8');
|
|
181
|
+
}
|
|
182
|
+
this.writeHeaders();
|
|
183
|
+
this.res.end(String(data));
|
|
184
|
+
}
|
|
185
|
+
this.finished = true;
|
|
186
|
+
}
|
|
187
|
+
redirect(url) {
|
|
188
|
+
if (this.finished)
|
|
189
|
+
return;
|
|
190
|
+
this.status(302);
|
|
191
|
+
// A sanitização no método .header() previne que um URL manipulado
|
|
192
|
+
// cause um ataque de Open Redirect via Header Injection.
|
|
193
|
+
this.header('Location', url);
|
|
194
|
+
this.writeHeaders();
|
|
195
|
+
this.res.end();
|
|
196
|
+
this.finished = true;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Options as BoxenOptions } from 'boxen';
|
|
2
|
+
/**
|
|
3
|
+
* Um "handle" para uma linha dinâmica. As instâncias desta classe
|
|
4
|
+
* são retornadas por `Console.dynamicLine()` e usadas para controlar
|
|
5
|
+
* o conteúdo da linha.
|
|
6
|
+
*/
|
|
7
|
+
export declare class DynamicLine {
|
|
8
|
+
private readonly _id;
|
|
9
|
+
constructor(initialContent: string);
|
|
10
|
+
/**
|
|
11
|
+
* Atualiza o conteúdo da linha no console.
|
|
12
|
+
* @param newContent O novo texto a ser exibido.
|
|
13
|
+
*/
|
|
14
|
+
update(newContent: string): void;
|
|
15
|
+
/**
|
|
16
|
+
* Finaliza a linha, opcionalmente com um texto final, e a torna estática.
|
|
17
|
+
* @param finalContent O texto final a ser exibido.
|
|
18
|
+
*/
|
|
19
|
+
end(finalContent: string): void;
|
|
20
|
+
}
|
|
21
|
+
export declare enum Colors {
|
|
22
|
+
Reset = "\u001B[0m",
|
|
23
|
+
Bright = "\u001B[1m",
|
|
24
|
+
Dim = "\u001B[2m",
|
|
25
|
+
Underscore = "\u001B[4m",
|
|
26
|
+
Blink = "\u001B[5m",
|
|
27
|
+
Reverse = "\u001B[7m",
|
|
28
|
+
Hidden = "\u001B[8m",
|
|
29
|
+
FgBlack = "\u001B[30m",
|
|
30
|
+
FgRed = "\u001B[31m",
|
|
31
|
+
FgGreen = "\u001B[32m",
|
|
32
|
+
FgYellow = "\u001B[33m",
|
|
33
|
+
FgBlue = "\u001B[34m",
|
|
34
|
+
FgMagenta = "\u001B[35m",
|
|
35
|
+
FgCyan = "\u001B[36m",
|
|
36
|
+
FgWhite = "\u001B[37m",
|
|
37
|
+
FgGray = "\u001B[90m",// ← adicionado
|
|
38
|
+
BgBlack = "\u001B[40m",
|
|
39
|
+
BgRed = "\u001B[41m",
|
|
40
|
+
BgGreen = "\u001B[42m",
|
|
41
|
+
BgYellow = "\u001B[43m",
|
|
42
|
+
BgBlue = "\u001B[44m",
|
|
43
|
+
BgMagenta = "\u001B[45m",
|
|
44
|
+
BgCyan = "\u001B[46m",
|
|
45
|
+
BgWhite = "\u001B[47m",
|
|
46
|
+
BgGray = "\u001B[100m"
|
|
47
|
+
}
|
|
48
|
+
export declare enum Levels {
|
|
49
|
+
ERROR = "ERROR",
|
|
50
|
+
WARN = "WARN",
|
|
51
|
+
INFO = "INFO",
|
|
52
|
+
DEBUG = "DEBUG",
|
|
53
|
+
SUCCESS = "SUCCESS"
|
|
54
|
+
}
|
|
55
|
+
export default class Console {
|
|
56
|
+
private static activeLines;
|
|
57
|
+
private static lastRenderedLines;
|
|
58
|
+
/**
|
|
59
|
+
* Limpa todas as linhas dinâmicas da tela e as redesenha com o conteúdo atualizado.
|
|
60
|
+
* Observação: usamos lastRenderedLines para saber quantas linhas mover
|
|
61
|
+
* o cursor para cima (isso evita mover para cima demais quando uma nova
|
|
62
|
+
* linha foi registrada).
|
|
63
|
+
*/
|
|
64
|
+
private static redrawDynamicLines;
|
|
65
|
+
/**
|
|
66
|
+
* Envolve a escrita de texto estático (logs normais) para não interferir
|
|
67
|
+
* com as linhas dinâmicas.
|
|
68
|
+
*/
|
|
69
|
+
private static writeStatic;
|
|
70
|
+
private static registerDynamicLine;
|
|
71
|
+
private static updateDynamicLine;
|
|
72
|
+
private static endDynamicLine;
|
|
73
|
+
static error(...args: any[]): void;
|
|
74
|
+
static warn(...args: any[]): void;
|
|
75
|
+
static info(...args: any[]): void;
|
|
76
|
+
static success(...args: any[]): void;
|
|
77
|
+
static debug(...args: any[]): void;
|
|
78
|
+
static logCustomLevel(levelName: string, without?: boolean, color?: Colors, ...args: any[]): void;
|
|
79
|
+
static logWithout(level: Levels, colors?: Colors, ...args: any[]): void;
|
|
80
|
+
static log(level: Levels, colors?: Colors, ...args: any[]): void;
|
|
81
|
+
static ask(question: string, defaultValue?: string): Promise<string>;
|
|
82
|
+
static confirm(message: string, defaultYes?: boolean): Promise<boolean>;
|
|
83
|
+
static table(data: Record<string, any> | Array<{
|
|
84
|
+
Field: string;
|
|
85
|
+
Value: any;
|
|
86
|
+
}>): void;
|
|
87
|
+
static box(content: string, options?: BoxenOptions): void;
|
|
88
|
+
/**
|
|
89
|
+
* Cria e retorna um controlador para uma linha dinâmica no console.
|
|
90
|
+
* @param initialContent O conteúdo inicial a ser exibido.
|
|
91
|
+
* @returns Uma instância de DynamicLine para controlar a linha.
|
|
92
|
+
*/
|
|
93
|
+
static dynamicLine(initialContent: string): DynamicLine;
|
|
94
|
+
}
|