barejs 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -1,81 +1,65 @@
1
-
2
- # 🏁 BareJS (v0.1.0-alpha)
3
-
4
- **The High-performance JIT-specialized web framework for Bun.** 🚀
5
-
6
- BareJS isn't just another framework; it's a high-speed engine engineered to outpace the fastest tools in the Bun ecosystem by utilizing **Static Code Injection** and **Zero-Allocation** routing.
7
-
8
- ## 📊 Performance Benchmark
9
- BareJS is designed for maximum throughput. In our latest head-to-head test against ElysiaJS:
10
-
11
- | Framework | Requests/sec | Avg Latency |
12
- |-----------|--------------|-------------|
13
- | **BareJS** | **7,416** | **1,335ms** |
14
- | ElysiaJS | 4,760 | 2,001ms |
15
-
16
- > **Result:** BareJS is **55.79% FASTER** than the competition.
17
-
18
- ---
19
-
20
- ## 🚀 Quick Start
21
-
22
- ### 1. Installation
23
- ```bash
24
- bun add barejs
25
-
26
- ```
27
-
28
- ### 2. Basic Usage
29
-
30
- ```typescript
31
- import { BareJS } from "barejs";
32
-
33
- const app = new BareJS();
34
-
35
- // Global Middleware
36
- app.use(async (ctx, next) => {
37
- const start = performance.now();
38
- await next();
39
- console.log(`Latency: ${performance.now() - start}ms`);
40
- });
41
-
42
- // Route with Auto-JSON Response
43
- app.get("/", () => ({ status: "BareJS is flying!" }));
44
-
45
- // Dynamic Route (Zero-Allocation)
46
- app.get("/user/:id", (ctx) => {
47
- return `User ID: ${ctx.params.id}`;
48
- });
49
-
50
- app.listen(3000);
51
-
52
- ```
53
-
54
- ---
55
-
56
- ## 🧠 Why is it so fast?
57
-
58
- 1. **JIT-First Compilation:** Unlike traditional frameworks that loop through arrays, BareJS compiles your entire route and middleware stack into a single, flat JavaScript function at startup. This allows the **JavaScriptCore JIT** to inline everything.
59
- 2. **Zero-Allocation Routing:** We use a frozen `EMPTY_PARAMS` object for static routes, reducing Garbage Collection (GC) pressure to nearly zero.
60
- 3. **Hyper-light Context:** The `ctx` object is kept minimal to ensure it stays within the CPU's L1/L2 cache during execution.
61
-
62
- ---
63
-
64
- ## 🧩 Plugin System
65
-
66
- BareJS supports a modular architecture. You can extend it easily:
67
-
68
- ```typescript
69
- const myPlugin = {
70
- name: 'my-plugin',
71
- setup: (app) => {
72
- app.use(async (ctx, next) => {
73
- ctx.customValue = "Hello";
74
- await next();
75
- });
76
- }
77
- };
78
-
79
- app.register(myPlugin);
80
-
81
- ```
1
+ # 🚀 BareJS
2
+
3
+ BareJS is an ultra-high-performance web engine built on the Bun runtime, designed for minimalism and the lowest possible latency.
4
+
5
+ ![Benchmark Status](https://github.com/xarhang/bareJS/actions/workflows/bench.yml/badge.svg)
6
+ [![Performance Dashboard](https://img.shields.io/badge/Performance-Dashboard-blueviolet?style=flat-square&logo=speedtest)](https://xarhang.github.io/bareJS/dev/benchmarks/)
7
+ [![Bun Version](https://img.shields.io/badge/Bun-%3E%3D1.0.0-black?style=flat-square&logo=bun)](https://bun.sh)
8
+
9
+ ---
10
+
11
+ ## 📊 Performance Benchmarks
12
+
13
+ Performance comparison between **BareJS**, **Elysia**, and **Hono**.
14
+
15
+ ### 🚀 Latest Benchmark Results
16
+ *Awaiting automated update...*
17
+
18
+ <!-- MARKER: PERFORMANCE_TABLE_START -->
19
+ | Framework | Latency (Avg) | Speed Ratio |
20
+ | :--- | :--- | :--- |
21
+ | **BareJS (Your Engine)** | **-- ns/iter** | **Baseline (1.0x)** |
22
+ | Elysia | -- ns/iter | --x slower |
23
+ | Hono | -- ns/iter | --x slower |
24
+ <!-- MARKER: PERFORMANCE_TABLE_END -->
25
+
26
+ <!-- NOTE: The table above is automatically updated via scripts/update-readme.ts -->
27
+
28
+ ---
29
+
30
+ ## ✨ Features
31
+
32
+ - **Ultra Low Latency:** Optimized to minimize processing overhead.
33
+ - **Zero Dependency:** Built natively for security and raw speed.
34
+ - **Optimized for Bun:** Leverages native Bun APIs for maximum performance.
35
+ - **Memory Efficient:** Minimal heap usage and clean garbage collection.
36
+
37
+ ## 🛠 Getting Started
38
+
39
+ ### Prerequisites
40
+ - [Bun](https://bun.sh) v1.0.0 or higher
41
+
42
+ ### Installation
43
+ ```bash
44
+ bun install
45
+ ```
46
+
47
+ ### Running Benchmarks Locally
48
+
49
+ ```bash
50
+ bun run benchmarks/index.ts
51
+
52
+ ```
53
+
54
+ ---
55
+
56
+ ## 🏗 Roadmap
57
+
58
+ * [x] Middleware Pattern Support (Chain Execution)
59
+ * [x] High-Speed Static Routing (O(1) Lookup Table)
60
+ * [x] Schema Validation Integration
61
+ * [ ] Full Documentation
62
+
63
+ ---
64
+
65
+ *Maintained by xarhang*
package/package.json CHANGED
@@ -1,22 +1,41 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
+ "author": "xarhang",
4
5
  "description": "High-performance JIT-specialized web framework for Bun",
5
6
  "main": "src/bare.ts",
6
7
  "types": "src/bare.ts",
7
8
  "type": "module",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/xarhang/barejs.git"
12
+ },
8
13
  "scripts": {
9
- "test": "echo \"Error: no test specified\" && exit 1"
14
+ "test": "echo \"Error: no test specified\" && exit 1",
15
+ "bench": "bun run benchmarks/index.ts",
16
+ "dev": "bun --watch src/bare.ts"
10
17
  },
11
18
  "keywords": [
12
19
  "bun",
13
20
  "framework",
14
21
  "fastest",
15
- "jit"
22
+ "jit",
23
+ "typebox",
24
+ "zod"
16
25
  ],
17
- "author": "xarhang",
18
26
  "license": "MIT",
27
+ "dependencies": {
28
+ "@sinclair/typebox": "^0.34.46",
29
+ "zod": "^4.3.5"
30
+ },
19
31
  "devDependencies": {
20
- "@types/bun": "latest"
21
- }
32
+ "@types/bun": "latest",
33
+ "elysia": "^1.4.21",
34
+ "hono": "^4.11.3",
35
+ "mitata": "^1.0.34"
36
+ },
37
+ "files": [
38
+ "src",
39
+ "README.md"
40
+ ]
22
41
  }
package/src/bare.ts CHANGED
@@ -1,29 +1,74 @@
1
- export interface Context {
2
- req: Request;
3
- params: Record<string, string>;
4
- json: (data: any) => Response;
5
- [key: string]: any;
6
- }
7
- export type Handler = (ctx: Context) => any;
8
- export type Middleware = (ctx: Context, next: () => Promise<any> | any) => any;
9
-
10
- export class BareJS {
11
- private routes: { method: string; path: string; handlers: (Middleware | Handler)[] }[] = [];
12
- private globalMiddlewares: Middleware[] = [];
13
- private compiledFetch?: (req: Request) => Promise<Response>;
14
-
15
- public get = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "GET", path, handlers: h }); return this; };
16
- public use = (m: Middleware) => { this.globalMiddlewares.push(m); return this; };
17
-
18
- private compile() {
19
- let fnBody = "const gMW = this.globalMiddlewares; const allRoutes = this.routes; const EMPTY_PARAMS = Object.freeze({}); return async (req) => { const url = req.url; const pathStart = url.indexOf('/', 8); const path = pathStart === -1 ? '/' : url.substring(pathStart); const method = req.method;";
20
- // (Logic การ Compile เหมือนที่คุยกันไว้)
21
- fnBody += "return new Response('404', { status: 404 }); };";
22
- this.compiledFetch = new Function(fnBody).bind(this)();
23
- }
24
-
25
- listen(port = 3000) {
26
- this.compile();
27
- return Bun.serve({ port, fetch: (req) => this.compiledFetch!(req) });
28
- }
29
- }
1
+ export interface Context {
2
+ req: Request;
3
+ params: Record<string, string>;
4
+ json: (data: any) => Response;
5
+ body?: any;
6
+ [key: string]: any;
7
+ }
8
+
9
+ export type Next = () => Promise<any> | any;
10
+ export type Middleware = (ctx: Context, next: Next) => any;
11
+ export type Handler = (ctx: Context) => any;
12
+
13
+ export class BareJS {
14
+ private routes: { method: string; path: string; handlers: (Middleware | Handler)[] }[] = [];
15
+ private globalMiddlewares: Middleware[] = [];
16
+ private compiledFetch?: (req: Request) => Promise<Response>;
17
+ private staticMap: Record<string, any> = {};
18
+
19
+ public post = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "POST", path, handlers: h }); return this; };
20
+ public put = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "PUT", path, handlers: h }); return this; };
21
+ public patch = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "PATCH", path, handlers: h }); return this; };
22
+ public delete = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "DELETE", path, handlers: h }); return this; };
23
+ public get = (path: string, ...h: (Middleware | Handler)[]) => { this.routes.push({ method: "GET", path, handlers: h }); return this; };
24
+ public use = (...m: Middleware[]) => { this.globalMiddlewares.push(...m); return this; };
25
+
26
+ public fetch = (req: Request): Promise<Response> | Response => {
27
+ if (!this.compiledFetch) this.compile();
28
+ return this.compiledFetch!(req);
29
+ }
30
+
31
+ private compile() {
32
+ this.routes.forEach((route) => {
33
+ const chain = (ctx: Context) => {
34
+ let idx = 0;
35
+ const middlewares = [...this.globalMiddlewares, ...route.handlers];
36
+ const next = (): any => {
37
+ const handler = middlewares[idx++];
38
+ if (!handler) return;
39
+ return handler(ctx, next);
40
+ };
41
+ return next();
42
+ };
43
+ this.staticMap[`${route.method}:${route.path}`] = chain;
44
+ });
45
+
46
+ const fnBody = `
47
+ const staticMap = this.staticMap;
48
+ const EMPTY_PARAMS = Object.freeze({});
49
+ const jsonHeader = { "content-type": "application/json" };
50
+ return (req) => {
51
+ const url = req.url;
52
+ const pathStart = url.indexOf('/', 8);
53
+ const path = pathStart === -1 ? '/' : url.substring(pathStart);
54
+ const key = req.method + ":" + path;
55
+ const runner = staticMap[key];
56
+ if (runner) {
57
+ const ctx = { req, params: EMPTY_PARAMS, json: (d) => new Response(JSON.stringify(d), { headers: jsonHeader }) };
58
+ return runner(ctx);
59
+ }
60
+ return new Response('404 Not Found', { status: 404 });
61
+ };`;
62
+ this.compiledFetch = new Function(fnBody).bind(this)();
63
+ }
64
+
65
+ listen(ip: string = '0.0.0.0', port: number = 3000) {
66
+ this.compile();
67
+ console.log(`🚀 BareJS running at http://${ip}:${port}`);
68
+ return Bun.serve({
69
+ hostname: ip,
70
+ port,
71
+ fetch: (req) => this.compiledFetch!(req),
72
+ });
73
+ }
74
+ }
@@ -0,0 +1,53 @@
1
+ import * as Compiler from '@sinclair/typebox/compiler';
2
+
3
+ /**
4
+ * 1. TypeBox Validator: Highest Performance (JIT Optimized)
5
+ * Best for: Production and Benchmarking
6
+ */
7
+ export const typebox = (schema: any) => {
8
+ const check = Compiler.TypeCompiler.Compile(schema);
9
+ return async (ctx: any, next: any) => {
10
+ try {
11
+ const body = await ctx.req.json();
12
+ if (!check.Check(body)) return new Response("TypeBox Validation Failed", { status: 400 });
13
+ ctx.body = body;
14
+ return next();
15
+ } catch { return new Response("Invalid JSON", { status: 400 }); }
16
+ };
17
+ };
18
+
19
+ /**
20
+ * 2. Native Validator: Zero Dependency
21
+ * Best for: Avoiding Runtime bugs or keeping the bundle lightweight.
22
+ */
23
+ export const native = (schema: any) => {
24
+ const properties = schema.properties || {};
25
+ const keys = Object.keys(properties);
26
+ return async (ctx: any, next: any) => {
27
+ try {
28
+ const body = await ctx.req.json();
29
+ for (const key of keys) {
30
+ if (typeof body[key] !== properties[key].type)
31
+ return new Response(`Native Validation Failed: ${key} is not ${properties[key].type}`, { status: 400 });
32
+ }
33
+ ctx.body = body;
34
+ return next();
35
+ } catch { return new Response("Invalid JSON", { status: 400 }); }
36
+ };
37
+ };
38
+
39
+ /**
40
+ * 3. Zod Validator: Best Developer Experience
41
+ * Note: Requires 'npm install zod'
42
+ */
43
+ export const zod = (schema: any) => {
44
+ return async (ctx: any, next: any) => {
45
+ try {
46
+ const body = await ctx.req.json();
47
+ const result = schema.safeParse(body);
48
+ if (!result.success) return new Response(JSON.stringify(result.error), { status: 400 });
49
+ ctx.body = result.data;
50
+ return next();
51
+ } catch { return new Response("Invalid JSON", { status: 400 }); }
52
+ };
53
+ };
package/bun.lock DELETED
@@ -1,25 +0,0 @@
1
- {
2
- "lockfileVersion": 1,
3
- "workspaces": {
4
- "": {
5
- "name": "barejs-release",
6
- "devDependencies": {
7
- "@types/bun": "latest",
8
- },
9
- "peerDependencies": {
10
- "typescript": "^5",
11
- },
12
- },
13
- },
14
- "packages": {
15
- "@types/bun": ["@types/bun@1.3.5", "", { "dependencies": { "bun-types": "1.3.5" } }, "sha512-RnygCqNrd3srIPEWBd5LFeUYG7plCoH2Yw9WaZGyNmdTEei+gWaHqydbaIRkIkcbXwhBT94q78QljxN0Sk838w=="],
16
-
17
- "@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
18
-
19
- "bun-types": ["bun-types@1.3.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-inmAYe2PFLs0SUbFOWSVD24sg1jFlMPxOjOSSCYqUgn4Hsc3rDc7dFvfVYjFPNHtov6kgUeulV4SxbuIV/stPw=="],
20
-
21
- "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
22
-
23
- "undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
24
- }
25
- }
package/index.ts DELETED
@@ -1 +0,0 @@
1
- console.log("Hello via Bun!");
package/tsconfig.json DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- // Environment setup & latest features
4
- "lib": ["ESNext"],
5
- "target": "ESNext",
6
- "module": "Preserve",
7
- "moduleDetection": "force",
8
- "jsx": "react-jsx",
9
- "allowJs": true,
10
-
11
- // Bundler mode
12
- "moduleResolution": "bundler",
13
- "allowImportingTsExtensions": true,
14
- "verbatimModuleSyntax": true,
15
- "noEmit": true,
16
-
17
- // Best practices
18
- "strict": true,
19
- "skipLibCheck": true,
20
- "noFallthroughCasesInSwitch": true,
21
- "noUncheckedIndexedAccess": true,
22
- "noImplicitOverride": true,
23
-
24
- // Some stricter flags (disabled by default)
25
- "noUnusedLocals": false,
26
- "noUnusedParameters": false,
27
- "noPropertyAccessFromIndexSignature": false
28
- }
29
- }