@increase21/simplenodejs 1.0.1 → 1.0.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.
@@ -0,0 +1,5 @@
1
+ export { CreateSimpleJsHttpServer } from "./server";
2
+ export * from "./utils/helpers";
3
+ export * from "./utils/simpleController";
4
+ export * from "./utils/simplePlugins";
5
+ export { Middleware, ErrorMiddleware, SimpleJsServer } from "./typings/general";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.CreateSimpleJsHttpServer = void 0;
18
+ var server_1 = require("./server");
19
+ Object.defineProperty(exports, "CreateSimpleJsHttpServer", { enumerable: true, get: function () { return server_1.CreateSimpleJsHttpServer; } });
20
+ __exportStar(require("./utils/helpers"), exports);
21
+ __exportStar(require("./utils/simpleController"), exports);
22
+ __exportStar(require("./utils/simplePlugins"), exports);
@@ -0,0 +1,7 @@
1
+ import { RequestObject, ResponseObject } from "./typings/general";
2
+ export interface ControllerMeta {
3
+ name: string;
4
+ Controller: any;
5
+ }
6
+ export declare function loadControllers(root?: string): Map<string, ControllerMeta>;
7
+ export declare function route(req: RequestObject, res: ResponseObject, controllersDir?: string): Promise<void>;
package/dist/router.js ADDED
@@ -0,0 +1,76 @@
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.loadControllers = loadControllers;
7
+ exports.route = route;
8
+ // router.ts
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ function loadControllers(root = "controllers") {
12
+ const base = node_path_1.default.resolve(process.cwd(), root);
13
+ const map = new Map();
14
+ //walk up
15
+ function walk(dir) {
16
+ //get all the file in the directory
17
+ for (const file of node_fs_1.default.readdirSync(dir)) {
18
+ //add the file name and path
19
+ const full = node_path_1.default.join(dir, file);
20
+ //load direct and reload the files
21
+ if (node_fs_1.default.statSync(full).isDirectory())
22
+ walk(full);
23
+ //if it's file load the file
24
+ else if (file.endsWith(".js") || file.endsWith(".ts")) {
25
+ const mod = require(full);
26
+ // const Controller = mod.default;
27
+ if (!full.startsWith(base))
28
+ return;
29
+ const Controller = require(full)?.default;
30
+ if (typeof Controller !== "function")
31
+ return;
32
+ const key = full.replace(base, "").replace(/\\/g, "/").replace(/\.(ts|js)$/, "");
33
+ map.set(key.toLowerCase(), { name: Controller.name, Controller });
34
+ }
35
+ }
36
+ }
37
+ walk(base);
38
+ return map;
39
+ }
40
+ const controllers = loadControllers();
41
+ async function route(req, res, controllersDir) {
42
+ // console.log("Router is called")
43
+ const url = new URL(req.url, "http://localhost");
44
+ const parts = url.pathname.replace(/^\/+|\/+$/g, "").split("/");
45
+ let controllerPath = (parts.length > 2 ? "/" + parts.slice(0, 2).join("/") : `/${parts.join("/")}`).toLocaleLowerCase();
46
+ let methodName = parts.length > 2 ? parts[2] : "index";
47
+ let id = methodName !== "index" ? parts.slice(parts.indexOf(methodName) + 1) : null;
48
+ const meta = controllers.get(controllerPath);
49
+ //if the controller is not available or not found
50
+ if (!meta || !meta.name || !meta.Controller)
51
+ return res.status(404).json({ error: "The requested resource does not exist" });
52
+ const ControllerClass = meta.Controller;
53
+ const controller = new ControllerClass();
54
+ //if the endpoint not a function
55
+ if (typeof controller[methodName] !== "function") {
56
+ //if it's using index
57
+ if (typeof controller["index"] === "function" && parts.length === 3) {
58
+ methodName = "index";
59
+ id = parts.slice(2);
60
+ }
61
+ else {
62
+ return res.status(404).json({ error: "The requested resource does not exist" });
63
+ }
64
+ }
65
+ //if the data require params but there's no matching params
66
+ if (id && id.length && (!controller[methodName].length || controller[methodName].length < id.length)) {
67
+ return res.status(404).json({ error: "The requested resource does not exist. Kindly check your url" });
68
+ }
69
+ controller._bindContext({ req, res });
70
+ const result = await controller[methodName](...(id || []));
71
+ //if it's not responded
72
+ if (!res.writableEnded && result) {
73
+ res.setHeader("Content-Type", "application/json");
74
+ res.end(JSON.stringify(result));
75
+ }
76
+ }
@@ -0,0 +1,3 @@
1
+ import { IncomingMessage, ServerResponse } from "http";
2
+ import { SimpleJsServer } from "./typings/general";
3
+ export declare const CreateSimpleJsHttpServer: (handler?: (req: IncomingMessage, res: ServerResponse) => void) => SimpleJsServer;
package/dist/server.js ADDED
@@ -0,0 +1,69 @@
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.CreateSimpleJsHttpServer = void 0;
7
+ const http_1 = __importDefault(require("http"));
8
+ const router_1 = require("./router");
9
+ const node_crypto_1 = __importDefault(require("node:crypto"));
10
+ const helpers_1 = require("./utils/helpers");
11
+ const extension = (req, res) => {
12
+ //for response status
13
+ res.status = (code) => {
14
+ if (!/^\d+/.test(String(code)) || typeof code !== "number")
15
+ throw new Error("Status code expected to be number but got " + typeof code);
16
+ res.statusCode = code ? code : 200;
17
+ return res;
18
+ };
19
+ ///convert the response to JSON
20
+ res.json = (param) => {
21
+ res.setHeader('Content-Type', 'application/json');
22
+ res.end(JSON.stringify(param));
23
+ };
24
+ //convert the response to text/plain
25
+ res.text = (param) => {
26
+ res.setHeader('Content-Type', 'text/plain');
27
+ res.end(param);
28
+ };
29
+ req.id = node_crypto_1.default.randomUUID();
30
+ res.setHeader("X-Request-Id", req.id);
31
+ };
32
+ const CreateSimpleJsHttpServer = (handler) => {
33
+ const middlewares = [];
34
+ const errorMiddlewares = [];
35
+ const plugins = [];
36
+ const server = http_1.default.createServer(async (req, res) => {
37
+ extension(req, res);
38
+ const run = (0, helpers_1.composeWithError)(middlewares, errorMiddlewares);
39
+ try {
40
+ handler && await handler(req, res);
41
+ if (res.writableEnded)
42
+ return;
43
+ await run(req, res);
44
+ //if the request has ended stop here
45
+ if (res.writableEnded)
46
+ return;
47
+ await (0, router_1.route)(req, res);
48
+ }
49
+ catch (err) {
50
+ // 1. Run error middlewares
51
+ for (const mw of errorMiddlewares) {
52
+ await mw(err, req, res, () => { });
53
+ }
54
+ // 2. Safe HTTP response fallback
55
+ if (!res.headersSent) {
56
+ res.statusCode = 503;
57
+ res.end("Service unavailable at the moment");
58
+ }
59
+ }
60
+ });
61
+ server.use = mw => { middlewares.push(mw); };
62
+ server.useError = mw => errorMiddlewares.push(mw);
63
+ server.register = async (plugin, opts) => {
64
+ plugins.push(plugin);
65
+ await plugin(server, opts);
66
+ };
67
+ return server;
68
+ };
69
+ exports.CreateSimpleJsHttpServer = CreateSimpleJsHttpServer;
@@ -0,0 +1,47 @@
1
+ import http, { IncomingMessage, ServerResponse } from "http";
2
+ export type Next = () => Promise<void> | void;
3
+ export type Plugin = (app: SimpleJsServer, opts?: any) => Promise<void> | void;
4
+ export type ObjectPayload = {
5
+ [key: string]: any;
6
+ };
7
+ export type Middleware = (req: RequestObject, res: ResponseObject, next: () => Promise<void> | void) => Promise<void> | void;
8
+ export type ErrorMiddleware = (err: any, req: RequestObject, res: ResponseObject, next: Next) => Promise<void> | void;
9
+ export interface SimpleJsServer extends http.Server {
10
+ use(mw: Middleware): Promise<any> | void;
11
+ useError: (mw: ErrorMiddleware) => void;
12
+ register: (plugin: Plugin, opts?: any) => Promise<void>;
13
+ _environment: 'dev' | 'stag' | 'live';
14
+ }
15
+ export interface RequestObject extends IncomingMessage {
16
+ body?: any;
17
+ query?: any;
18
+ _server_environment?: 'dev' | 'stag' | 'live';
19
+ id?: string;
20
+ }
21
+ export interface ResponseObject extends ServerResponse {
22
+ status: (value: number) => ResponseObject;
23
+ json: (value: object) => void;
24
+ text: (value?: string) => void;
25
+ }
26
+ export interface SubRequestHandler {
27
+ post?: (params: PrivateMethodProps) => void;
28
+ put?: (params: PrivateMethodProps) => void;
29
+ get?: (params: PrivateMethodProps) => void;
30
+ delete?: (params: PrivateMethodProps) => void;
31
+ patch?: (params: PrivateMethodProps) => void;
32
+ }
33
+ export interface PrivateMethodProps {
34
+ body: ObjectPayload;
35
+ res: ResponseObject;
36
+ req: RequestObject;
37
+ query: ObjectPayload;
38
+ id?: string;
39
+ idMethod?: {
40
+ post?: 'required' | 'optional';
41
+ get?: 'required' | 'optional';
42
+ put?: 'required' | 'optional';
43
+ delete?: 'required' | 'optional';
44
+ patch?: 'required' | 'optional';
45
+ };
46
+ }
47
+ export type AcceptHeaderValue = 'application/media' | 'application/text';
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ export type SimpleJSRateLimitType = {
2
+ windowMs: number;
3
+ max: number;
4
+ keyGenerator?: (req: any) => string;
5
+ };
6
+ export type SimpleJSBodyParseType = {
7
+ limit?: string | number;
8
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import { RequestObject, ResponseObject } from "../typings/general";
2
+ import { ErrorMiddleware, Middleware } from "../typings/general";
3
+ import { SimpleJSBodyParseType, SimpleJSRateLimitType } from "../typings/simpletypes";
4
+ export declare function SetRequestCORS(opts: {
5
+ name: string;
6
+ value: string;
7
+ }[]): (req: RequestObject, res: ResponseObject, next: any) => Promise<void>;
8
+ export declare function SetRateLimiter(opts: SimpleJSRateLimitType): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
9
+ export declare function SetBodyParser(opts: SimpleJSBodyParseType): (req: RequestObject, res: ResponseObject, next: () => Promise<any> | void) => Promise<void>;
10
+ export declare function composeWithError(middlewares: Middleware[], errorMiddlewares: ErrorMiddleware[]): (req: RequestObject, res: ResponseObject) => Promise<void>;
@@ -0,0 +1,169 @@
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.SetRequestCORS = SetRequestCORS;
7
+ exports.SetRateLimiter = SetRateLimiter;
8
+ exports.SetBodyParser = SetBodyParser;
9
+ exports.composeWithError = composeWithError;
10
+ const node_querystring_1 = __importDefault(require("node:querystring"));
11
+ // core/cors.ts
12
+ function SetRequestCORS(opts) {
13
+ return async (req, res, next) => {
14
+ const defaults = {
15
+ "Access-Control-Allow-Origin": "*",
16
+ "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization",
17
+ "Access-Control-Allow-Methods": "GET, POST, DELETE, PUT, PATCH",
18
+ "X-Content-Type-Options": "nosniff",
19
+ "X-Frame-Options": "DENY",
20
+ "Referrer-Policy": "no-referrer",
21
+ "Content-Security-Policy": "default-src 'none'",
22
+ };
23
+ let merged = { ...defaults };
24
+ for (const { name, value } of opts) {
25
+ merged[name] = value; // overrides defaults if same key
26
+ }
27
+ //allow credentials only when origin specified
28
+ if (merged["Access-Control-Allow-Credentials"] === "true") {
29
+ const origin = req.headers.origin;
30
+ res.status(403).end();
31
+ if (!origin)
32
+ return;
33
+ merged["Access-Control-Allow-Origin"] = origin;
34
+ }
35
+ for (const [key, value] of Object.entries(merged)) {
36
+ res.setHeader(key, value);
37
+ }
38
+ if (req.method === "OPTIONS") {
39
+ res.status(204).end();
40
+ return;
41
+ }
42
+ await next();
43
+ };
44
+ }
45
+ // core/rateLimit.ts
46
+ function SetRateLimiter(opts) {
47
+ const store = new Map();
48
+ const timer = setInterval(() => {
49
+ const now = Date.now();
50
+ for (const [k, v] of store) {
51
+ if (now - v.ts > opts.windowMs * 2)
52
+ store.delete(k);
53
+ }
54
+ }, opts.windowMs);
55
+ timer.unref();
56
+ return async (req, res, next) => {
57
+ const rawIp = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "unknown";
58
+ const ip = Array.isArray(rawIp) ? rawIp[0] : String(rawIp).split(",")[0].trim();
59
+ const key = String(opts.keyGenerator?.(req) || ip || "unknown");
60
+ const now = Date.now();
61
+ const entry = store.get(key) || { count: 0, ts: now };
62
+ if (now - entry.ts > opts.windowMs) {
63
+ entry.count = 0;
64
+ entry.ts = now;
65
+ }
66
+ entry.count++;
67
+ store.set(key, entry);
68
+ if (entry.count > opts.max) {
69
+ res.setHeader("Retry-After", Math.ceil(opts.windowMs / 1000));
70
+ res.status(429).json({ error: "Too Many Requests" });
71
+ return;
72
+ }
73
+ await next();
74
+ };
75
+ }
76
+ // core/body.ts
77
+ function SetBodyLimit(limit = "1mb") {
78
+ if (typeof limit === "number")
79
+ return limit;
80
+ const match = /^(\d+)(kb|mb)?$/i.exec(limit);
81
+ if (!match)
82
+ return 1024 * 1024;
83
+ const n = parseInt(match[1], 10);
84
+ const unit = match[2]?.toLowerCase();
85
+ if (unit === "kb")
86
+ return n * 1024;
87
+ if (unit === "mb")
88
+ return n * 1024 * 1024;
89
+ return n;
90
+ }
91
+ function SetBodyParser(opts) {
92
+ const maxSize = SetBodyLimit(opts.limit);
93
+ return async (req, res, next) => {
94
+ return new Promise(resolve => {
95
+ let size = 0;
96
+ let body = "";
97
+ req.on("data", chunk => {
98
+ size += chunk.length;
99
+ if (maxSize && size > maxSize) {
100
+ if (!res.writableEnded) {
101
+ res.status(413).json({ error: "Payload too large" });
102
+ }
103
+ req.destroy();
104
+ req.socket.destroy();
105
+ return;
106
+ }
107
+ //add the body
108
+ body += chunk;
109
+ });
110
+ req.on("end", () => {
111
+ if (res.writableEnded)
112
+ return resolve();
113
+ try {
114
+ if (body && !["application/text", "application/media"].includes(req.headers.accept)) {
115
+ req.body = JSON.parse(body);
116
+ //parse query
117
+ if (req.query) {
118
+ req.query = JSON.parse(JSON.stringify(node_querystring_1.default.parse(req.query)));
119
+ }
120
+ }
121
+ else {
122
+ req.body = body;
123
+ }
124
+ resolve(next());
125
+ }
126
+ catch (e) {
127
+ res.status(400).json({ error: "Invalid request body" });
128
+ return resolve();
129
+ }
130
+ });
131
+ req.on("error", () => {
132
+ if (!res.writableEnded) {
133
+ res.status(400).json({ error: "Request stream error" });
134
+ }
135
+ resolve();
136
+ });
137
+ });
138
+ };
139
+ }
140
+ function composeWithError(middlewares, errorMiddlewares) {
141
+ return async function (req, res) {
142
+ let idx = -1;
143
+ async function dispatch(i) {
144
+ if (i <= idx)
145
+ throw new Error("next() called twice");
146
+ idx = i;
147
+ const fn = middlewares[i];
148
+ if (!fn)
149
+ return;
150
+ try {
151
+ await fn(req, res, () => dispatch(i + 1));
152
+ }
153
+ catch (err) {
154
+ await dispatchError(err, 0);
155
+ }
156
+ }
157
+ async function dispatchError(err, i) {
158
+ const fn = errorMiddlewares[i];
159
+ if (!fn) {
160
+ if (!res.writableEnded) {
161
+ res.status(500).json({ error: "Unhandled error", detail: String(err) });
162
+ }
163
+ return;
164
+ }
165
+ await fn(err, req, res, () => dispatchError(err, i + 1));
166
+ }
167
+ await dispatch(0);
168
+ };
169
+ }
@@ -0,0 +1,18 @@
1
+ import { RequestObject, ResponseObject } from "../typings/general";
2
+ type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
3
+ type SubRequestHandler = Partial<Record<HttpMethod, (params: PrivateMethodProps) => any>>;
4
+ interface PrivateMethodProps {
5
+ id?: string;
6
+ idMethod?: Partial<Record<HttpMethod, "required" | "optional">>;
7
+ }
8
+ export declare class SimpleNodeJsController {
9
+ protected req: RequestObject;
10
+ protected res: ResponseObject;
11
+ /** framework-internal method */
12
+ _bindContext(ctx: {
13
+ req: RequestObject;
14
+ res: ResponseObject;
15
+ }): void;
16
+ protected RunRequest(handlers: SubRequestHandler, params?: PrivateMethodProps): any;
17
+ }
18
+ export {};
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SimpleNodeJsController = void 0;
4
+ class SimpleNodeJsController {
5
+ /** framework-internal method */
6
+ _bindContext(ctx) {
7
+ this.req = ctx.req;
8
+ this.res = ctx.res;
9
+ }
10
+ RunRequest(handlers, params) {
11
+ const method = this.req.method?.toLowerCase();
12
+ if (!method) {
13
+ return this.res.status(400).json({ code: 400, msg: "Invalid HTTP Method" });
14
+ }
15
+ const runFn = handlers[method];
16
+ if (typeof runFn !== "function") {
17
+ return this.res.status(405).json({ code: 405, msg: "Method Not Allowed" });
18
+ }
19
+ // ID validation rules
20
+ if (params && params.id && (!params.idMethod || !params.idMethod[method])) {
21
+ return this.res.status(404).json({ code: 404, msg: "Resource not found" });
22
+ }
23
+ if (params && params.idMethod?.[method] === "required" && !params.id) {
24
+ return this.res.status(404).json({ code: 404, msg: "Resource not found" });
25
+ }
26
+ return runFn({
27
+ ...(params || {}),
28
+ req: this.req,
29
+ res: this.res,
30
+ });
31
+ }
32
+ }
33
+ exports.SimpleNodeJsController = SimpleNodeJsController;
@@ -0,0 +1,9 @@
1
+ import { SimpleJsServer } from "../typings/general";
2
+ import { SimpleJSRateLimitType } from "../typings/simpletypes";
3
+ export declare function SecurityPlugin(app: SimpleJsServer, opts: {
4
+ cors?: {
5
+ name: string;
6
+ value: string;
7
+ }[];
8
+ rateLimit?: SimpleJSRateLimitType;
9
+ }): void;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SecurityPlugin = SecurityPlugin;
4
+ const helpers_1 = require("./helpers");
5
+ function SecurityPlugin(app, opts) {
6
+ app.use((0, helpers_1.SetRequestCORS)(opts.cors || []));
7
+ app.use((0, helpers_1.SetRateLimiter)(opts.rateLimit || { windowMs: 1000, max: 100 }));
8
+ }
package/package.json CHANGED
@@ -1,9 +1,15 @@
1
1
  {
2
2
  "name": "@increase21/simplenodejs",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Lightweight Node.js HTTP framework with middleware and plugins",
5
5
  "dev": "dist/index.js",
6
+ "bugs": "https://github.com/increase21/simplenodejs/issues",
6
7
  "types": "dist/index.d.ts",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/increase21/simplenodejs.git",
11
+ "directory": ""
12
+ },
7
13
  "files": [
8
14
  "dist/**/*"
9
15
  ],