nyte 1.0.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 (78) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +59 -0
  3. package/dist/adapters/express.d.ts +7 -0
  4. package/dist/adapters/express.js +63 -0
  5. package/dist/adapters/factory.d.ts +23 -0
  6. package/dist/adapters/factory.js +121 -0
  7. package/dist/adapters/fastify.d.ts +25 -0
  8. package/dist/adapters/fastify.js +61 -0
  9. package/dist/adapters/native.d.ts +8 -0
  10. package/dist/adapters/native.js +200 -0
  11. package/dist/api/console.d.ts +81 -0
  12. package/dist/api/console.js +318 -0
  13. package/dist/api/http.d.ts +180 -0
  14. package/dist/api/http.js +469 -0
  15. package/dist/bin/nytejs.d.ts +2 -0
  16. package/dist/bin/nytejs.js +277 -0
  17. package/dist/builder.d.ts +32 -0
  18. package/dist/builder.js +634 -0
  19. package/dist/client/DefaultNotFound.d.ts +1 -0
  20. package/dist/client/DefaultNotFound.js +79 -0
  21. package/dist/client/client.d.ts +4 -0
  22. package/dist/client/client.js +27 -0
  23. package/dist/client/clientRouter.d.ts +58 -0
  24. package/dist/client/clientRouter.js +132 -0
  25. package/dist/client/entry.client.d.ts +1 -0
  26. package/dist/client/entry.client.js +455 -0
  27. package/dist/client/rpc.d.ts +8 -0
  28. package/dist/client/rpc.js +97 -0
  29. package/dist/components/Link.d.ts +7 -0
  30. package/dist/components/Link.js +13 -0
  31. package/dist/global/global.d.ts +117 -0
  32. package/dist/global/global.js +17 -0
  33. package/dist/helpers.d.ts +20 -0
  34. package/dist/helpers.js +604 -0
  35. package/dist/hotReload.d.ts +32 -0
  36. package/dist/hotReload.js +545 -0
  37. package/dist/index.d.ts +18 -0
  38. package/dist/index.js +515 -0
  39. package/dist/loaders.d.ts +1 -0
  40. package/dist/loaders.js +138 -0
  41. package/dist/renderer.d.ts +14 -0
  42. package/dist/renderer.js +380 -0
  43. package/dist/router.d.ts +101 -0
  44. package/dist/router.js +659 -0
  45. package/dist/rpc/server.d.ts +11 -0
  46. package/dist/rpc/server.js +166 -0
  47. package/dist/rpc/types.d.ts +22 -0
  48. package/dist/rpc/types.js +20 -0
  49. package/dist/types/framework.d.ts +37 -0
  50. package/dist/types/framework.js +2 -0
  51. package/dist/types.d.ts +218 -0
  52. package/dist/types.js +2 -0
  53. package/package.json +87 -0
  54. package/src/adapters/express.ts +87 -0
  55. package/src/adapters/factory.ts +112 -0
  56. package/src/adapters/fastify.ts +104 -0
  57. package/src/adapters/native.ts +245 -0
  58. package/src/api/console.ts +348 -0
  59. package/src/api/http.ts +535 -0
  60. package/src/bin/nytejs.js +331 -0
  61. package/src/builder.js +690 -0
  62. package/src/client/DefaultNotFound.tsx +119 -0
  63. package/src/client/client.ts +24 -0
  64. package/src/client/clientRouter.ts +153 -0
  65. package/src/client/entry.client.tsx +529 -0
  66. package/src/client/rpc.ts +101 -0
  67. package/src/components/Link.tsx +38 -0
  68. package/src/global/global.ts +171 -0
  69. package/src/helpers.ts +657 -0
  70. package/src/hotReload.ts +566 -0
  71. package/src/index.ts +582 -0
  72. package/src/loaders.js +160 -0
  73. package/src/renderer.tsx +421 -0
  74. package/src/router.ts +732 -0
  75. package/src/rpc/server.ts +190 -0
  76. package/src/rpc/types.ts +45 -0
  77. package/src/types/framework.ts +58 -0
  78. package/src/types.ts +288 -0
@@ -0,0 +1,469 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NyteResponse = exports.NyteRequest = void 0;
4
+ // Input validation and sanitization utilities
5
+ class SecurityUtils {
6
+ static sanitizeHeader(value) {
7
+ if (Array.isArray(value)) {
8
+ return value.map(v => this.sanitizeString(v, this.MAX_HEADER_LENGTH));
9
+ }
10
+ return this.sanitizeString(value, this.MAX_HEADER_LENGTH);
11
+ }
12
+ static sanitizeString(str, maxLength) {
13
+ if (typeof str !== 'string')
14
+ return '';
15
+ // Remove null bytes and control characters except newline/tab
16
+ let clean = str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
17
+ // Limit length
18
+ if (clean.length > maxLength) {
19
+ clean = clean.substring(0, maxLength);
20
+ }
21
+ return clean;
22
+ }
23
+ static isValidURL(url) {
24
+ if (!url || typeof url !== 'string')
25
+ return false;
26
+ if (url.length > this.MAX_URL_LENGTH)
27
+ return false;
28
+ // Basic URL validation - prevent dangerous protocols
29
+ const dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:'];
30
+ const lowerUrl = url.toLowerCase();
31
+ return !dangerousProtocols.some(protocol => lowerUrl.startsWith(protocol));
32
+ }
33
+ static validateContentLength(length) {
34
+ return length >= 0 && length <= this.MAX_BODY_SIZE;
35
+ }
36
+ }
37
+ SecurityUtils.MAX_HEADER_LENGTH = 8192;
38
+ SecurityUtils.MAX_COOKIE_LENGTH = 4096;
39
+ SecurityUtils.MAX_URL_LENGTH = 2048;
40
+ SecurityUtils.MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB
41
+ /**
42
+ * Abstração sobre a requisição HTTP de entrada.
43
+ * Funciona com qualquer framework web (Express, Fastify, etc.)
44
+ */
45
+ class NyteRequest {
46
+ constructor(req) {
47
+ // Validate and sanitize request data
48
+ this._req = this.validateAndSanitizeRequest(req);
49
+ }
50
+ validateAndSanitizeRequest(req) {
51
+ // Validate URL
52
+ if (!SecurityUtils.isValidURL(req.url)) {
53
+ throw new Error('Invalid URL format');
54
+ }
55
+ // Sanitize headers
56
+ const sanitizedHeaders = {};
57
+ for (const [key, value] of Object.entries(req.headers || {})) {
58
+ const cleanKey = SecurityUtils.sanitizeString(key.toLowerCase(), 100);
59
+ if (cleanKey && value) {
60
+ sanitizedHeaders[cleanKey] = SecurityUtils.sanitizeHeader(value);
61
+ }
62
+ }
63
+ // Validate content length
64
+ const contentLength = req.headers['content-length'];
65
+ if (contentLength) {
66
+ const length = parseInt(Array.isArray(contentLength) ? contentLength[0] : contentLength, 10);
67
+ if (!SecurityUtils.validateContentLength(length)) {
68
+ throw new Error('Request too large');
69
+ }
70
+ }
71
+ // Sanitize cookies
72
+ const sanitizedCookies = {};
73
+ for (const [key, value] of Object.entries(req.cookies || {})) {
74
+ const cleanKey = SecurityUtils.sanitizeString(key, 100);
75
+ const cleanValue = SecurityUtils.sanitizeString(value, SecurityUtils.MAX_COOKIE_LENGTH);
76
+ if (cleanKey && cleanValue) {
77
+ sanitizedCookies[cleanKey] = cleanValue;
78
+ }
79
+ }
80
+ return {
81
+ ...req,
82
+ headers: sanitizedHeaders,
83
+ cookies: sanitizedCookies,
84
+ url: SecurityUtils.sanitizeString(req.url, SecurityUtils.MAX_URL_LENGTH)
85
+ };
86
+ }
87
+ /**
88
+ * Retorna o método HTTP da requisição (GET, POST, etc.)
89
+ */
90
+ get method() {
91
+ return this._req.method;
92
+ }
93
+ /**
94
+ * Retorna a URL completa da requisição
95
+ */
96
+ get url() {
97
+ return this._req.url;
98
+ }
99
+ /**
100
+ * Retorna todos os headers da requisição
101
+ */
102
+ get headers() {
103
+ return this._req.headers;
104
+ }
105
+ /**
106
+ * Retorna um header específico com validação
107
+ */
108
+ header(name) {
109
+ if (!name || typeof name !== 'string')
110
+ return undefined;
111
+ const cleanName = SecurityUtils.sanitizeString(name.toLowerCase(), 100);
112
+ return this._req.headers[cleanName];
113
+ }
114
+ /**
115
+ * Retorna todos os query parameters
116
+ */
117
+ get query() {
118
+ return this._req.query || {};
119
+ }
120
+ /**
121
+ * Retorna todos os parâmetros de rota
122
+ */
123
+ get params() {
124
+ return this._req.params || {};
125
+ }
126
+ /**
127
+ * Retorna todos os cookies
128
+ */
129
+ get cookies() {
130
+ return this._req.cookies || {};
131
+ }
132
+ /**
133
+ * Retorna um cookie específico com validação
134
+ */
135
+ cookie(name) {
136
+ if (!name || typeof name !== 'string')
137
+ return undefined;
138
+ const cleanName = SecurityUtils.sanitizeString(name, 100);
139
+ return this._req.cookies?.[cleanName];
140
+ }
141
+ /**
142
+ * Retorna o corpo (body) da requisição, já parseado como JSON com validação
143
+ */
144
+ async json() {
145
+ try {
146
+ const body = this._req.body;
147
+ // Validate JSON structure
148
+ if (typeof body === 'string') {
149
+ // Check for potential JSON bombs
150
+ if (body.length > SecurityUtils.MAX_BODY_SIZE) {
151
+ throw new Error('Request body too large');
152
+ }
153
+ return JSON.parse(body);
154
+ }
155
+ return body;
156
+ }
157
+ catch (error) {
158
+ if (error instanceof SyntaxError) {
159
+ throw new Error('Invalid JSON format');
160
+ }
161
+ throw error;
162
+ }
163
+ }
164
+ /**
165
+ * Retorna o corpo da requisição como texto
166
+ */
167
+ async text() {
168
+ if (typeof this._req.body === 'string') {
169
+ return this._req.body;
170
+ }
171
+ return JSON.stringify(this._req.body);
172
+ }
173
+ /**
174
+ * Retorna o corpo da requisição como FormData (para uploads)
175
+ */
176
+ async formData() {
177
+ return this._req.body;
178
+ }
179
+ /**
180
+ * Retorna a requisição original do framework
181
+ */
182
+ get raw() {
183
+ return this._req.raw;
184
+ }
185
+ /**
186
+ * Verifica se a requisição tem um content-type específico
187
+ */
188
+ is(type) {
189
+ const contentType = this.header('content-type');
190
+ if (!contentType)
191
+ return false;
192
+ const ct = Array.isArray(contentType) ? contentType[0] : contentType;
193
+ return ct.toLowerCase().includes(type.toLowerCase());
194
+ }
195
+ /**
196
+ * Verifica se a requisição é AJAX/XHR
197
+ */
198
+ get isAjax() {
199
+ const xhr = this.header('x-requested-with');
200
+ return xhr === 'XMLHttpRequest';
201
+ }
202
+ /**
203
+ * Retorna o IP do cliente com validação melhorada
204
+ */
205
+ get ip() {
206
+ // Check X-Forwarded-For with validation
207
+ const forwarded = this.header('x-forwarded-for');
208
+ if (forwarded) {
209
+ const ips = Array.isArray(forwarded) ? forwarded[0] : forwarded;
210
+ const firstIp = ips.split(',')[0].trim();
211
+ // Basic IP validation
212
+ if (this.isValidIP(firstIp)) {
213
+ return firstIp;
214
+ }
215
+ }
216
+ // Check X-Real-IP
217
+ const realIp = this.header('x-real-ip');
218
+ if (realIp) {
219
+ const ip = Array.isArray(realIp) ? realIp[0] : realIp;
220
+ if (this.isValidIP(ip)) {
221
+ return ip;
222
+ }
223
+ }
224
+ return 'unknown';
225
+ }
226
+ isValidIP(ip) {
227
+ if (!ip || typeof ip !== 'string')
228
+ return false;
229
+ // Basic IPv4 validation
230
+ const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
231
+ if (ipv4Regex.test(ip)) {
232
+ const parts = ip.split('.');
233
+ return parts.every(part => {
234
+ const num = parseInt(part, 10);
235
+ return num >= 0 && num <= 255;
236
+ });
237
+ }
238
+ // Basic IPv6 validation (simplified)
239
+ const ipv6Regex = /^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$/;
240
+ return ipv6Regex.test(ip);
241
+ }
242
+ /**
243
+ * Retorna o User-Agent
244
+ */
245
+ get userAgent() {
246
+ const ua = this.header('user-agent');
247
+ return Array.isArray(ua) ? ua[0] : ua;
248
+ }
249
+ }
250
+ exports.NyteRequest = NyteRequest;
251
+ /**
252
+ * Abstração para construir a resposta HTTP.
253
+ * Funciona com qualquer framework web (Express, Fastify, etc.)
254
+ */
255
+ class NyteResponse {
256
+ constructor() {
257
+ this._status = 200;
258
+ this._headers = {};
259
+ this._cookies = [];
260
+ this._body = null;
261
+ this._sent = false;
262
+ }
263
+ /**
264
+ * Define o status HTTP da resposta
265
+ */
266
+ status(code) {
267
+ this._status = code;
268
+ return this;
269
+ }
270
+ /**
271
+ * Define um header da resposta
272
+ */
273
+ header(name, value) {
274
+ this._headers[name] = value;
275
+ return this;
276
+ }
277
+ /**
278
+ * Define múltiplos headers
279
+ */
280
+ headers(headers) {
281
+ Object.assign(this._headers, headers);
282
+ return this;
283
+ }
284
+ /**
285
+ * Define um cookie
286
+ */
287
+ cookie(name, value, options) {
288
+ this._cookies.push({ name, value, options });
289
+ return this;
290
+ }
291
+ /**
292
+ * Remove um cookie
293
+ */
294
+ clearCookie(name, options) {
295
+ this._cookies.push({
296
+ name,
297
+ value: '',
298
+ options: { ...options, expires: new Date(0) }
299
+ });
300
+ return this;
301
+ }
302
+ /**
303
+ * Envia resposta JSON
304
+ */
305
+ json(data) {
306
+ this._headers['Content-Type'] = 'application/json';
307
+ this._body = JSON.stringify(data);
308
+ this._sent = true;
309
+ return this;
310
+ }
311
+ /**
312
+ * Envia resposta de texto
313
+ */
314
+ text(data) {
315
+ this._headers['Content-Type'] = 'text/plain; charset=utf-8';
316
+ this._body = data;
317
+ this._sent = true;
318
+ return this;
319
+ }
320
+ /**
321
+ * Envia resposta HTML
322
+ */
323
+ html(data) {
324
+ this._headers['Content-Type'] = 'text/html; charset=utf-8';
325
+ this._body = data;
326
+ this._sent = true;
327
+ return this;
328
+ }
329
+ /**
330
+ * Envia qualquer tipo de dados
331
+ */
332
+ send(data) {
333
+ this._body = data;
334
+ this._sent = true;
335
+ return this;
336
+ }
337
+ /**
338
+ * Redireciona para uma URL
339
+ */
340
+ redirect(url, status = 302) {
341
+ this._status = status;
342
+ this._headers['Location'] = url;
343
+ this._sent = true;
344
+ return this;
345
+ }
346
+ /**
347
+ * Método interno para aplicar a resposta ao objeto de resposta do framework
348
+ */
349
+ _applyTo(res) {
350
+ // Aplica status
351
+ res.status(this._status);
352
+ // Aplica headers
353
+ Object.entries(this._headers).forEach(([name, value]) => {
354
+ res.header(name, value);
355
+ });
356
+ // Aplica cookies
357
+ this._cookies.forEach(({ name, value, options }) => {
358
+ if (options?.expires && options.expires.getTime() === 0) {
359
+ res.clearCookie(name, options);
360
+ }
361
+ else {
362
+ res.cookie(name, value, options);
363
+ }
364
+ });
365
+ // Handle redirects specifically
366
+ if (this._headers['Location']) {
367
+ res.redirect(this._headers['Location']);
368
+ return;
369
+ }
370
+ // Envia o corpo se foi definido
371
+ if (this._sent && this._body !== null) {
372
+ if (this._headers['Content-Type']?.includes('application/json')) {
373
+ res.json(JSON.parse(this._body));
374
+ }
375
+ else {
376
+ res.send(this._body);
377
+ }
378
+ }
379
+ }
380
+ /**
381
+ * Método de compatibilidade com versão anterior (Express)
382
+ */
383
+ _send(res) {
384
+ // Assume que é Express se tem os métodos específicos
385
+ if (res.set && res.status && res.send) {
386
+ res.set(this._headers).status(this._status);
387
+ this._cookies.forEach(({ name, value, options }) => {
388
+ if (options?.expires && options.expires.getTime() === 0) {
389
+ res.clearCookie(name, options);
390
+ }
391
+ else {
392
+ res.cookie(name, value, options);
393
+ }
394
+ });
395
+ res.send(this._body);
396
+ }
397
+ }
398
+ // === MÉTODOS ESTÁTICOS DE CONVENIÊNCIA ===
399
+ /**
400
+ * Cria uma resposta JSON
401
+ */
402
+ static json(data, options) {
403
+ const response = new NyteResponse();
404
+ if (options?.status)
405
+ response.status(options.status);
406
+ if (options?.headers)
407
+ response.headers(options.headers);
408
+ return response.json(data);
409
+ }
410
+ /**
411
+ * Cria uma resposta de texto
412
+ */
413
+ static text(data, options) {
414
+ const response = new NyteResponse();
415
+ if (options?.status)
416
+ response.status(options.status);
417
+ if (options?.headers)
418
+ response.headers(options.headers);
419
+ return response.text(data);
420
+ }
421
+ /**
422
+ * Cria uma resposta HTML
423
+ */
424
+ static html(data, options) {
425
+ const response = new NyteResponse();
426
+ if (options?.status)
427
+ response.status(options.status);
428
+ if (options?.headers)
429
+ response.headers(options.headers);
430
+ return response.html(data);
431
+ }
432
+ /**
433
+ * Cria um redirecionamento
434
+ */
435
+ static redirect(url, status = 302) {
436
+ return new NyteResponse().redirect(url, status);
437
+ }
438
+ /**
439
+ * Cria uma resposta 404
440
+ */
441
+ static notFound(message = 'Not Found') {
442
+ return NyteResponse.text(message, { status: 404 });
443
+ }
444
+ /**
445
+ * Cria uma resposta 500
446
+ */
447
+ static error(message = 'Internal Server Error') {
448
+ return NyteResponse.text(message, { status: 500 });
449
+ }
450
+ /**
451
+ * Cria uma resposta 400
452
+ */
453
+ static badRequest(message = 'Bad Request') {
454
+ return NyteResponse.text(message, { status: 400 });
455
+ }
456
+ /**
457
+ * Cria uma resposta 401
458
+ */
459
+ static unauthorized(message = 'Unauthorized') {
460
+ return NyteResponse.text(message, { status: 401 });
461
+ }
462
+ /**
463
+ * Cria uma resposta 403
464
+ */
465
+ static forbidden(message = 'Forbidden') {
466
+ return NyteResponse.text(message, { status: 403 });
467
+ }
468
+ }
469
+ exports.NyteResponse = NyteResponse;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};