@syntay/fastay 0.1.5 → 0.1.7

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/app.js CHANGED
@@ -4,6 +4,7 @@ import { loadApiRoutes } from './router.js';
4
4
  import { loadFastayMiddlewares, createMiddleware, } from './middleware.js';
5
5
  import { logger } from './logger.js';
6
6
  import { printBanner } from './banner.js';
7
+ import { RequestCookies } from './utils/cookies.js';
7
8
  /**
8
9
  * Bootstraps and configures a Fastay application.
9
10
  *
@@ -91,8 +92,9 @@ export async function createApp(opts) {
91
92
  const isMiddleware = await loadFastayMiddlewares(app);
92
93
  // health check
93
94
  app.get('/_health', (_, res) => res.json({ ok: true }));
94
- app.use((_req, res, next) => {
95
+ app.use((req, res, next) => {
95
96
  res.setHeader('X-Powered-By', 'Syntay Engine');
97
+ req.cookies = new RequestCookies(req.headers.cookie);
96
98
  next();
97
99
  });
98
100
  // load routes
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { createApp } from './app.js';
2
2
  export { createMiddleware } from './middleware.js';
3
3
  export type { CreateAppOptions } from './app.js';
4
- export { Request, Response, Next } from './types';
4
+ export type { Request, Response, Next } from './types';
package/dist/router.js CHANGED
@@ -42,6 +42,61 @@ function wrapHandler(fn, routePath, filePath) {
42
42
  return;
43
43
  if (result === undefined)
44
44
  return;
45
+ // Suporte a status e cookies customizado
46
+ // if (
47
+ // typeof result === 'object' &&
48
+ // 'status' in result &&
49
+ // 'body' in result &&
50
+ // typeof result.status === 'number'
51
+ // ) {
52
+ // return res.status(result.status).json(result.body);
53
+ // }
54
+ if (typeof result === 'object' && result !== null) {
55
+ const typedResult = result;
56
+ // redirect
57
+ if (typedResult.redirect) {
58
+ return res.redirect(typedResult.status ?? 302, typedResult.redirect);
59
+ }
60
+ //headers
61
+ if (typedResult.headers) {
62
+ for (const [h, v] of Object.entries(typedResult.headers)) {
63
+ res.setHeader(h, v);
64
+ }
65
+ }
66
+ //file
67
+ if (typedResult.file) {
68
+ const { path, filename, options } = typedResult.file;
69
+ if (filename) {
70
+ return res.download(path, filename, options);
71
+ }
72
+ return res.download(path, options);
73
+ }
74
+ // stream
75
+ if (typedResult.stream) {
76
+ if (typedResult.headers) {
77
+ for (const [h, v] of Object.entries(typedResult.headers))
78
+ res.setHeader(h, v);
79
+ }
80
+ return typedResult.stream.pipe(res);
81
+ }
82
+ // raw
83
+ if (typedResult.raw) {
84
+ if (typedResult.headers) {
85
+ for (const [h, v] of Object.entries(typedResult.headers))
86
+ res.setHeader(h, v);
87
+ }
88
+ return res.status(typedResult.status ?? 200).send(typedResult.raw);
89
+ }
90
+ if (typedResult.cookies) {
91
+ for (const [name, data] of Object.entries(typedResult.cookies)) {
92
+ res.cookie(name, data.value, data.options || {});
93
+ }
94
+ }
95
+ const statusCode = typeof result.status === 'number' ? result.status : 200;
96
+ const body = result.body ?? result; // se não existir body, retorna o objeto inteiro
97
+ return res.status(statusCode).json(body);
98
+ }
99
+ // Suporte a retorno simples
45
100
  if (typeof result === 'string')
46
101
  return res.send(result);
47
102
  if (typeof result === 'number')
@@ -50,31 +105,7 @@ function wrapHandler(fn, routePath, filePath) {
50
105
  }
51
106
  catch (err) {
52
107
  const stack = err?.stack?.split('\n').slice(0, 3).join('\n') || '';
53
- // logger.error(
54
- // `✗ Runtime Error in route [${req.method} ${routePath}]\n` +
55
- // ` File: ${filePath}\n` +
56
- // ` ${err.name}: ${err.message || 'Unknown error'}\n` +
57
- // ` Stack: ${stack}`
58
- // );
59
- let fileInfo = '';
60
- if (err.stack) {
61
- const stackLine = err.stack.split('\n')[1]; // pega primeira linha depois do erro
62
- const match = stackLine.match(/\((.*):(\d+):(\d+)\)/);
63
- if (match) {
64
- const [_, file, line, col] = match;
65
- fileInfo = `${file}:${line}:${col}`;
66
- // Tenta mostrar o trecho da linha que deu erro
67
- if (fs.existsSync(file)) {
68
- const codeLines = fs.readFileSync(file, 'utf-8').split('\n');
69
- const codeSnippet = codeLines[parseInt(line) - 1].trim();
70
- fileInfo += ` → ${codeSnippet}`;
71
- }
72
- }
73
- }
74
- // logger.group(`✗ Runtime Error in route [${req.method} ${routePath}]`);
75
108
  logger.error(`${err.name}: ${err.message}`);
76
- if (fileInfo)
77
- logger.error(`Location: ${fileInfo}`);
78
109
  next(err);
79
110
  }
80
111
  };
@@ -1,8 +1,59 @@
1
1
  import { Request as ExpressRequest, Response as ExpressResponse, NextFunction } from 'express';
2
- /**
3
- * Request e Response do Express
4
- * Podem ser usados nos handlers do usuário
5
- */
6
- export type Request = ExpressRequest;
2
+ export interface CookieItem {
3
+ value: string;
4
+ }
5
+ export interface RequestCookies {
6
+ /**
7
+ * Retrieves a cookie by its name.
8
+ * @param name - The name of the cookie to retrieve.
9
+ * @returns An object containing the cookie's value, or undefined if not found.
10
+ */
11
+ get(name: string): CookieItem | undefined;
12
+ /**
13
+ * Checks if a cookie with the given name exists.
14
+ * @param name - The name of the cookie to check.
15
+ * @returns True if the cookie exists, false otherwise.
16
+ */
17
+ has(name: string): boolean;
18
+ /**
19
+ * Returns all cookies as a key-value object.
20
+ * @returns An object where keys are cookie names and values are cookie values.
21
+ */
22
+ all(): Record<string, string>;
23
+ }
24
+ export interface Request extends ExpressRequest {
25
+ /**
26
+ * Represents the cookies sent in a request.
27
+ */
28
+ cookies: RequestCookies;
29
+ }
7
30
  export type Response = ExpressResponse;
8
31
  export type Next = NextFunction;
32
+ declare global {
33
+ type FastayResponse = {
34
+ status?: number;
35
+ body?: any;
36
+ cookies?: Record<string, {
37
+ value: string;
38
+ options?: any;
39
+ }>;
40
+ headers?: Record<string, string>;
41
+ redirect?: string;
42
+ file?: {
43
+ path: string;
44
+ filename?: string;
45
+ options?: any;
46
+ };
47
+ stream?: NodeJS.ReadableStream;
48
+ raw?: Buffer | string;
49
+ };
50
+ }
51
+ export type RouteHandler = (() => FastayResponse | any) | ((req: Request) => FastayResponse | any) | ((req: Request, res: Response) => FastayResponse | any);
52
+ export interface CookieItem {
53
+ value: string;
54
+ }
55
+ declare module 'express-serve-static-core' {
56
+ interface Request {
57
+ typedCookies: RequestCookies | any;
58
+ }
59
+ }
@@ -0,0 +1,9 @@
1
+ export declare class RequestCookies {
2
+ private cookies;
3
+ constructor(cookieHeader: string | undefined);
4
+ get(name: string): {
5
+ value: string;
6
+ } | undefined;
7
+ has(name: string): boolean;
8
+ all(): Record<string, string>;
9
+ }
@@ -0,0 +1,27 @@
1
+ export class RequestCookies {
2
+ constructor(cookieHeader) {
3
+ this.cookies = new Map();
4
+ if (!cookieHeader)
5
+ return;
6
+ cookieHeader.split(';').forEach((cookie) => {
7
+ const [name, ...rest] = cookie.trim().split('=');
8
+ if (!name)
9
+ return;
10
+ this.cookies.set(name, decodeURIComponent(rest.join('=')));
11
+ });
12
+ }
13
+ get(name) {
14
+ const value = this.cookies.get(name);
15
+ if (!value)
16
+ return undefined;
17
+ return { value };
18
+ }
19
+ has(name) {
20
+ return this.cookies.has(name);
21
+ }
22
+ all() {
23
+ const obj = {};
24
+ this.cookies.forEach((v, k) => (obj[k] = v));
25
+ return obj;
26
+ }
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syntay/fastay",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Framework backend moderno baseado em Express.js, para criar APIs rapidamente",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/app.ts CHANGED
@@ -10,6 +10,7 @@ import { logger } from './logger.js';
10
10
  import { printBanner } from './banner.js';
11
11
  import type { ServeStaticOptions } from 'serve-static';
12
12
  import { Next, Request, Response } from './types/index.js';
13
+ import { RequestCookies } from './utils/cookies.js';
13
14
 
14
15
  /**
15
16
  * Express configuration options applied automatically by Fastay
@@ -214,8 +215,9 @@ export async function createApp(opts?: CreateAppOptions) {
214
215
 
215
216
  // health check
216
217
  app.get('/_health', (_, res) => res.json({ ok: true }));
217
- app.use((_req: Request, res: Response, next: Next) => {
218
+ app.use((req: Request, res: Response, next: Next) => {
218
219
  res.setHeader('X-Powered-By', 'Syntay Engine');
220
+ (req as any).cookies = new RequestCookies(req.headers.cookie);
219
221
  next();
220
222
  });
221
223
 
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { createApp } from './app.js';
2
2
  export { createMiddleware } from './middleware.js';
3
3
  export type { CreateAppOptions } from './app.js';
4
- export { Request, Response, Next } from './types';
4
+ export type { Request, Response, Next } from './types';
package/src/router.ts CHANGED
@@ -47,41 +47,96 @@ function wrapHandler(fn: Function, routePath: string, filePath: string) {
47
47
  return async (req: Request, res: Response, next: NextFunction) => {
48
48
  try {
49
49
  const result = fn.length >= 2 ? await fn(req, res) : await fn(req);
50
+
50
51
  if (res.headersSent) return;
51
52
  if (result === undefined) return;
52
- if (typeof result === 'string') return res.send(result);
53
- if (typeof result === 'number') return res.send(String(result));
54
- return res.json(result);
55
- } catch (err: any) {
56
- const stack = err?.stack?.split('\n').slice(0, 3).join('\n') || '';
57
- // logger.error(
58
- // `✗ Runtime Error in route [${req.method} ${routePath}]\n` +
59
- // ` File: ${filePath}\n` +
60
- // ` ${err.name}: ${err.message || 'Unknown error'}\n` +
61
- // ` Stack: ${stack}`
62
- // );
63
53
 
64
- let fileInfo = '';
65
- if (err.stack) {
66
- const stackLine = err.stack.split('\n')[1]; // pega primeira linha depois do erro
67
- const match = stackLine.match(/\((.*):(\d+):(\d+)\)/);
68
- if (match) {
69
- const [_, file, line, col] = match;
70
- fileInfo = `${file}:${line}:${col}`;
54
+ // Suporte a status e cookies customizado
55
+ // if (
56
+ // typeof result === 'object' &&
57
+ // 'status' in result &&
58
+ // 'body' in result &&
59
+ // typeof result.status === 'number'
60
+ // ) {
61
+ // return res.status(result.status).json(result.body);
62
+ // }
63
+ if (typeof result === 'object' && result !== null) {
64
+ const typedResult = result as {
65
+ status?: number;
66
+ body?: any;
67
+ cookies?: Record<string, { value: string; options?: any }>;
68
+ headers?: Record<string, string>;
69
+ redirect?: string;
70
+ file?: {
71
+ path: string;
72
+ filename?: string;
73
+ options?: any;
74
+ };
75
+ stream?: NodeJS.ReadableStream;
76
+ raw?: Buffer | string;
77
+ };
78
+
79
+ // redirect
80
+ if (typedResult.redirect) {
81
+ return res.redirect(typedResult.status ?? 302, typedResult.redirect);
82
+ }
71
83
 
72
- // Tenta mostrar o trecho da linha que deu erro
73
- if (fs.existsSync(file)) {
74
- const codeLines = fs.readFileSync(file, 'utf-8').split('\n');
75
- const codeSnippet = codeLines[parseInt(line) - 1].trim();
76
- fileInfo += ` → ${codeSnippet}`;
84
+ //headers
85
+ if (typedResult.headers) {
86
+ for (const [h, v] of Object.entries(typedResult.headers)) {
87
+ res.setHeader(h, v);
77
88
  }
78
89
  }
90
+
91
+ //file
92
+ if (typedResult.file) {
93
+ const { path, filename, options } = typedResult.file;
94
+
95
+ if (filename) {
96
+ return res.download(path, filename, options);
97
+ }
98
+
99
+ return res.download(path, options);
100
+ }
101
+
102
+ // stream
103
+ if (typedResult.stream) {
104
+ if (typedResult.headers) {
105
+ for (const [h, v] of Object.entries(typedResult.headers))
106
+ res.setHeader(h, v);
107
+ }
108
+ return typedResult.stream.pipe(res);
109
+ }
110
+
111
+ // raw
112
+ if (typedResult.raw) {
113
+ if (typedResult.headers) {
114
+ for (const [h, v] of Object.entries(typedResult.headers))
115
+ res.setHeader(h, v);
116
+ }
117
+ return res.status(typedResult.status ?? 200).send(typedResult.raw);
118
+ }
119
+
120
+ if (typedResult.cookies) {
121
+ for (const [name, data] of Object.entries(typedResult.cookies)) {
122
+ res.cookie(name, data.value, data.options || {});
123
+ }
124
+ }
125
+
126
+ const statusCode =
127
+ typeof result.status === 'number' ? result.status : 200;
128
+
129
+ const body = result.body ?? result; // se não existir body, retorna o objeto inteiro
130
+ return res.status(statusCode).json(body);
79
131
  }
80
132
 
81
- // logger.group(`✗ Runtime Error in route [${req.method} ${routePath}]`);
133
+ // Suporte a retorno simples
134
+ if (typeof result === 'string') return res.send(result);
135
+ if (typeof result === 'number') return res.send(String(result));
136
+ return res.json(result);
137
+ } catch (err: any) {
138
+ const stack = err?.stack?.split('\n').slice(0, 3).join('\n') || '';
82
139
  logger.error(`${err.name}: ${err.message}`);
83
- if (fileInfo) logger.error(`Location: ${fileInfo}`);
84
-
85
140
  next(err);
86
141
  }
87
142
  };
@@ -0,0 +1,7 @@
1
+ import { RequestCookies } from '../src/utils/cookies';
2
+
3
+ declare module 'express-serve-static-core' {
4
+ interface Request {
5
+ cookies: RequestCookies;
6
+ }
7
+ }
@@ -0,0 +1,9 @@
1
+ export interface CookieItem {
2
+ value: string;
3
+ }
4
+
5
+ export interface RequestCookies {
6
+ get(name: string): CookieItem | undefined;
7
+ has(name: string): boolean;
8
+ all(): Record<string, string>;
9
+ }
@@ -4,10 +4,68 @@ import {
4
4
  NextFunction,
5
5
  } from 'express';
6
6
 
7
- /**
8
- * Request e Response do Express
9
- * Podem ser usados nos handlers do usuário
10
- */
11
- export type Request = ExpressRequest;
7
+ export interface CookieItem {
8
+ value: string;
9
+ }
10
+
11
+ export interface RequestCookies {
12
+ /**
13
+ * Retrieves a cookie by its name.
14
+ * @param name - The name of the cookie to retrieve.
15
+ * @returns An object containing the cookie's value, or undefined if not found.
16
+ */
17
+ get(name: string): CookieItem | undefined;
18
+
19
+ /**
20
+ * Checks if a cookie with the given name exists.
21
+ * @param name - The name of the cookie to check.
22
+ * @returns True if the cookie exists, false otherwise.
23
+ */
24
+ has(name: string): boolean;
25
+
26
+ /**
27
+ * Returns all cookies as a key-value object.
28
+ * @returns An object where keys are cookie names and values are cookie values.
29
+ */
30
+ all(): Record<string, string>;
31
+ }
32
+
33
+ export interface Request extends ExpressRequest {
34
+ /**
35
+ * Represents the cookies sent in a request.
36
+ */
37
+ cookies: RequestCookies;
38
+ // params:
39
+ // query:
40
+ }
41
+
12
42
  export type Response = ExpressResponse;
13
43
  export type Next = NextFunction;
44
+
45
+ declare global {
46
+ type FastayResponse = {
47
+ status?: number;
48
+ body?: any;
49
+ cookies?: Record<string, { value: string; options?: any }>;
50
+ headers?: Record<string, string>;
51
+ redirect?: string;
52
+ file?: { path: string; filename?: string; options?: any };
53
+ stream?: NodeJS.ReadableStream;
54
+ raw?: Buffer | string;
55
+ };
56
+ }
57
+
58
+ export type RouteHandler =
59
+ | (() => FastayResponse | any)
60
+ | ((req: Request) => FastayResponse | any)
61
+ | ((req: Request, res: Response) => FastayResponse | any);
62
+
63
+ export interface CookieItem {
64
+ value: string;
65
+ }
66
+
67
+ declare module 'express-serve-static-core' {
68
+ interface Request {
69
+ typedCookies: RequestCookies | any;
70
+ }
71
+ }
@@ -0,0 +1,32 @@
1
+ // utils/cookies.ts
2
+ import { IncomingMessage } from 'http';
3
+
4
+ export class RequestCookies {
5
+ private cookies: Map<string, string> = new Map();
6
+
7
+ constructor(cookieHeader: string | undefined) {
8
+ if (!cookieHeader) return;
9
+
10
+ cookieHeader.split(';').forEach((cookie) => {
11
+ const [name, ...rest] = cookie.trim().split('=');
12
+ if (!name) return;
13
+ this.cookies.set(name, decodeURIComponent(rest.join('=')));
14
+ });
15
+ }
16
+
17
+ public get(name: string) {
18
+ const value = this.cookies.get(name);
19
+ if (!value) return undefined;
20
+ return { value };
21
+ }
22
+
23
+ public has(name: string) {
24
+ return this.cookies.has(name);
25
+ }
26
+
27
+ public all() {
28
+ const obj: Record<string, string> = {};
29
+ this.cookies.forEach((v, k) => (obj[k] = v));
30
+ return obj;
31
+ }
32
+ }
package/tsconfig.json CHANGED
@@ -4,14 +4,16 @@
4
4
  "module": "CommonJS",
5
5
  "rootDir": "src",
6
6
  "outDir": "dist",
7
+ "baseUrl": ".",
7
8
  "strict": true,
8
9
  "esModuleInterop": true,
9
10
  "forceConsistentCasingInFileNames": true,
10
11
  "skipLibCheck": true,
11
12
  "moduleResolution": "node",
12
13
  "resolveJsonModule": true,
13
- "allowSyntheticDefaultImports": true
14
+ "allowSyntheticDefaultImports": true,
15
+ "typeRoots": ["./node_modules/@types", "./types"]
14
16
  },
15
- "include": ["src"],
17
+ "include": ["src", "types"],
16
18
  "exclude": ["node_modules", "dist"]
17
19
  }