bini-server 1.0.0 → 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.
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,29 @@ 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";
14
+ process.env.NODE_ENV = "production";
15
+ (function suppressDotenv() {
16
+ const _log = console.log.bind(console);
17
+ const _err = console.error.bind(console);
18
+ const isDotenv = (...args) => {
19
+ const msg = args.join(" ");
20
+ return msg.includes("[dotenv@") || msg.includes("[bini-env] Loaded");
21
+ };
22
+ console.log = (...args) => {
23
+ if (!isDotenv(...args)) _log(...args);
24
+ };
25
+ console.error = (...args) => {
26
+ if (!isDotenv(...args)) _err(...args);
27
+ };
28
+ })();
12
29
  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");
30
+ var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
31
+ var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
15
32
  var API_EXTS = [".ts", ".js"];
16
33
  var BODY_TIMEOUT = 3e4;
17
34
  var HANDLER_TIMEOUT = 3e4;
@@ -36,19 +53,9 @@ function getAllNetworkIps() {
36
53
  }
37
54
  return [...new Set(ips)];
38
55
  }
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
56
  function printBanner(port) {
50
57
  const networkIps = getAllNetworkIps();
51
- const envFiles = detectEnvFiles();
58
+ const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
52
59
  console.log(`
53
60
  ${C.CYAN}\xDF Bini.js${C.RESET} (production)
54
61
  `);
@@ -61,7 +68,7 @@ function printBanner(port) {
61
68
  }
62
69
  if (!fs.existsSync(API_DIR)) {
63
70
  console.log(`
64
- ${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
71
+ ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
65
72
  }
66
73
  console.log("");
67
74
  }
@@ -147,10 +154,15 @@ async function importHandler(filePath) {
147
154
  }
148
155
  const cached = moduleCache.get(filePath);
149
156
  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;
157
+ try {
158
+ const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
159
+ const handler = mod.default ?? null;
160
+ moduleCache.set(filePath, { mtime, handler });
161
+ return handler;
162
+ } catch (e) {
163
+ moduleCache.delete(filePath);
164
+ throw e;
165
+ }
154
166
  }
155
167
  function readBody(req) {
156
168
  return new Promise((resolve, reject) => {
@@ -172,7 +184,7 @@ function readBody(req) {
172
184
  });
173
185
  req.on("end", () => {
174
186
  clearTimeout(timeout);
175
- resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
187
+ resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
176
188
  });
177
189
  req.on("error", (err) => {
178
190
  clearTimeout(timeout);
@@ -181,16 +193,19 @@ function readBody(req) {
181
193
  });
182
194
  }
183
195
  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
- );
196
+ const out = {};
197
+ for (const [k, v] of Object.entries(raw)) {
198
+ if (v === void 0) continue;
199
+ out[k] = Array.isArray(v) ? k.toLowerCase() === "cookie" ? v.join("; ") : v.join(", ") : v;
200
+ }
201
+ return out;
187
202
  }
188
- var routeCache = null;
189
203
  var CORS_HEADERS = {
190
204
  "Access-Control-Allow-Origin": "*",
191
205
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
192
206
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
193
207
  };
208
+ var routeCache = null;
194
209
  async function handleApiRequest(req, res, next) {
195
210
  try {
196
211
  if (req.method === "OPTIONS") {
@@ -219,7 +234,14 @@ async function handleApiRequest(req, res, next) {
219
234
  body: body ?? null
220
235
  });
221
236
  for (const route of routeCache.routes) {
222
- const handler = await importHandler(route.filePath);
237
+ let handler;
238
+ try {
239
+ handler = await importHandler(route.filePath);
240
+ } catch (e) {
241
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
242
+ res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
243
+ return;
244
+ }
223
245
  if (!handler) continue;
224
246
  let webRes;
225
247
  try {
@@ -276,22 +298,30 @@ async function handleApiRequest(req, res, next) {
276
298
  var MIME = {
277
299
  ".html": "text/html; charset=utf-8",
278
300
  ".js": "application/javascript",
301
+ ".mjs": "application/javascript",
279
302
  ".css": "text/css",
280
303
  ".json": "application/json",
281
304
  ".png": "image/png",
282
305
  ".jpg": "image/jpeg",
283
306
  ".jpeg": "image/jpeg",
307
+ ".gif": "image/gif",
284
308
  ".svg": "image/svg+xml",
285
309
  ".ico": "image/x-icon",
286
310
  ".webp": "image/webp",
311
+ ".avif": "image/avif",
287
312
  ".woff": "font/woff",
288
313
  ".woff2": "font/woff2",
289
314
  ".ttf": "font/ttf",
290
315
  ".eot": "application/vnd.ms-fontobject",
291
316
  ".txt": "text/plain",
292
- ".webmanifest": "application/manifest+json"
317
+ ".xml": "application/xml",
318
+ ".webmanifest": "application/manifest+json",
319
+ ".map": "application/json"
293
320
  };
294
- async function sendFile(filePath, res) {
321
+ function getETag(stat) {
322
+ return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
323
+ }
324
+ async function sendFile(filePath, req, res) {
295
325
  const ext = path.extname(filePath).toLowerCase();
296
326
  const mimeType = MIME[ext] ?? "application/octet-stream";
297
327
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -303,12 +333,24 @@ async function sendFile(filePath, res) {
303
333
  res.end("Not found");
304
334
  return;
305
335
  }
336
+ const etag = getETag(stat);
337
+ const ifNoneMatch = req.headers["if-none-match"];
338
+ if (ifNoneMatch === etag) {
339
+ res.writeHead(304);
340
+ res.end();
341
+ return;
342
+ }
306
343
  res.writeHead(200, {
307
344
  "Content-Type": mimeType,
308
345
  "Content-Length": stat.size,
309
346
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
347
+ "ETag": etag,
310
348
  "X-Powered-By": "Bini.js"
311
349
  });
350
+ if (req.method === "HEAD") {
351
+ res.end();
352
+ return;
353
+ }
312
354
  try {
313
355
  await pipeline(createReadStream(filePath), res);
314
356
  } catch {
@@ -318,12 +360,12 @@ async function serveStatic(req, res, next) {
318
360
  const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
319
361
  const filePath = path.join(DIST_DIR, pathname);
320
362
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
321
- await sendFile(filePath, res);
363
+ await sendFile(filePath, req, res);
322
364
  return;
323
365
  }
324
366
  const indexPath = path.join(DIST_DIR, "index.html");
325
367
  if (fs.existsSync(indexPath)) {
326
- await sendFile(indexPath, res);
368
+ await sendFile(indexPath, req, res);
327
369
  return;
328
370
  }
329
371
  next();
@@ -334,12 +376,20 @@ function compose(middlewares) {
334
376
  async function next() {
335
377
  if (idx >= middlewares.length) return;
336
378
  const fn = middlewares[idx++];
337
- await fn(req, res, next);
379
+ try {
380
+ await fn(req, res, next);
381
+ } catch (e) {
382
+ if (!res.headersSent) {
383
+ res.writeHead(500, { "Content-Type": "application/json" });
384
+ res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
385
+ }
386
+ }
338
387
  }
339
388
  await next();
340
389
  };
341
390
  }
342
391
  async function start() {
392
+ await loadEnv(process.cwd());
343
393
  if (!fs.existsSync(DIST_DIR)) {
344
394
  console.error(`
345
395
  ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
@@ -359,6 +409,7 @@ async function start() {
359
409
  }
360
410
  ]);
361
411
  const server = http.createServer((req, res) => {
412
+ res.setHeader("Connection", "keep-alive");
362
413
  handler(req, res).catch(() => {
363
414
  if (!res.headersSent) {
364
415
  res.writeHead(500);
@@ -366,6 +417,8 @@ async function start() {
366
417
  }
367
418
  });
368
419
  });
420
+ server.keepAliveTimeout = 65e3;
421
+ server.headersTimeout = 66e3;
369
422
  server.listen(port, "0.0.0.0", () => {
370
423
  printBanner(port);
371
424
  });
@@ -378,4 +431,7 @@ async function start() {
378
431
  }
379
432
 
380
433
  // src/cli.ts
381
- start();
434
+ start().catch((err) => {
435
+ console.error(err);
436
+ process.exit(1);
437
+ });
package/dist/index.js CHANGED
@@ -4,12 +4,29 @@ 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";
12
+ process.env.NODE_ENV = "production";
13
+ (function suppressDotenv() {
14
+ const _log = console.log.bind(console);
15
+ const _err = console.error.bind(console);
16
+ const isDotenv = (...args) => {
17
+ const msg = args.join(" ");
18
+ return msg.includes("[dotenv@") || msg.includes("[bini-env] Loaded");
19
+ };
20
+ console.log = (...args) => {
21
+ if (!isDotenv(...args)) _log(...args);
22
+ };
23
+ console.error = (...args) => {
24
+ if (!isDotenv(...args)) _err(...args);
25
+ };
26
+ })();
10
27
  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");
28
+ var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
29
+ var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
13
30
  var API_EXTS = [".ts", ".js"];
14
31
  var BODY_TIMEOUT = 3e4;
15
32
  var HANDLER_TIMEOUT = 3e4;
@@ -34,19 +51,9 @@ function getAllNetworkIps() {
34
51
  }
35
52
  return [...new Set(ips)];
36
53
  }
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
54
  function printBanner(port) {
48
55
  const networkIps = getAllNetworkIps();
49
- const envFiles = detectEnvFiles();
56
+ const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
50
57
  console.log(`
51
58
  ${C.CYAN}\xDF Bini.js${C.RESET} (production)
52
59
  `);
@@ -59,7 +66,7 @@ function printBanner(port) {
59
66
  }
60
67
  if (!fs.existsSync(API_DIR)) {
61
68
  console.log(`
62
- ${C.DIM}No src/app/api/ found \u2014 API routes disabled.${C.RESET}`);
69
+ ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
63
70
  }
64
71
  console.log("");
65
72
  }
@@ -145,10 +152,15 @@ async function importHandler(filePath) {
145
152
  }
146
153
  const cached = moduleCache.get(filePath);
147
154
  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;
155
+ try {
156
+ const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
157
+ const handler = mod.default ?? null;
158
+ moduleCache.set(filePath, { mtime, handler });
159
+ return handler;
160
+ } catch (e) {
161
+ moduleCache.delete(filePath);
162
+ throw e;
163
+ }
152
164
  }
153
165
  function readBody(req) {
154
166
  return new Promise((resolve, reject) => {
@@ -170,7 +182,7 @@ function readBody(req) {
170
182
  });
171
183
  req.on("end", () => {
172
184
  clearTimeout(timeout);
173
- resolve(chunks.length > 0 ? Buffer.concat(chunks).buffer : void 0);
185
+ resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
174
186
  });
175
187
  req.on("error", (err) => {
176
188
  clearTimeout(timeout);
@@ -179,16 +191,19 @@ function readBody(req) {
179
191
  });
180
192
  }
181
193
  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
- );
194
+ const out = {};
195
+ for (const [k, v] of Object.entries(raw)) {
196
+ if (v === void 0) continue;
197
+ out[k] = Array.isArray(v) ? k.toLowerCase() === "cookie" ? v.join("; ") : v.join(", ") : v;
198
+ }
199
+ return out;
185
200
  }
186
- var routeCache = null;
187
201
  var CORS_HEADERS = {
188
202
  "Access-Control-Allow-Origin": "*",
189
203
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
190
204
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
191
205
  };
206
+ var routeCache = null;
192
207
  async function handleApiRequest(req, res, next) {
193
208
  try {
194
209
  if (req.method === "OPTIONS") {
@@ -217,7 +232,14 @@ async function handleApiRequest(req, res, next) {
217
232
  body: body ?? null
218
233
  });
219
234
  for (const route of routeCache.routes) {
220
- const handler = await importHandler(route.filePath);
235
+ let handler;
236
+ try {
237
+ handler = await importHandler(route.filePath);
238
+ } catch (e) {
239
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
240
+ res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
241
+ return;
242
+ }
221
243
  if (!handler) continue;
222
244
  let webRes;
223
245
  try {
@@ -274,22 +296,30 @@ async function handleApiRequest(req, res, next) {
274
296
  var MIME = {
275
297
  ".html": "text/html; charset=utf-8",
276
298
  ".js": "application/javascript",
299
+ ".mjs": "application/javascript",
277
300
  ".css": "text/css",
278
301
  ".json": "application/json",
279
302
  ".png": "image/png",
280
303
  ".jpg": "image/jpeg",
281
304
  ".jpeg": "image/jpeg",
305
+ ".gif": "image/gif",
282
306
  ".svg": "image/svg+xml",
283
307
  ".ico": "image/x-icon",
284
308
  ".webp": "image/webp",
309
+ ".avif": "image/avif",
285
310
  ".woff": "font/woff",
286
311
  ".woff2": "font/woff2",
287
312
  ".ttf": "font/ttf",
288
313
  ".eot": "application/vnd.ms-fontobject",
289
314
  ".txt": "text/plain",
290
- ".webmanifest": "application/manifest+json"
315
+ ".xml": "application/xml",
316
+ ".webmanifest": "application/manifest+json",
317
+ ".map": "application/json"
291
318
  };
292
- async function sendFile(filePath, res) {
319
+ function getETag(stat) {
320
+ return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
321
+ }
322
+ async function sendFile(filePath, req, res) {
293
323
  const ext = path.extname(filePath).toLowerCase();
294
324
  const mimeType = MIME[ext] ?? "application/octet-stream";
295
325
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -301,12 +331,24 @@ async function sendFile(filePath, res) {
301
331
  res.end("Not found");
302
332
  return;
303
333
  }
334
+ const etag = getETag(stat);
335
+ const ifNoneMatch = req.headers["if-none-match"];
336
+ if (ifNoneMatch === etag) {
337
+ res.writeHead(304);
338
+ res.end();
339
+ return;
340
+ }
304
341
  res.writeHead(200, {
305
342
  "Content-Type": mimeType,
306
343
  "Content-Length": stat.size,
307
344
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
345
+ "ETag": etag,
308
346
  "X-Powered-By": "Bini.js"
309
347
  });
348
+ if (req.method === "HEAD") {
349
+ res.end();
350
+ return;
351
+ }
310
352
  try {
311
353
  await pipeline(createReadStream(filePath), res);
312
354
  } catch {
@@ -316,12 +358,12 @@ async function serveStatic(req, res, next) {
316
358
  const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
317
359
  const filePath = path.join(DIST_DIR, pathname);
318
360
  if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
319
- await sendFile(filePath, res);
361
+ await sendFile(filePath, req, res);
320
362
  return;
321
363
  }
322
364
  const indexPath = path.join(DIST_DIR, "index.html");
323
365
  if (fs.existsSync(indexPath)) {
324
- await sendFile(indexPath, res);
366
+ await sendFile(indexPath, req, res);
325
367
  return;
326
368
  }
327
369
  next();
@@ -332,12 +374,20 @@ function compose(middlewares) {
332
374
  async function next() {
333
375
  if (idx >= middlewares.length) return;
334
376
  const fn = middlewares[idx++];
335
- await fn(req, res, next);
377
+ try {
378
+ await fn(req, res, next);
379
+ } catch (e) {
380
+ if (!res.headersSent) {
381
+ res.writeHead(500, { "Content-Type": "application/json" });
382
+ res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
383
+ }
384
+ }
336
385
  }
337
386
  await next();
338
387
  };
339
388
  }
340
389
  async function start() {
390
+ await loadEnv(process.cwd());
341
391
  if (!fs.existsSync(DIST_DIR)) {
342
392
  console.error(`
343
393
  ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
@@ -357,6 +407,7 @@ async function start() {
357
407
  }
358
408
  ]);
359
409
  const server = http.createServer((req, res) => {
410
+ res.setHeader("Connection", "keep-alive");
360
411
  handler(req, res).catch(() => {
361
412
  if (!res.headersSent) {
362
413
  res.writeHead(500);
@@ -364,6 +415,8 @@ async function start() {
364
415
  }
365
416
  });
366
417
  });
418
+ server.keepAliveTimeout = 65e3;
419
+ server.headersTimeout = 66e3;
367
420
  server.listen(port, "0.0.0.0", () => {
368
421
  printBanner(port);
369
422
  });
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.2",
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.8",
63
+ "tsup" : "^8",
64
+ "typescript" : "^5"
45
65
  }
46
66
  }