@wxn0brp/falcon-frame 0.8.0 → 0.8.2

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/compress.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { createDeflate, createGzip } from "zlib";
2
2
  export function compression(req, res) {
3
+ if (req._compression)
4
+ return;
5
+ req._compression = true;
3
6
  const encoding = req.headers["accept-encoding"];
4
7
  if (!encoding || typeof encoding !== "string" || res.headersSent) {
5
8
  return;
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { Cookies, RouteHandler, StaticServeOptions } from "./types.js";
1
+ import { Cookies } from "./types.js";
2
2
  export declare function parseCookies(cookieHeader: string): Cookies;
3
3
  export declare function getContentType(filePath: string, utf8?: boolean): string;
4
- export declare function handleStaticFiles(dirPath: string, opts: StaticServeOptions): RouteHandler;
5
4
  export declare const ensureLeadingDot: (str: string) => string;
package/dist/helpers.js CHANGED
@@ -1,4 +1,3 @@
1
- import fs from "fs";
2
1
  import path from "path";
3
2
  export function parseCookies(cookieHeader) {
4
3
  const cookies = {};
@@ -33,81 +32,4 @@ export function getContentType(filePath, utf8 = false) {
33
32
  contentType += "; charset=utf-8";
34
33
  return contentType;
35
34
  }
36
- export function handleStaticFiles(dirPath, opts) {
37
- opts = {
38
- utf8: true,
39
- render: true,
40
- renderData: {},
41
- etag: true,
42
- errorIfDirNotFound: true,
43
- ...opts,
44
- };
45
- if (opts.errorIfDirNotFound && !fs.existsSync(dirPath)) {
46
- throw new Error(`Directory ${dirPath} does not exist`);
47
- }
48
- const serveFile = (req, res, filePath, stats) => {
49
- if (opts.render) {
50
- const defaultRenderer = res.FF.getVar("view engine");
51
- const renderStatement = (defaultRenderer && filePath.endsWith(ensureLeadingDot(defaultRenderer))) ||
52
- (!opts.notRenderHtml && filePath.endsWith(".html"));
53
- if (renderStatement) {
54
- const relativePath = filePath.replace(dirPath + "/", "").replace(".html", "");
55
- res.render(filePath, opts.renderData?.[relativePath] || {}, { notUseViews: true });
56
- return true;
57
- }
58
- }
59
- if (opts.etag) {
60
- const etag = `W/"${stats.size}-${stats.mtime.getTime()}"`;
61
- if (req.headers["if-none-match"] === etag) {
62
- res.status(304).end();
63
- return true;
64
- }
65
- res.setHeader("ETag", etag);
66
- }
67
- res.ct(getContentType(filePath, opts.utf8));
68
- fs.createReadStream(filePath).pipe(res);
69
- return true;
70
- };
71
- return (req, res, next) => {
72
- if (req.method.toLowerCase() !== "get")
73
- return next();
74
- const apiPath = req.middleware.path;
75
- const filePath = path.join(dirPath, req.path.replace(apiPath, ""));
76
- try {
77
- const stats = fs.statSync(filePath);
78
- if (stats.isFile()) {
79
- return serveFile(req, res, filePath, stats);
80
- }
81
- if (stats.isDirectory()) {
82
- const indexPath = path.join(filePath, "index.html");
83
- try {
84
- const indexStats = fs.statSync(indexPath);
85
- if (indexStats.isFile()) {
86
- if (!req.path.endsWith("/")) {
87
- res.redirect(req.path + "/");
88
- return true;
89
- }
90
- return serveFile(req, res, indexPath, indexStats);
91
- }
92
- }
93
- catch (e) {
94
- /* index.html not found, do nothing */
95
- }
96
- }
97
- }
98
- catch (e) {
99
- /* file/dir not found, proceed to check for .html */
100
- }
101
- try {
102
- const htmlPath = filePath + ".html";
103
- const htmlStats = fs.statSync(htmlPath);
104
- if (htmlStats.isFile())
105
- return serveFile(req, res, htmlPath, htmlStats);
106
- }
107
- catch (e) {
108
- /* .html file not found, fall through to next() */
109
- }
110
- next();
111
- };
112
- }
113
35
  export const ensureLeadingDot = (str) => (str.startsWith(".") ? str : "." + str);
package/dist/req.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import FalconFrame from "./index.js";
2
2
  import { FFResponse } from "./res.js";
3
3
  import { FFRequest } from "./types.js";
4
- export declare function handleRequest(req: FFRequest, res: FFResponse, FF: FalconFrame<any>): void;
4
+ export declare function handleRequest(req: FFRequest, res: FFResponse, FF: FalconFrame<any>, reRoute?: boolean): void;
package/dist/req.js CHANGED
@@ -3,15 +3,17 @@ import { parseCookies } from "./helpers.js";
3
3
  import { getMiddlewares, matchMiddleware } from "./middleware.js";
4
4
  import { FFResponse } from "./res.js";
5
5
  import { validate } from "./valid.js";
6
- export function handleRequest(req, res, FF) {
7
- Object.setPrototypeOf(res, FFResponse.prototype);
8
- req.FF = FF;
9
- res.FF = FF;
10
- const originalEnd = res.end;
11
- res.end = function (...any) {
12
- res._ended = true;
13
- return originalEnd.call(res, ...any);
14
- };
6
+ export function handleRequest(req, res, FF, reRoute = false) {
7
+ if (!reRoute) {
8
+ Object.setPrototypeOf(res, FFResponse.prototype);
9
+ req.FF = FF;
10
+ res.FF = FF;
11
+ const originalEnd = res.end;
12
+ res.end = function (...any) {
13
+ res._ended = true;
14
+ return originalEnd.call(res, ...any);
15
+ };
16
+ }
15
17
  const { logger } = FF;
16
18
  try {
17
19
  const [path, params] = (req.url || "").split("?");
@@ -28,6 +30,10 @@ export function handleRequest(req, res, FF) {
28
30
  req.cookies = parseCookies(req.headers.cookie || "");
29
31
  req.params = {};
30
32
  req.valid = (schema) => validate(schema, req.body);
33
+ req.reRoute = (fn) => {
34
+ fn(req);
35
+ handleRequest(req, res, FF, true);
36
+ };
31
37
  logger.info(`Incoming request: ${req.method} ${req.url}`);
32
38
  const middlewaresPath = req.path + "/";
33
39
  const middlewares = getMiddlewares(FF.middlewares, middlewaresPath.replace(/\/+/g, "/"));
@@ -98,6 +104,11 @@ export function handleRequest(req, res, FF) {
98
104
  next();
99
105
  return;
100
106
  }
107
+ if (reRoute) {
108
+ logger.debug("Re-route. Executing middlewares");
109
+ next();
110
+ return;
111
+ }
101
112
  req.body = {};
102
113
  let bodyParserIndex = 0;
103
114
  function nextBodyParser() {
package/dist/res.d.ts CHANGED
@@ -38,13 +38,14 @@ export declare class FFResponse extends http.ServerResponse {
38
38
  */
39
39
  status(code: number): this;
40
40
  /**
41
- * Set status code to 302 and set location header to the provided url.
41
+ * Set status code to 303 and set location header to the provided url.
42
42
  * If end is true, ends the response.
43
43
  * @param url The url to redirect to
44
+ * @param status Status code to set
44
45
  * @param end Whether to end the response after setting the headers
45
46
  * @returns The response object
46
47
  */
47
- redirect(url: string, end?: boolean): this;
48
+ redirect(url: string, status?: number, end?: boolean): this;
48
49
  /**
49
50
  * Sends a file as the response.
50
51
  * Sets the "Content-Type" header based on the provided contentType or the file's extension.
package/dist/res.js CHANGED
@@ -67,14 +67,15 @@ export class FFResponse extends http.ServerResponse {
67
67
  return this;
68
68
  }
69
69
  /**
70
- * Set status code to 302 and set location header to the provided url.
70
+ * Set status code to 303 and set location header to the provided url.
71
71
  * If end is true, ends the response.
72
72
  * @param url The url to redirect to
73
+ * @param status Status code to set
73
74
  * @param end Whether to end the response after setting the headers
74
75
  * @returns The response object
75
76
  */
76
- redirect(url, end = true) {
77
- this.statusCode = 302;
77
+ redirect(url, status = 303, end = true) {
78
+ this.statusCode = status;
78
79
  this.setHeader("Location", url);
79
80
  if (end)
80
81
  this.end();
package/dist/router.js CHANGED
@@ -1,5 +1,5 @@
1
- import { handleStaticFiles } from "./helpers.js";
2
1
  import { SSEManager } from "./sse.js";
2
+ import { handleStaticFiles } from "./static.js";
3
3
  export class Router {
4
4
  middlewares = [];
5
5
  addRoute(method, path, ...handlers) {
@@ -0,0 +1,2 @@
1
+ import { RouteHandler, StaticServeOptions } from "./types.js";
2
+ export declare function handleStaticFiles(dirPath: string, opts: StaticServeOptions): RouteHandler;
package/dist/static.js ADDED
@@ -0,0 +1,85 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { ensureLeadingDot, getContentType } from "./helpers.js";
4
+ export function handleStaticFiles(dirPath, opts) {
5
+ opts = {
6
+ utf8: true,
7
+ render: true,
8
+ renderData: {},
9
+ etag: true,
10
+ errorIfDirNotFound: true,
11
+ ...opts,
12
+ };
13
+ if (opts.errorIfDirNotFound && !fs.existsSync(dirPath)) {
14
+ throw new Error(`Directory ${dirPath} does not exist`);
15
+ }
16
+ const serveFile = (req, res, filePath, stats) => {
17
+ if (opts.render) {
18
+ const defaultRenderer = res.FF.getVar("view engine");
19
+ const renderStatement = (defaultRenderer && filePath.endsWith(ensureLeadingDot(defaultRenderer))) ||
20
+ (!opts.notRenderHtml && filePath.endsWith(".html"));
21
+ if (renderStatement) {
22
+ const relativePath = filePath.replace(dirPath + "/", "").replace(".html", "");
23
+ res.render(filePath, opts.renderData?.[relativePath] || {}, { notUseViews: true });
24
+ return true;
25
+ }
26
+ }
27
+ if (opts.etag) {
28
+ const etag = `W/"${stats.size}-${stats.mtime.getTime()}"`;
29
+ if (req.headers["if-none-match"] === etag) {
30
+ res.status(304).end();
31
+ return true;
32
+ }
33
+ res.setHeader("ETag", etag);
34
+ }
35
+ res.ct(getContentType(filePath, opts.utf8));
36
+ fs.createReadStream(filePath).pipe(res);
37
+ return true;
38
+ };
39
+ return (req, res, next) => {
40
+ if (req.method.toLowerCase() !== "get")
41
+ return next();
42
+ const apiPath = req.middleware.path;
43
+ const unsafePath = req.path.replace(apiPath, "");
44
+ const filePath = path.join(dirPath, path.normalize(unsafePath));
45
+ const resolvedPath = path.resolve(filePath);
46
+ const resolvedDir = path.resolve(dirPath);
47
+ if (!resolvedPath.startsWith(resolvedDir))
48
+ return next();
49
+ try {
50
+ const stats = fs.statSync(filePath);
51
+ if (stats.isFile()) {
52
+ return serveFile(req, res, filePath, stats);
53
+ }
54
+ if (stats.isDirectory()) {
55
+ const indexPath = path.join(filePath, "index.html");
56
+ try {
57
+ const indexStats = fs.statSync(indexPath);
58
+ if (indexStats.isFile()) {
59
+ if (!req.path.endsWith("/")) {
60
+ res.redirect(req.path + "/");
61
+ return true;
62
+ }
63
+ return serveFile(req, res, indexPath, indexStats);
64
+ }
65
+ }
66
+ catch (e) {
67
+ /* index.html not found, do nothing */
68
+ }
69
+ }
70
+ }
71
+ catch (e) {
72
+ /* file/dir not found, proceed to check for .html */
73
+ }
74
+ try {
75
+ const htmlPath = filePath + ".html";
76
+ const htmlStats = fs.statSync(htmlPath);
77
+ if (htmlStats.isFile())
78
+ return serveFile(req, res, htmlPath, htmlStats);
79
+ }
80
+ catch (e) {
81
+ /* .html file not found, fall through to next() */
82
+ }
83
+ next();
84
+ };
85
+ }
package/dist/types.d.ts CHANGED
@@ -31,6 +31,8 @@ export declare class FFRequest extends http.IncomingMessage {
31
31
  valid: (schema: ValidationSchema) => ValidationResult;
32
32
  middleware: Middleware;
33
33
  sseId?: string;
34
+ reRoute: (fn: (req: FFRequest) => void) => void;
35
+ _compression?: true;
34
36
  }
35
37
  export interface Middleware {
36
38
  path: string;
package/dist/types.js CHANGED
@@ -9,4 +9,6 @@ export class FFRequest extends http.IncomingMessage {
9
9
  valid;
10
10
  middleware;
11
11
  sseId;
12
+ reRoute;
13
+ _compression;
12
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wxn0brp/falcon-frame",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "author": "wxn0brP",
@@ -26,7 +26,7 @@
26
26
  "devDependencies": {
27
27
  "@types/node": "*",
28
28
  "tsc-alias": "*",
29
- "typescript": "*"
29
+ "typescript": "^6"
30
30
  },
31
31
  "dependencies": {
32
32
  "@wxn0brp/lucerna-log": "^0.2.2"