bini-server 1.0.0 → 1.0.1

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Binidu Ranasinghe
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Binidu Ranasinghe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,203 +1,257 @@
1
- # bini-server
2
-
3
- <div align="center">
4
-
5
- [![npm version](https://img.shields.io/npm/v/bini-server?color=00CFFF&labelColor=0a0a0a&style=flat-square)](https://www.npmjs.com/package/bini-server)
6
- [![license](https://img.shields.io/badge/license-MIT-00CFFF?labelColor=0a0a0a&style=flat-square)](./LICENSE)
7
- [![node](https://img.shields.io/badge/node-%3E%3D22-00CFFF?labelColor=0a0a0a&style=flat-square)](https://nodejs.org)
8
- [![zero deps](https://img.shields.io/badge/dependencies-0-00CFFF?labelColor=0a0a0a&style=flat-square)](./package.json)
9
-
10
- **Zero-dependency production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
11
- Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handlers — just like Vite's preview server, but for production.
12
-
13
- </div>
14
-
15
- ---
16
-
17
- ## Features
18
-
19
- - ⚡ **Zero dependencies** — pure Node.js built-ins only
20
- - 🗂️ **Static file serving** — streams `dist/` with correct MIME types and cache headers
21
- - 🌐 **API routes** — proxies `/api/*` to your `src/app/api/` handlers (Hono apps + plain functions)
22
- - 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
23
- - 🛡️ **CORS** — enabled by default on all API responses
24
- - ⏱️ **Timeouts** — 30s body read + 30s handler timeout with proper error responses
25
- - 🔒 **Body limit** — 10MB request body limit
26
- - 🔌 **Port auto-increment** — starts at 3000, increments if busy
27
- - 🪄 **Graceful shutdown** — handles SIGTERM + SIGINT with 10s force-exit fallback
28
- - 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
29
-
30
- ---
31
-
32
- ## Requirements
33
-
34
- - Node.js **≥ 22**
35
- - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
36
-
37
- ---
38
-
39
- ## Install
40
-
41
- ```bash
42
- npm install bini-server
43
- ```
44
-
45
- ---
46
-
47
- ## Usage
48
-
49
- Add to your `package.json`:
50
-
51
- ```json
52
- {
53
- "scripts": {
54
- "build": "vite build",
55
- "start": "bini-server"
56
- }
57
- }
58
- ```
59
-
60
- Then:
61
-
62
- ```bash
63
- npm run build # build your app
64
- npm start # serve it in production
65
- ```
66
-
67
- Terminal output:
68
-
69
- ```
70
- ß Bini.js (production)
71
-
72
- ➜ Environments: .env, .env.production
73
- ➜ Local: http://localhost:3000/
74
- ➜ Network: http://192.168.1.5:3000/
75
- ```
76
-
77
- ---
78
-
79
- ## How it works
80
-
81
- `bini-server` runs a plain Node.js `http` server with a three-layer middleware stack:
82
-
83
- ```
84
- Request
85
- │
86
- ├─ /api/* → src/app/api/ handlers (Hono apps or plain functions)
87
- │
88
- ├─ /* → stream static file from dist/
89
- │
90
- └─ /* → dist/index.html (SPA fallback)
91
- ```
92
-
93
- No Vite, no Express, no Fastify — just Node's built-in `http` module.
94
-
95
- ---
96
-
97
- ## Port
98
-
99
- Default port is `3000`. Override via environment variable:
100
-
101
- ```bash
102
- PORT=8080 bini-server
103
- ```
104
-
105
- If the port is busy, `bini-server` automatically increments and warns:
106
-
107
- ```
108
- ⚠ Port 3000 is in use, using port 3001 instead.
109
- ```
110
-
111
- ---
112
-
113
- ## API Routes
114
-
115
- `bini-server` reads `src/app/api/` directly — the same files your dev server uses. Both Hono apps and plain function handlers are supported:
116
-
117
- ```ts
118
- // src/app/api/hello.ts
119
-
120
- // ✅ Hono app
121
- import { Hono } from 'hono'
122
- const app = new Hono().basePath('/api')
123
- app.get('/hello', (c) => c.json({ message: 'hello' }))
124
- export default app
125
-
126
- // ✅ Plain function
127
- export default function handler(req: Request) {
128
- return Response.json({ message: 'hello' })
129
- }
130
- ```
131
-
132
- ---
133
-
134
- ## Deployment
135
-
136
- ### VPS (Ubuntu, Debian, etc.)
137
-
138
- ```bash
139
- npm run build
140
- npm start
141
- ```
142
-
143
- Use [pm2](https://pm2.keymetrics.io/) to keep it running:
144
-
145
- ```bash
146
- npm install -g pm2
147
- pm2 start "npm start" --name my-app
148
- pm2 save
149
- pm2 startup
150
- ```
151
-
152
- ### Railway
153
-
154
- Set start command to `npm start` in your Railway project settings. Railway injects `PORT` automatically.
155
-
156
- ### Render
157
-
158
- Set start command to `npm start`. Render injects `PORT` automatically.
159
-
160
- ### Fly.io
161
-
162
- ```toml
163
- # fly.toml
164
- [processes]
165
- app = "npm start"
166
- ```
167
-
168
- ---
169
-
170
- ## Project structure
171
-
172
- `bini-server` expects the standard bini-router project layout:
173
-
174
- ```
175
- my-app/
176
- ├── src/
177
- │ └── app/
178
- │ └── api/ ← API route handlers
179
- ├── dist/ ← built frontend (vite build output)
180
- └── package.json
181
- ```
182
-
183
- ---
184
-
185
- ## vs `vite preview`
186
-
187
- | Feature | `vite preview` | `bini-server` |
188
- |---|---|---|
189
- | Serves `dist/` | ✅ | ✅ |
190
- | API routes | ✅ via bini-router | ✅ via bini-router |
191
- | SPA fallback | ✅ | ✅ |
192
- | Production use | ❌ not recommended | ✅ |
193
- | Body timeout | ❌ | ✅ 30s |
194
- | Body size limit | ❌ | ✅ 10MB |
195
- | Handler timeout | ❌ | ✅ 30s |
196
- | Graceful shutdown | ❌ | ✅ |
197
- | Zero dependencies | ✅ | ✅ |
198
-
199
- ---
200
-
201
- ## License
202
-
1
+ # bini-server
2
+
3
+ <div align="center">
4
+
5
+ [![npm version](https://img.shields.io/npm/v/bini-server?color=00CFFF&labelColor=0a0a0a&style=flat-square)](https://www.npmjs.com/package/bini-server)
6
+ [![license](https://img.shields.io/badge/license-MIT-00CFFF?labelColor=0a0a0a&style=flat-square)](./LICENSE)
7
+ [![node](https://img.shields.io/badge/node-%3E%3D18-00CFFF?labelColor=0a0a0a&style=flat-square)](https://nodejs.org)
8
+ [![bini-env](https://img.shields.io/badge/bini--env-powered-00CFFF?labelColor=0a0a0a&style=flat-square)](https://www.npmjs.com/package/bini-env)
9
+
10
+ **Zero-dependency production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
11
+ Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handlers — just like Vite's preview server, but for production.
12
+
13
+ </div>
14
+
15
+ ---
16
+
17
+ ## Features
18
+
19
+ - ⚡ **Zero dependencies** — pure Node.js built-ins only
20
+ - 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
21
+ - 🌐 **API routes** — proxies `/api/*` to your `src/app/api/` handlers (Hono apps + plain functions)
22
+ - 🔀 **SPA fallback** — unknown routes serve `dist/index.html`
23
+ - 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env) — no dotenv setup needed
24
+ - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
25
+ - 🛡️ **CORS** — enabled by default on all API responses
26
+ - ⏱️ **Timeouts** — 30s body read + 30s handler timeout with proper error responses
27
+ - 🔒 **Body limit** — 10MB request body limit
28
+ - 🔌 **Port auto-increment** — starts at 3000, increments if busy
29
+ - 🪄 **Graceful shutdown** — handles SIGTERM + SIGINT with 10s force-exit fallback
30
+ - 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
31
+
32
+ ---
33
+
34
+ ## Requirements
35
+
36
+ - Node.js **≥ 18**
37
+ - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
38
+
39
+ ---
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ npm install bini-server
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Usage
50
+
51
+ Add to your `package.json`:
52
+
53
+ ```json
54
+ {
55
+ "scripts": {
56
+ "build": "vite build",
57
+ "start": "bini-server"
58
+ }
59
+ }
60
+ ```
61
+
62
+ Then:
63
+
64
+ ```bash
65
+ npm run build # build your app
66
+ npm start # serve it in production
67
+ ```
68
+
69
+ Terminal output:
70
+
71
+ ```
72
+ ß Bini.js (production)
73
+
74
+ ➜ Environments: .env
75
+ ➜ Local: http://localhost:3000/
76
+ ➜ Network: http://192.168.1.5:3000/
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Environment Variables
82
+
83
+ bini-server uses [bini-env](https://www.npmjs.com/package/bini-env) to automatically load `.env` before the server starts — no manual dotenv setup needed.
84
+
85
+ ```env
86
+ # .env
87
+ PORT=3000
88
+
89
+ # Server-side vars — used by API routes via getEnv() / requireEnv()
90
+ SMTP_USER=user@smtp.example.com
91
+ SMTP_PASS=your_password
92
+ FROM_EMAIL=App <noreply@example.com>
93
+
94
+ # Client-side vars — already baked into dist/ at build time, ignored by server
95
+ BINI_FIREBASE_API_KEY=your_key
96
+ ```
97
+
98
+ > Client-side `BINI_*` vars are baked into `dist/` at build time by Vite — bini-server loads them into `process.env` but never uses them. They don't cause any errors.
99
+
100
+ ---
101
+
102
+ ## How it works
103
+
104
+ bini-server runs a plain Node.js `http` server with a three-layer middleware stack:
105
+
106
+ ```
107
+ Request
108
+ │
109
+ ├─ /api/* → src/app/api/ handlers (Hono apps or plain functions)
110
+ │
111
+ ├─ /* → stream static file from dist/ (with ETag + cache headers)
112
+ │
113
+ └─ /* → dist/index.html (SPA fallback)
114
+ ```
115
+
116
+ No Vite, no Express, no Fastify — just Node's built-in `http` module.
117
+
118
+ ---
119
+
120
+ ## Port
121
+
122
+ Default port is `3000`. Override via environment variable:
123
+
124
+ ```bash
125
+ PORT=8080 bini-server
126
+ ```
127
+
128
+ Or in `.env`:
129
+
130
+ ```env
131
+ PORT=8080
132
+ ```
133
+
134
+ If the port is busy, bini-server automatically increments and warns:
135
+
136
+ ```
137
+ ⚠ Port 3000 is in use, using port 3001 instead.
138
+ ```
139
+
140
+ ---
141
+
142
+ ## Configurable Directories
143
+
144
+ By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars if your project uses a different structure:
145
+
146
+ ```env
147
+ BINI_API_DIR=src/api # default: src/app/api
148
+ BINI_DIST_DIR=build # default: dist
149
+ ```
150
+
151
+ ---
152
+
153
+ ## API Routes
154
+
155
+ bini-server reads `src/app/api/` directly — the same files your dev server uses. Both Hono apps and plain function handlers are supported. `getEnv` and `requireEnv` are auto-imported by bini-router so no imports needed:
156
+
157
+ ```ts
158
+ // src/app/api/email.ts
159
+ import { Hono } from 'hono'
160
+ import nodemailer from 'nodemailer'
161
+
162
+ const app = new Hono().basePath('/api')
163
+
164
+ const transporter = nodemailer.createTransport({
165
+ host: 'smtp-relay.brevo.com',
166
+ port: 587,
167
+ auth: {
168
+ user: requireEnv('SMTP_USER'), // auto-imported, throws if missing
169
+ pass: requireEnv('SMTP_PASS'),
170
+ },
171
+ })
172
+
173
+ app.post('/email', async (c) => {
174
+ const { to, subject, html } = await c.req.json()
175
+ await transporter.sendMail({ from: requireEnv('FROM_EMAIL'), to, subject, html })
176
+ return c.json({ ok: true })
177
+ })
178
+
179
+ export default app
180
+ ```
181
+
182
+ ---
183
+
184
+ ## Deployment
185
+
186
+ ### VPS (Ubuntu, Debian, etc.)
187
+
188
+ ```bash
189
+ npm run build
190
+ npm start
191
+ ```
192
+
193
+ Use [pm2](https://pm2.keymetrics.io/) to keep it running:
194
+
195
+ ```bash
196
+ npm install -g pm2
197
+ pm2 start "npm start" --name my-app
198
+ pm2 save
199
+ pm2 startup
200
+ ```
201
+
202
+ ### Railway
203
+
204
+ Set start command to `npm start` in your Railway project settings. Railway injects `PORT` automatically.
205
+
206
+ ### Render
207
+
208
+ Set start command to `npm start`. Render injects `PORT` automatically.
209
+
210
+ ### Fly.io
211
+
212
+ ```toml
213
+ # fly.toml
214
+ [processes]
215
+ app = "npm start"
216
+ ```
217
+
218
+ ---
219
+
220
+ ## Project structure
221
+
222
+ bini-server expects the standard bini-router project layout:
223
+
224
+ ```
225
+ my-app/
226
+ ├── src/
227
+ │ └── app/
228
+ │ └── api/ ← API route handlers
229
+ ├── dist/ ← built frontend (vite build output)
230
+ ├── .env ← environment variables
231
+ └── package.json
232
+ ```
233
+
234
+ ---
235
+
236
+ ## vs `vite preview`
237
+
238
+ | Feature | `vite preview` | `bini-server` |
239
+ |---|---|---|
240
+ | Serves `dist/` | ✅ | ✅ |
241
+ | API routes | ✅ via bini-router | ✅ via bini-router |
242
+ | SPA fallback | ✅ | ✅ |
243
+ | Auto env loading | ✅ via bini-env | ✅ via bini-env |
244
+ | ETag / 304 support | ❌ | ✅ |
245
+ | Production use | ❌ not recommended | ✅ |
246
+ | Body timeout | ❌ | ✅ 30s |
247
+ | Body size limit | ❌ | ✅ 10MB |
248
+ | Handler timeout | ❌ | ✅ 30s |
249
+ | Graceful shutdown | ❌ | ✅ |
250
+ | Configurable dirs | ❌ | ✅ |
251
+ | Zero dependencies | ✅ | ✅ |
252
+
253
+ ---
254
+
255
+ ## License
256
+
203
257
  MIT © [Binidu Ranasinghe](https://bini.js.org)
package/dist/cli.js CHANGED
@@ -6,12 +6,14 @@ import fs from "fs";
6
6
  import path from "path";
7
7
  import os from "os";
8
8
  import net from "net";
9
+ import crypto from "crypto";
9
10
  import { pathToFileURL } from "url";
10
11
  import { pipeline } from "stream/promises";
11
12
  import { createReadStream } from "fs";
13
+ import { loadEnv, detectEnvFiles } from "bini-env";
12
14
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
13
- var API_DIR = path.join(process.cwd(), "src/app/api");
14
- var DIST_DIR = path.join(process.cwd(), "dist");
15
+ var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
16
+ var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
15
17
  var API_EXTS = [".ts", ".js"];
16
18
  var BODY_TIMEOUT = 3e4;
17
19
  var HANDLER_TIMEOUT = 3e4;
@@ -36,19 +38,9 @@ function getAllNetworkIps() {
36
38
  }
37
39
  return [...new Set(ips)];
38
40
  }
39
- function detectEnvFiles() {
40
- const nodeEnv = process.env.NODE_ENV ?? "production";
41
- const candidates = [
42
- ".env.local",
43
- `.env.${nodeEnv}.local`,
44
- `.env.${nodeEnv}`,
45
- ".env"
46
- ];
47
- return candidates.filter((f) => fs.existsSync(path.join(process.cwd(), f)));
48
- }
49
41
  function printBanner(port) {
50
42
  const networkIps = getAllNetworkIps();
51
- const envFiles = detectEnvFiles();
43
+ const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
52
44
  console.log(`
53
45
  ${C.CYAN}\xDF Bini.js${C.RESET} (production)
54
46
  `);
@@ -61,7 +53,7 @@ function printBanner(port) {
61
53
  }
62
54
  if (!fs.existsSync(API_DIR)) {
63
55
  console.log(`
64
- ${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
56
+ ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
65
57
  }
66
58
  console.log("");
67
59
  }
@@ -147,10 +139,15 @@ async function importHandler(filePath) {
147
139
  }
148
140
  const cached = moduleCache.get(filePath);
149
141
  if (cached && cached.mtime === mtime) return cached.handler;
150
- const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
151
- const handler = mod.default ?? null;
152
- moduleCache.set(filePath, { mtime, handler });
153
- return handler;
142
+ try {
143
+ const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
144
+ const handler = mod.default ?? null;
145
+ moduleCache.set(filePath, { mtime, handler });
146
+ return handler;
147
+ } catch (e) {
148
+ moduleCache.delete(filePath);
149
+ throw e;
150
+ }
154
151
  }
155
152
  function readBody(req) {
156
153
  return new Promise((resolve, reject) => {
@@ -172,7 +169,7 @@ function readBody(req) {
172
169
  });
173
170
  req.on("end", () => {
174
171
  clearTimeout(timeout);
175
- resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
172
+ resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
176
173
  });
177
174
  req.on("error", (err) => {
178
175
  clearTimeout(timeout);
@@ -181,16 +178,19 @@ function readBody(req) {
181
178
  });
182
179
  }
183
180
  function normalizeHeaders(raw) {
184
- return Object.fromEntries(
185
- Object.entries(raw).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v])
186
- );
181
+ const out = {};
182
+ for (const [k, v] of Object.entries(raw)) {
183
+ if (v === void 0) continue;
184
+ out[k] = Array.isArray(v) ? k.toLowerCase() === "cookie" ? v.join("; ") : v.join(", ") : v;
185
+ }
186
+ return out;
187
187
  }
188
- var routeCache = null;
189
188
  var CORS_HEADERS = {
190
189
  "Access-Control-Allow-Origin": "*",
191
190
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
192
191
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
193
192
  };
193
+ var routeCache = null;
194
194
  async function handleApiRequest(req, res, next) {
195
195
  try {
196
196
  if (req.method === "OPTIONS") {
@@ -219,7 +219,14 @@ async function handleApiRequest(req, res, next) {
219
219
  body: body ?? null
220
220
  });
221
221
  for (const route of routeCache.routes) {
222
- const handler = await importHandler(route.filePath);
222
+ let handler;
223
+ try {
224
+ handler = await importHandler(route.filePath);
225
+ } catch (e) {
226
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
227
+ res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
228
+ return;
229
+ }
223
230
  if (!handler) continue;
224
231
  let webRes;
225
232
  try {
@@ -276,22 +283,30 @@ async function handleApiRequest(req, res, next) {
276
283
  var MIME = {
277
284
  ".html": "text/html; charset=utf-8",
278
285
  ".js": "application/javascript",
286
+ ".mjs": "application/javascript",
279
287
  ".css": "text/css",
280
288
  ".json": "application/json",
281
289
  ".png": "image/png",
282
290
  ".jpg": "image/jpeg",
283
291
  ".jpeg": "image/jpeg",
292
+ ".gif": "image/gif",
284
293
  ".svg": "image/svg+xml",
285
294
  ".ico": "image/x-icon",
286
295
  ".webp": "image/webp",
296
+ ".avif": "image/avif",
287
297
  ".woff": "font/woff",
288
298
  ".woff2": "font/woff2",
289
299
  ".ttf": "font/ttf",
290
300
  ".eot": "application/vnd.ms-fontobject",
291
301
  ".txt": "text/plain",
292
- ".webmanifest": "application/manifest+json"
302
+ ".xml": "application/xml",
303
+ ".webmanifest": "application/manifest+json",
304
+ ".map": "application/json"
293
305
  };
294
- async function sendFile(filePath, res) {
306
+ function getETag(stat) {
307
+ return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
308
+ }
309
+ async function sendFile(filePath, req, res) {
295
310
  const ext = path.extname(filePath).toLowerCase();
296
311
  const mimeType = MIME[ext] ?? "application/octet-stream";
297
312
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -303,12 +318,24 @@ async function sendFile(filePath, res) {
303
318
  res.end("Not found");
304
319
  return;
305
320
  }
321
+ const etag = getETag(stat);
322
+ const ifNoneMatch = req.headers["if-none-match"];
323
+ if (ifNoneMatch === etag) {
324
+ res.writeHead(304);
325
+ res.end();
326
+ return;
327
+ }
306
328
  res.writeHead(200, {
307
329
  "Content-Type": mimeType,
308
330
  "Content-Length": stat.size,
309
331
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
332
+ "ETag": etag,
310
333
  "X-Powered-By": "Bini.js"
311
334
  });
335
+ if (req.method === "HEAD") {
336
+ res.end();
337
+ return;
338
+ }
312
339
  try {
313
340
  await pipeline(createReadStream(filePath), res);
314
341
  } catch {
@@ -318,12 +345,12 @@ async function serveStatic(req, res, next) {
318
345
  const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
319
346
  const filePath = path.join(DIST_DIR, pathname);
320
347
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
321
- await sendFile(filePath, res);
348
+ await sendFile(filePath, req, res);
322
349
  return;
323
350
  }
324
351
  const indexPath = path.join(DIST_DIR, "index.html");
325
352
  if (fs.existsSync(indexPath)) {
326
- await sendFile(indexPath, res);
353
+ await sendFile(indexPath, req, res);
327
354
  return;
328
355
  }
329
356
  next();
@@ -334,12 +361,20 @@ function compose(middlewares) {
334
361
  async function next() {
335
362
  if (idx >= middlewares.length) return;
336
363
  const fn = middlewares[idx++];
337
- await fn(req, res, next);
364
+ try {
365
+ await fn(req, res, next);
366
+ } catch (e) {
367
+ if (!res.headersSent) {
368
+ res.writeHead(500, { "Content-Type": "application/json" });
369
+ res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
370
+ }
371
+ }
338
372
  }
339
373
  await next();
340
374
  };
341
375
  }
342
376
  async function start() {
377
+ await loadEnv(process.cwd());
343
378
  if (!fs.existsSync(DIST_DIR)) {
344
379
  console.error(`
345
380
  ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
@@ -359,6 +394,7 @@ async function start() {
359
394
  }
360
395
  ]);
361
396
  const server = http.createServer((req, res) => {
397
+ res.setHeader("Connection", "keep-alive");
362
398
  handler(req, res).catch(() => {
363
399
  if (!res.headersSent) {
364
400
  res.writeHead(500);
@@ -366,10 +402,15 @@ async function start() {
366
402
  }
367
403
  });
368
404
  });
405
+ server.keepAliveTimeout = 65e3;
406
+ server.headersTimeout = 66e3;
369
407
  server.listen(port, "0.0.0.0", () => {
370
408
  printBanner(port);
371
409
  });
372
410
  function shutdown() {
411
+ console.log(`
412
+ ${C.YELLOW}\u26A0${C.RESET} Shutting down...
413
+ `);
373
414
  server.close(() => process.exit(0));
374
415
  setTimeout(() => process.exit(1), 1e4).unref();
375
416
  }
@@ -378,4 +419,7 @@ async function start() {
378
419
  }
379
420
 
380
421
  // src/cli.ts
381
- start();
422
+ start().catch((err) => {
423
+ console.error(err);
424
+ process.exit(1);
425
+ });
package/dist/index.js CHANGED
@@ -4,12 +4,14 @@ import fs from "fs";
4
4
  import path from "path";
5
5
  import os from "os";
6
6
  import net from "net";
7
+ import crypto from "crypto";
7
8
  import { pathToFileURL } from "url";
8
9
  import { pipeline } from "stream/promises";
9
10
  import { createReadStream } from "fs";
11
+ import { loadEnv, detectEnvFiles } from "bini-env";
10
12
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
11
- var API_DIR = path.join(process.cwd(), "src/app/api");
12
- var DIST_DIR = path.join(process.cwd(), "dist");
13
+ var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
14
+ var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
13
15
  var API_EXTS = [".ts", ".js"];
14
16
  var BODY_TIMEOUT = 3e4;
15
17
  var HANDLER_TIMEOUT = 3e4;
@@ -34,19 +36,9 @@ function getAllNetworkIps() {
34
36
  }
35
37
  return [...new Set(ips)];
36
38
  }
37
- function detectEnvFiles() {
38
- const nodeEnv = process.env.NODE_ENV ?? "production";
39
- const candidates = [
40
- ".env.local",
41
- `.env.${nodeEnv}.local`,
42
- `.env.${nodeEnv}`,
43
- ".env"
44
- ];
45
- return candidates.filter((f) => fs.existsSync(path.join(process.cwd(), f)));
46
- }
47
39
  function printBanner(port) {
48
40
  const networkIps = getAllNetworkIps();
49
- const envFiles = detectEnvFiles();
41
+ const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
50
42
  console.log(`
51
43
  ${C.CYAN}\xDF Bini.js${C.RESET} (production)
52
44
  `);
@@ -59,7 +51,7 @@ function printBanner(port) {
59
51
  }
60
52
  if (!fs.existsSync(API_DIR)) {
61
53
  console.log(`
62
- ${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
54
+ ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
63
55
  }
64
56
  console.log("");
65
57
  }
@@ -145,10 +137,15 @@ async function importHandler(filePath) {
145
137
  }
146
138
  const cached = moduleCache.get(filePath);
147
139
  if (cached && cached.mtime === mtime) return cached.handler;
148
- const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
149
- const handler = mod.default ?? null;
150
- moduleCache.set(filePath, { mtime, handler });
151
- return handler;
140
+ try {
141
+ const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
142
+ const handler = mod.default ?? null;
143
+ moduleCache.set(filePath, { mtime, handler });
144
+ return handler;
145
+ } catch (e) {
146
+ moduleCache.delete(filePath);
147
+ throw e;
148
+ }
152
149
  }
153
150
  function readBody(req) {
154
151
  return new Promise((resolve, reject) => {
@@ -170,7 +167,7 @@ function readBody(req) {
170
167
  });
171
168
  req.on("end", () => {
172
169
  clearTimeout(timeout);
173
- resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
170
+ resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
174
171
  });
175
172
  req.on("error", (err) => {
176
173
  clearTimeout(timeout);
@@ -179,16 +176,19 @@ function readBody(req) {
179
176
  });
180
177
  }
181
178
  function normalizeHeaders(raw) {
182
- return Object.fromEntries(
183
- Object.entries(raw).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? v.join(", ") : v])
184
- );
179
+ const out = {};
180
+ for (const [k, v] of Object.entries(raw)) {
181
+ if (v === void 0) continue;
182
+ out[k] = Array.isArray(v) ? k.toLowerCase() === "cookie" ? v.join("; ") : v.join(", ") : v;
183
+ }
184
+ return out;
185
185
  }
186
- var routeCache = null;
187
186
  var CORS_HEADERS = {
188
187
  "Access-Control-Allow-Origin": "*",
189
188
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
190
189
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
191
190
  };
191
+ var routeCache = null;
192
192
  async function handleApiRequest(req, res, next) {
193
193
  try {
194
194
  if (req.method === "OPTIONS") {
@@ -217,7 +217,14 @@ async function handleApiRequest(req, res, next) {
217
217
  body: body ?? null
218
218
  });
219
219
  for (const route of routeCache.routes) {
220
- const handler = await importHandler(route.filePath);
220
+ let handler;
221
+ try {
222
+ handler = await importHandler(route.filePath);
223
+ } catch (e) {
224
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
225
+ res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
226
+ return;
227
+ }
221
228
  if (!handler) continue;
222
229
  let webRes;
223
230
  try {
@@ -274,22 +281,30 @@ async function handleApiRequest(req, res, next) {
274
281
  var MIME = {
275
282
  ".html": "text/html; charset=utf-8",
276
283
  ".js": "application/javascript",
284
+ ".mjs": "application/javascript",
277
285
  ".css": "text/css",
278
286
  ".json": "application/json",
279
287
  ".png": "image/png",
280
288
  ".jpg": "image/jpeg",
281
289
  ".jpeg": "image/jpeg",
290
+ ".gif": "image/gif",
282
291
  ".svg": "image/svg+xml",
283
292
  ".ico": "image/x-icon",
284
293
  ".webp": "image/webp",
294
+ ".avif": "image/avif",
285
295
  ".woff": "font/woff",
286
296
  ".woff2": "font/woff2",
287
297
  ".ttf": "font/ttf",
288
298
  ".eot": "application/vnd.ms-fontobject",
289
299
  ".txt": "text/plain",
290
- ".webmanifest": "application/manifest+json"
300
+ ".xml": "application/xml",
301
+ ".webmanifest": "application/manifest+json",
302
+ ".map": "application/json"
291
303
  };
292
- async function sendFile(filePath, res) {
304
+ function getETag(stat) {
305
+ return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
306
+ }
307
+ async function sendFile(filePath, req, res) {
293
308
  const ext = path.extname(filePath).toLowerCase();
294
309
  const mimeType = MIME[ext] ?? "application/octet-stream";
295
310
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -301,12 +316,24 @@ async function sendFile(filePath, res) {
301
316
  res.end("Not found");
302
317
  return;
303
318
  }
319
+ const etag = getETag(stat);
320
+ const ifNoneMatch = req.headers["if-none-match"];
321
+ if (ifNoneMatch === etag) {
322
+ res.writeHead(304);
323
+ res.end();
324
+ return;
325
+ }
304
326
  res.writeHead(200, {
305
327
  "Content-Type": mimeType,
306
328
  "Content-Length": stat.size,
307
329
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
330
+ "ETag": etag,
308
331
  "X-Powered-By": "Bini.js"
309
332
  });
333
+ if (req.method === "HEAD") {
334
+ res.end();
335
+ return;
336
+ }
310
337
  try {
311
338
  await pipeline(createReadStream(filePath), res);
312
339
  } catch {
@@ -316,12 +343,12 @@ async function serveStatic(req, res, next) {
316
343
  const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
317
344
  const filePath = path.join(DIST_DIR, pathname);
318
345
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
319
- await sendFile(filePath, res);
346
+ await sendFile(filePath, req, res);
320
347
  return;
321
348
  }
322
349
  const indexPath = path.join(DIST_DIR, "index.html");
323
350
  if (fs.existsSync(indexPath)) {
324
- await sendFile(indexPath, res);
351
+ await sendFile(indexPath, req, res);
325
352
  return;
326
353
  }
327
354
  next();
@@ -332,12 +359,20 @@ function compose(middlewares) {
332
359
  async function next() {
333
360
  if (idx >= middlewares.length) return;
334
361
  const fn = middlewares[idx++];
335
- await fn(req, res, next);
362
+ try {
363
+ await fn(req, res, next);
364
+ } catch (e) {
365
+ if (!res.headersSent) {
366
+ res.writeHead(500, { "Content-Type": "application/json" });
367
+ res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
368
+ }
369
+ }
336
370
  }
337
371
  await next();
338
372
  };
339
373
  }
340
374
  async function start() {
375
+ await loadEnv(process.cwd());
341
376
  if (!fs.existsSync(DIST_DIR)) {
342
377
  console.error(`
343
378
  ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
@@ -357,6 +392,7 @@ async function start() {
357
392
  }
358
393
  ]);
359
394
  const server = http.createServer((req, res) => {
395
+ res.setHeader("Connection", "keep-alive");
360
396
  handler(req, res).catch(() => {
361
397
  if (!res.headersSent) {
362
398
  res.writeHead(500);
@@ -364,10 +400,15 @@ async function start() {
364
400
  }
365
401
  });
366
402
  });
403
+ server.keepAliveTimeout = 65e3;
404
+ server.headersTimeout = 66e3;
367
405
  server.listen(port, "0.0.0.0", () => {
368
406
  printBanner(port);
369
407
  });
370
408
  function shutdown() {
409
+ console.log(`
410
+ ${C.YELLOW}\u26A0${C.RESET} Shutting down...
411
+ `);
371
412
  server.close(() => process.exit(0));
372
413
  setTimeout(() => process.exit(1), 1e4).unref();
373
414
  }
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.0",
4
- "description": "Zero-dependency production server for bini-router apps",
3
+ "version": "1.0.1",
4
+ "description": "Zero-dependency production server for bini-router apps — static files, API routes, SPA fallback",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
7
8
  "exports": {
8
9
  ".": {
9
- "import": "./dist/index.js"
10
+ "import": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
10
14
  }
11
15
  },
12
16
  "bin": {
@@ -15,32 +19,48 @@
15
19
  "files": [
16
20
  "dist"
17
21
  ],
22
+ "scripts": {
23
+ "build": "tsup",
24
+ "dev": "tsup --watch",
25
+ "prepublishOnly": "npm run build",
26
+ "lint": "tsc --noEmit",
27
+ "clean": "rm -rf dist"
28
+ },
29
+ "dependencies": {
30
+ "bini-env": "^1.0.6"
31
+ },
18
32
  "engines": {
19
- "node": ">=22"
33
+ "node": ">=18.0.0"
20
34
  },
21
35
  "keywords": [
22
36
  "bini",
37
+ "bini-js",
23
38
  "bini-router",
39
+ "bini-env",
24
40
  "server",
25
41
  "spa",
26
42
  "vite",
27
43
  "hono",
28
44
  "production",
29
- "node"
45
+ "node",
46
+ "static-server",
47
+ "api-routes",
48
+ "etag"
30
49
  ],
31
50
  "author": "Binidu Ranasinghe",
32
51
  "license": "MIT",
33
52
  "homepage": "https://bini.js.org",
34
53
  "repository": {
35
54
  "type": "git",
36
- "url": "https://github.com/binidu/bini-server"
55
+ "url": "https://github.com/Binidu01/bini-server.git"
56
+ },
57
+ "bugs": {
58
+ "url": "https://github.com/Binidu01/bini-server/issues"
37
59
  },
38
60
  "devDependencies": {
39
61
  "@types/node": "^25",
40
- "tsup": "^8",
41
- "typescript": "^5"
42
- },
43
- "scripts": {
44
- "build": "tsup"
62
+ "bini-env" : "^1.0.6",
63
+ "tsup" : "^8",
64
+ "typescript" : "^5"
45
65
  }
46
66
  }