bini-server 1.0.3 → 1.0.6

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.
Files changed (4) hide show
  1. package/README.md +39 -26
  2. package/dist/cli.js +170 -145
  3. package/dist/index.js +170 -145
  4. package/package.json +5 -8
package/README.md CHANGED
@@ -2,12 +2,11 @@
2
2
 
3
3
  <div align="center">
4
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)
5
+ [![npm version](https://img.shields.io/npm/v/bini-server?style=flat-square&logo=npm&logoColor=white&label=npm&color=CB3837&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
6
+ [![license](https://img.shields.io/badge/license-MIT-green?style=flat-square&logo=opensourceinitiative&logoColor=white&labelColor=0a0a0a)](./LICENSE)
7
+ [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
9
8
 
10
- **Zero-dependency production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
9
+ **Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
11
10
  Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` handlers — just like `vite preview`, but production-grade.
12
11
 
13
12
  </div>
@@ -16,24 +15,24 @@ Serves your `dist/` statically and handles `/api/*` from your `src/app/api/` han
16
15
 
17
16
  ## Features
18
17
 
19
- - ⚡ **Zero dependencies** — pure Node.js built-ins only
20
18
  - 🗂️ **Static file serving** — streams `dist/` with correct MIME types, ETag, and cache headers
21
19
  - 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
22
20
  - 🔀 **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)
21
+ - 🌿 **Auto env loading** — `.env` files detected and listed automatically at startup
24
22
  - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
25
23
  - 🛡️ **CORS** — enabled by default on all API responses
26
- - ⏱️ **Timeouts** — 30s body read timeout + 30s handler timeout
27
- - 🔒 **Body limit** — 10MB request body limit
24
+ - ⏱️ **Timeouts** — configurable body read + handler timeouts (default 30s each)
25
+ - 🔒 **Body limit** — configurable request body limit (default 10MB)
28
26
  - 🔌 **Port auto-increment** — starts at `3000`, increments if busy
29
27
  - 🪄 **Graceful shutdown** — handles `SIGTERM` + `SIGINT` with 10s force-exit fallback
28
+ - ⌨️ **Interactive keyboard shortcuts** — `h` for help, `o` to open in browser, `q` to quit
30
29
  - 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
31
30
 
32
31
  ---
33
32
 
34
33
  ## Requirements
35
34
 
36
- - Node.js **≥ 18**
35
+ - Node.js **≥ 20**
37
36
  - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
38
37
 
39
38
  ---
@@ -69,18 +68,30 @@ npm start # serve it in production
69
68
  Terminal output:
70
69
 
71
70
  ```
72
- ß Bini.js (production)
73
-
71
+ ß Bini.js (production)
74
72
  ➜ Environments: .env
75
73
  ➜ Local: http://localhost:3000/
76
74
  ➜ Network: http://192.168.1.5:3000/
75
+ ➜ press h + enter to show help
77
76
  ```
78
77
 
79
78
  ---
80
79
 
80
+ ## Keyboard Shortcuts
81
+
82
+ Once the server is running, type a key and press `enter`:
83
+
84
+ | Key | Action |
85
+ |-----|--------|
86
+ | `h` | Show available shortcuts |
87
+ | `o` | Open in browser |
88
+ | `q` | Quit |
89
+
90
+ ---
91
+
81
92
  ## Environment Variables
82
93
 
83
- `.env` is loaded automatically at startup — all vars are available in `process.env` in your API handlers with no imports needed.
94
+ `.env` files are detected automatically at startup and listed in the banner. All vars are available in `process.env` in your API handlers with no imports needed.
84
95
 
85
96
  ```env
86
97
  PORT=3000
@@ -88,6 +99,19 @@ SMTP_USER=user@smtp.example.com
88
99
  SMTP_PASS=your_password
89
100
  ```
90
101
 
102
+ ### Server Configuration
103
+
104
+ These variables tune server behaviour and can be set in `.env` or inline:
105
+
106
+ | Variable | Default | Description |
107
+ |---|---|---|
108
+ | `PORT` | `3000` | HTTP port to listen on |
109
+ | `BINI_API_DIR` | `src/app/api` | Path to API handlers directory |
110
+ | `BINI_DIST_DIR` | `dist` | Path to static files directory |
111
+ | `BINI_BODY_TIMEOUT_SECS` | `30` | Max seconds to read request body |
112
+ | `BINI_HANDLER_TIMEOUT_SECS` | `30` | Max seconds for an API handler to respond |
113
+ | `BINI_BODY_SIZE_LIMIT` | `10485760` | Max request body size in bytes (default 10MB) |
114
+
91
115
  ---
92
116
 
93
117
  ## Important: ship your `src/` folder
@@ -113,18 +137,7 @@ PORT=8080 bini-server
113
137
  If the port is busy, bini-server automatically increments and warns:
114
138
 
115
139
  ```
116
- ⚠ Port 3000 is in use, using port 3001 instead.
117
- ```
118
-
119
- ---
120
-
121
- ## Configurable Directories
122
-
123
- By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars:
124
-
125
- ```env
126
- BINI_API_DIR=src/api # default: src/app/api
127
- BINI_DIST_DIR=build # default: dist
140
+ ⚠ Port 3000 in use — using 3001 instead.
128
141
  ```
129
142
 
130
143
  ---
@@ -179,8 +192,8 @@ Set start command to `npm start`. Render injects `PORT` automatically.
179
192
  | Body size limit | ❌ | ✅ 10MB |
180
193
  | Handler timeout | ❌ | ✅ 30s |
181
194
  | Graceful shutdown | ❌ | ✅ |
195
+ | Handler module cache | ❌ | ✅ |
182
196
  | Configurable dirs | ❌ | ✅ |
183
- | Zero dependencies | ✅ | ✅ |
184
197
 
185
198
  ---
186
199
 
package/dist/cli.js CHANGED
@@ -7,69 +7,70 @@ import path from "path";
7
7
  import os from "os";
8
8
  import net from "net";
9
9
  import crypto from "crypto";
10
+ import readline from "readline";
11
+ import { exec } from "child_process";
10
12
  import { pathToFileURL } from "url";
11
13
  import { pipeline } from "stream/promises";
12
14
  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
- })();
15
+ function detectEnvFiles(root) {
16
+ const nodeEnv = process.env.NODE_ENV ?? "production";
17
+ return [
18
+ ".env.local",
19
+ `.env.${nodeEnv}.local`,
20
+ `.env.${nodeEnv}`,
21
+ ".env"
22
+ ].filter((f) => fs.existsSync(path.join(root, f)));
23
+ }
29
24
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
25
+ var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
26
+ var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
27
+ var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
30
28
  var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
31
29
  var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
32
- var API_EXTS = [".ts", ".js"];
33
- var BODY_TIMEOUT = 3e4;
34
- var HANDLER_TIMEOUT = 3e4;
35
- var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
30
+ var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
36
31
  var C = {
37
32
  CYAN: "\x1B[36m",
38
33
  RESET: "\x1B[0m",
39
34
  GREEN: "\x1B[32m",
40
35
  RED: "\x1B[31m",
41
36
  YELLOW: "\x1B[33m",
37
+ BOLD: "\x1B[1m",
42
38
  DIM: "\x1B[2m"
43
39
  };
44
- function getAllNetworkIps() {
40
+ function getNetworkIp() {
45
41
  const ifaces = os.networkInterfaces();
46
- const ips = [];
42
+ const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
47
43
  for (const name in ifaces) {
48
- if (/docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i.test(name)) continue;
44
+ if (SKIP.test(name)) continue;
49
45
  for (const iface of ifaces[name] ?? []) {
50
46
  if (iface.internal || iface.family !== "IPv4") continue;
51
- ips.push(iface.address);
47
+ const [a, b] = iface.address.split(".").map(Number);
48
+ if (a === 169 && b === 254) continue;
49
+ const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
50
+ if (isPrivate) return iface.address;
51
+ }
52
+ }
53
+ for (const name in ifaces) {
54
+ if (SKIP.test(name)) continue;
55
+ for (const iface of ifaces[name] ?? []) {
56
+ if (!iface.internal && iface.family === "IPv4") return iface.address;
52
57
  }
53
58
  }
54
- return [...new Set(ips)];
59
+ return null;
55
60
  }
56
61
  function printBanner(port) {
57
- const networkIps = getAllNetworkIps();
58
- const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
62
+ const envFiles = detectEnvFiles(process.cwd());
63
+ const networkIp = getNetworkIp();
59
64
  console.log(`
60
- ${C.CYAN}\xDF Bini.js${C.RESET} (production)
61
- `);
65
+ ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
62
66
  if (envFiles.length > 0) {
63
67
  console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
64
68
  }
65
69
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
66
- for (const ip of networkIps) {
67
- console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${ip}:${port}/${C.RESET}`);
68
- }
69
- if (!fs.existsSync(API_DIR)) {
70
- console.log(`
71
- ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
70
+ if (networkIp) {
71
+ console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
72
72
  }
73
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
73
74
  console.log("");
74
75
  }
75
76
  async function isPortFree(port) {
@@ -85,16 +86,39 @@ async function findFreePort(start2) {
85
86
  if (await isPortFree(port)) {
86
87
  if (port !== start2) {
87
88
  console.log(`
88
- ${C.YELLOW}\u26A0${C.RESET} Port ${start2} is in use, using port ${C.CYAN}${port}${C.RESET} instead.`);
89
+ ${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
89
90
  }
90
91
  return port;
91
92
  }
92
93
  }
93
- throw new Error(`No free port found between ${start2} and ${start2 + 100}`);
94
+ throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
94
95
  }
95
- function scanApiRoutes(dir, baseRoute = "") {
96
+ function startKeyboardLoop(port) {
97
+ const rl = readline.createInterface({ input: process.stdin });
98
+ rl.on("line", (line) => {
99
+ switch (line.trim()) {
100
+ case "h":
101
+ console.log("");
102
+ console.log(" Shortcuts");
103
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
104
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
105
+ console.log("");
106
+ break;
107
+ case "o": {
108
+ const url = `http://localhost:${port}/`;
109
+ const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
110
+ exec(cmd);
111
+ break;
112
+ }
113
+ case "q":
114
+ process.exit(0);
115
+ }
116
+ });
117
+ rl.on("close", () => process.exit(0));
118
+ }
119
+ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
96
120
  const routes = [];
97
- if (!fs.existsSync(dir)) return routes;
121
+ if (depth > 100 || !fs.existsSync(dir)) return routes;
98
122
  let entries;
99
123
  try {
100
124
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -108,26 +132,20 @@ function scanApiRoutes(dir, baseRoute = "") {
108
132
  const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
109
133
  const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
110
134
  const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
111
- routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`));
135
+ routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
112
136
  continue;
113
137
  }
114
138
  const ext = path.extname(entry.name);
115
139
  const base = path.basename(entry.name, ext);
116
- if (!API_EXTS.includes(ext)) continue;
140
+ if (!API_EXTS.has(ext)) continue;
117
141
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
118
142
  const isDynamic = base.startsWith("[") && base.endsWith("]");
119
143
  let routePath;
120
- if (isCatchAll) {
121
- routePath = `${baseRoute}/*`;
122
- } else if (base === "index") {
123
- routePath = baseRoute || "/";
124
- } else if (isDynamic) {
125
- routePath = `${baseRoute}/:${base.slice(1, -1)}`;
126
- } else {
127
- routePath = `${baseRoute}/${base}`;
128
- }
129
- const normalizedPath = `/api${routePath}`;
130
- routes.push({ routePath: normalizedPath, filePath: fullPath });
144
+ if (isCatchAll) routePath = `${baseRoute}/*`;
145
+ else if (base === "index") routePath = baseRoute || "/";
146
+ else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
147
+ else routePath = `${baseRoute}/${base}`;
148
+ routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
131
149
  }
132
150
  return routes;
133
151
  }
@@ -139,8 +157,7 @@ function matchRoute(pattern, pathname) {
139
157
  const prefix = patParts.slice(0, -1);
140
158
  if (urlParts.length < prefix.length) return null;
141
159
  for (let i = 0; i < prefix.length; i++) {
142
- if (prefix[i].startsWith(":")) continue;
143
- if (prefix[i] !== urlParts[i]) return null;
160
+ if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
144
161
  }
145
162
  return { "*": urlParts.slice(prefix.length).join("/") };
146
163
  }
@@ -148,7 +165,9 @@ function matchRoute(pattern, pathname) {
148
165
  const params = {};
149
166
  for (let i = 0; i < patParts.length; i++) {
150
167
  if (patParts[i].startsWith(":")) {
151
- params[patParts[i].slice(1)] = decodeURIComponent(urlParts[i]);
168
+ const value = decodeURIComponent(urlParts[i]);
169
+ if (value.includes("..") || value.includes("//")) return null;
170
+ params[patParts[i].slice(1)] = value;
152
171
  } else if (patParts[i] !== urlParts[i]) {
153
172
  return null;
154
173
  }
@@ -164,13 +183,14 @@ async function importHandler(filePath) {
164
183
  return null;
165
184
  }
166
185
  const cached = moduleCache.get(filePath);
167
- if (cached && cached.mtime === mtime) return cached.handler;
186
+ if (cached?.mtime === mtime) return cached.handler;
168
187
  try {
169
188
  const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
170
189
  const handler = mod.default ?? null;
171
190
  moduleCache.set(filePath, { mtime, handler });
172
191
  return handler;
173
- } catch {
192
+ } catch (e) {
193
+ console.error(`[bini-api] import error: ${filePath}`, e?.message);
174
194
  moduleCache.delete(filePath);
175
195
  return null;
176
196
  }
@@ -179,14 +199,14 @@ function readBody(req) {
179
199
  return new Promise((resolve, reject) => {
180
200
  const chunks = [];
181
201
  let size = 0;
182
- const timeout = setTimeout(() => {
202
+ const timer = setTimeout(() => {
183
203
  req.destroy();
184
204
  reject(new Error("Request body timeout"));
185
205
  }, BODY_TIMEOUT);
186
206
  req.on("data", (chunk) => {
187
207
  size += chunk.byteLength;
188
208
  if (size > BODY_SIZE_LIMIT) {
189
- clearTimeout(timeout);
209
+ clearTimeout(timer);
190
210
  req.destroy();
191
211
  reject(new Error("Request body too large"));
192
212
  return;
@@ -194,11 +214,11 @@ function readBody(req) {
194
214
  chunks.push(chunk);
195
215
  });
196
216
  req.on("end", () => {
197
- clearTimeout(timeout);
217
+ clearTimeout(timer);
198
218
  resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
199
219
  });
200
220
  req.on("error", (err) => {
201
- clearTimeout(timeout);
221
+ clearTimeout(timer);
202
222
  reject(err);
203
223
  });
204
224
  });
@@ -214,97 +234,106 @@ function normalizeHeaders(raw) {
214
234
  var CORS_HEADERS = {
215
235
  "Access-Control-Allow-Origin": "*",
216
236
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
217
- "Access-Control-Allow-Headers": "Content-Type,Authorization"
237
+ "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
238
+ "Vary": "Origin"
218
239
  };
219
- function isHonoApp(handler) {
220
- return handler && typeof handler.fetch === "function";
240
+ function invokeHono(honoApp, request) {
241
+ return honoApp.fetch(request, process.env);
221
242
  }
222
243
  var routeCache = null;
223
244
  async function handleApiRequest(req, res, next) {
245
+ if (req.method === "OPTIONS") {
246
+ res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
247
+ res.end();
248
+ return;
249
+ }
250
+ routeCache ??= scanApiRoutes(API_DIR);
251
+ const host = req.headers.host ?? "localhost";
252
+ const rawUrl = `http://${host}${req.url ?? "/"}`;
253
+ const method = (req.method ?? "GET").toUpperCase();
254
+ let parsedUrl;
224
255
  try {
225
- if (req.method === "OPTIONS") {
226
- res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
227
- res.end();
228
- return;
229
- }
230
- if (!routeCache) {
231
- routeCache = scanApiRoutes(API_DIR);
232
- }
233
- const host = req.headers.host ?? "localhost";
234
- const url = `http://${host}${req.url ?? ""}`;
235
- const pathname = new URL(url).pathname;
236
- const method = (req.method ?? "GET").toUpperCase();
237
- let matchedRoute;
238
- for (const route of routeCache) {
239
- if (matchRoute(route.routePath, pathname) !== null) {
240
- matchedRoute = route;
241
- break;
242
- }
243
- }
244
- if (!matchedRoute) {
245
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
246
- res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
247
- return;
256
+ parsedUrl = new URL(rawUrl);
257
+ } catch {
258
+ res.writeHead(400, { "Content-Type": "application/json" });
259
+ res.end(JSON.stringify({ error: "Bad request URL" }));
260
+ return;
261
+ }
262
+ const { pathname, search } = parsedUrl;
263
+ let matchedRoute = null;
264
+ let params = null;
265
+ for (const route of routeCache) {
266
+ params = matchRoute(route.routePath, pathname);
267
+ if (params !== null) {
268
+ matchedRoute = route;
269
+ break;
248
270
  }
249
- let body;
271
+ }
272
+ if (!matchedRoute) {
273
+ res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
274
+ res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
275
+ return;
276
+ }
277
+ let body;
278
+ if (!["GET", "HEAD"].includes(method)) {
250
279
  try {
251
- body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
280
+ body = await readBody(req);
252
281
  } catch (e) {
253
- res.writeHead(413, { "Content-Type": "application/json" });
282
+ const status = e.message.includes("too large") ? 413 : 408;
283
+ res.writeHead(status, { "Content-Type": "application/json" });
254
284
  res.end(JSON.stringify({ error: e.message }));
255
285
  return;
256
286
  }
257
- const handler = await importHandler(matchedRoute.filePath);
258
- if (!handler) {
259
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
260
- res.end(JSON.stringify({ error: `Failed to load handler for ${matchedRoute.routePath}` }));
261
- return;
262
- }
263
- let webRes;
264
- try {
265
- if (isHonoApp(handler)) {
266
- const newUrl = url.replace(/^https?:\/\/[^\/]+\/api/, `http://${host}`);
267
- const modifiedReq = new Request(newUrl, {
268
- method,
269
- headers: normalizeHeaders(req.headers),
270
- body: body ?? null
271
- });
272
- webRes = await handler.fetch(modifiedReq);
273
- } else if (typeof handler === "function") {
274
- const params = matchRoute(matchedRoute.routePath, pathname);
275
- const reqWithParams = new Request(url, {
276
- method,
277
- headers: {
278
- ...normalizeHeaders(req.headers),
279
- "x-bini-params": JSON.stringify(params ?? {})
280
- },
281
- body: body ?? null
282
- });
283
- const result = await Promise.race([
284
- handler(reqWithParams),
285
- new Promise((_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT))
286
- ]);
287
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
288
- status: 200,
289
- headers: { "Content-Type": "application/json" }
290
- });
291
- } else {
292
- throw new Error("Invalid handler type");
293
- }
294
- } catch (e) {
287
+ }
288
+ const handler = await importHandler(matchedRoute.filePath);
289
+ if (!handler) {
290
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
291
+ res.end(JSON.stringify({ error: "Failed to load handler" }));
292
+ return;
293
+ }
294
+ const normalizedHeaders = normalizeHeaders(req.headers);
295
+ let webRes;
296
+ try {
297
+ if (typeof handler.fetch === "function") {
298
+ const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
299
+ webRes = await invokeHono(handler, new Request(honoUrl, {
300
+ method,
301
+ headers: normalizedHeaders,
302
+ body: body ? new Uint8Array(body) : null
303
+ }));
304
+ } else if (typeof handler === "function") {
305
+ const reqWithParams = new Request(rawUrl, {
306
+ method,
307
+ headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
308
+ body: body ? new Uint8Array(body) : null
309
+ });
310
+ const result = await Promise.race([
311
+ handler(reqWithParams),
312
+ new Promise(
313
+ (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
314
+ )
315
+ ]);
316
+ webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
317
+ status: 200,
318
+ headers: { "Content-Type": "application/json" }
319
+ });
320
+ } else {
295
321
  res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
296
- res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
322
+ res.end(JSON.stringify({ error: "Handler has no valid default export" }));
297
323
  return;
298
324
  }
299
- const finalHeaders = { ...CORS_HEADERS };
300
- webRes.headers.forEach((v, k) => {
301
- finalHeaders[k] = v;
302
- });
303
- res.writeHead(webRes.status, finalHeaders);
304
- res.end(Buffer.from(await webRes.arrayBuffer()));
305
325
  } catch (e) {
306
- next();
326
+ console.error("[bini-api] handler error:", e?.message ?? e);
327
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
328
+ res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
329
+ return;
307
330
  }
331
+ const finalHeaders = { ...CORS_HEADERS };
332
+ webRes.headers.forEach((v, k) => {
333
+ finalHeaders[k] = v;
334
+ });
335
+ res.writeHead(webRes.status, finalHeaders);
336
+ res.end(Buffer.from(await webRes.arrayBuffer()));
308
337
  }
309
338
  var MIME = {
310
339
  ".html": "text/html; charset=utf-8",
@@ -345,8 +374,7 @@ async function sendFile(filePath, req, res) {
345
374
  return;
346
375
  }
347
376
  const etag = getETag(stat);
348
- const ifNoneMatch = req.headers["if-none-match"];
349
- if (ifNoneMatch === etag) {
377
+ if (req.headers["if-none-match"] === etag) {
350
378
  res.writeHead(304);
351
379
  res.end();
352
380
  return;
@@ -369,12 +397,9 @@ async function sendFile(filePath, req, res) {
369
397
  }
370
398
  async function serveStatic(req, res, next) {
371
399
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
372
- if (pathname.startsWith("/api")) {
373
- return next();
374
- }
400
+ if (pathname.startsWith("/api")) return next();
375
401
  const filePath = path.join(DIST_DIR, pathname);
376
402
  try {
377
- await fs.promises.access(filePath);
378
403
  const stat = await fs.promises.stat(filePath);
379
404
  if (stat.isFile()) {
380
405
  await sendFile(filePath, req, res);
@@ -386,7 +411,6 @@ async function serveStatic(req, res, next) {
386
411
  try {
387
412
  await fs.promises.access(indexPath);
388
413
  await sendFile(indexPath, req, res);
389
- return;
390
414
  } catch {
391
415
  next();
392
416
  }
@@ -410,10 +434,10 @@ function compose(middlewares) {
410
434
  };
411
435
  }
412
436
  async function start() {
413
- await loadEnv(process.cwd());
414
437
  if (!fs.existsSync(DIST_DIR)) {
415
438
  console.error(`
416
- ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
439
+ ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
440
+ Run ${C.CYAN}npm run build${C.RESET} first.
417
441
  `);
418
442
  process.exit(1);
419
443
  }
@@ -440,6 +464,7 @@ async function start() {
440
464
  });
441
465
  server.keepAliveTimeout = 65e3;
442
466
  server.headersTimeout = 66e3;
467
+ startKeyboardLoop(port);
443
468
  server.listen(port, "0.0.0.0", () => {
444
469
  printBanner(port);
445
470
  });
package/dist/index.js CHANGED
@@ -5,69 +5,70 @@ import path from "path";
5
5
  import os from "os";
6
6
  import net from "net";
7
7
  import crypto from "crypto";
8
+ import readline from "readline";
9
+ import { exec } from "child_process";
8
10
  import { pathToFileURL } from "url";
9
11
  import { pipeline } from "stream/promises";
10
12
  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
- })();
13
+ function detectEnvFiles(root) {
14
+ const nodeEnv = process.env.NODE_ENV ?? "production";
15
+ return [
16
+ ".env.local",
17
+ `.env.${nodeEnv}.local`,
18
+ `.env.${nodeEnv}`,
19
+ ".env"
20
+ ].filter((f) => fs.existsSync(path.join(root, f)));
21
+ }
27
22
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
23
+ var BODY_TIMEOUT = parseInt(process.env.BINI_BODY_TIMEOUT_SECS ?? "30", 10) * 1e3;
24
+ var HANDLER_TIMEOUT = parseInt(process.env.BINI_HANDLER_TIMEOUT_SECS ?? "30", 10) * 1e3;
25
+ var BODY_SIZE_LIMIT = parseInt(process.env.BINI_BODY_SIZE_LIMIT ?? String(10 * 1024 * 1024), 10);
28
26
  var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
29
27
  var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
30
- var API_EXTS = [".ts", ".js"];
31
- var BODY_TIMEOUT = 3e4;
32
- var HANDLER_TIMEOUT = 3e4;
33
- var BODY_SIZE_LIMIT = 10 * 1024 * 1024;
28
+ var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js", ".mjs", ".cjs"]);
34
29
  var C = {
35
30
  CYAN: "\x1B[36m",
36
31
  RESET: "\x1B[0m",
37
32
  GREEN: "\x1B[32m",
38
33
  RED: "\x1B[31m",
39
34
  YELLOW: "\x1B[33m",
35
+ BOLD: "\x1B[1m",
40
36
  DIM: "\x1B[2m"
41
37
  };
42
- function getAllNetworkIps() {
38
+ function getNetworkIp() {
43
39
  const ifaces = os.networkInterfaces();
44
- const ips = [];
40
+ const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
45
41
  for (const name in ifaces) {
46
- if (/docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i.test(name)) continue;
42
+ if (SKIP.test(name)) continue;
47
43
  for (const iface of ifaces[name] ?? []) {
48
44
  if (iface.internal || iface.family !== "IPv4") continue;
49
- ips.push(iface.address);
45
+ const [a, b] = iface.address.split(".").map(Number);
46
+ if (a === 169 && b === 254) continue;
47
+ const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
48
+ if (isPrivate) return iface.address;
49
+ }
50
+ }
51
+ for (const name in ifaces) {
52
+ if (SKIP.test(name)) continue;
53
+ for (const iface of ifaces[name] ?? []) {
54
+ if (!iface.internal && iface.family === "IPv4") return iface.address;
50
55
  }
51
56
  }
52
- return [...new Set(ips)];
57
+ return null;
53
58
  }
54
59
  function printBanner(port) {
55
- const networkIps = getAllNetworkIps();
56
- const envFiles = detectEnvFiles(process.cwd()).map((f) => f.name);
60
+ const envFiles = detectEnvFiles(process.cwd());
61
+ const networkIp = getNetworkIp();
57
62
  console.log(`
58
- ${C.CYAN}\xDF Bini.js${C.RESET} (production)
59
- `);
63
+ ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
60
64
  if (envFiles.length > 0) {
61
65
  console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
62
66
  }
63
67
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
64
- for (const ip of networkIps) {
65
- console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${ip}:${port}/${C.RESET}`);
66
- }
67
- if (!fs.existsSync(API_DIR)) {
68
- console.log(`
69
- ${C.DIM}No api directory found \u2014 API routes disabled.${C.RESET}`);
68
+ if (networkIp) {
69
+ console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
70
70
  }
71
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
71
72
  console.log("");
72
73
  }
73
74
  async function isPortFree(port) {
@@ -83,16 +84,39 @@ async function findFreePort(start2) {
83
84
  if (await isPortFree(port)) {
84
85
  if (port !== start2) {
85
86
  console.log(`
86
- ${C.YELLOW}\u26A0${C.RESET} Port ${start2} is in use, using port ${C.CYAN}${port}${C.RESET} instead.`);
87
+ ${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
87
88
  }
88
89
  return port;
89
90
  }
90
91
  }
91
- throw new Error(`No free port found between ${start2} and ${start2 + 100}`);
92
+ throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
92
93
  }
93
- function scanApiRoutes(dir, baseRoute = "") {
94
+ function startKeyboardLoop(port) {
95
+ const rl = readline.createInterface({ input: process.stdin });
96
+ rl.on("line", (line) => {
97
+ switch (line.trim()) {
98
+ case "h":
99
+ console.log("");
100
+ console.log(" Shortcuts");
101
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
102
+ console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
103
+ console.log("");
104
+ break;
105
+ case "o": {
106
+ const url = `http://localhost:${port}/`;
107
+ const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
108
+ exec(cmd);
109
+ break;
110
+ }
111
+ case "q":
112
+ process.exit(0);
113
+ }
114
+ });
115
+ rl.on("close", () => process.exit(0));
116
+ }
117
+ function scanApiRoutes(dir, baseRoute = "", depth = 0) {
94
118
  const routes = [];
95
- if (!fs.existsSync(dir)) return routes;
119
+ if (depth > 100 || !fs.existsSync(dir)) return routes;
96
120
  let entries;
97
121
  try {
98
122
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -106,26 +130,20 @@ function scanApiRoutes(dir, baseRoute = "") {
106
130
  const isCatchAll2 = entry.name.startsWith("[...") && entry.name.endsWith("]");
107
131
  const isDynamic2 = entry.name.startsWith("[") && entry.name.endsWith("]");
108
132
  const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
109
- routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`));
133
+ routes.push(...scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1));
110
134
  continue;
111
135
  }
112
136
  const ext = path.extname(entry.name);
113
137
  const base = path.basename(entry.name, ext);
114
- if (!API_EXTS.includes(ext)) continue;
138
+ if (!API_EXTS.has(ext)) continue;
115
139
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
116
140
  const isDynamic = base.startsWith("[") && base.endsWith("]");
117
141
  let routePath;
118
- if (isCatchAll) {
119
- routePath = `${baseRoute}/*`;
120
- } else if (base === "index") {
121
- routePath = baseRoute || "/";
122
- } else if (isDynamic) {
123
- routePath = `${baseRoute}/:${base.slice(1, -1)}`;
124
- } else {
125
- routePath = `${baseRoute}/${base}`;
126
- }
127
- const normalizedPath = `/api${routePath}`;
128
- routes.push({ routePath: normalizedPath, filePath: fullPath });
142
+ if (isCatchAll) routePath = `${baseRoute}/*`;
143
+ else if (base === "index") routePath = baseRoute || "/";
144
+ else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
145
+ else routePath = `${baseRoute}/${base}`;
146
+ routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
129
147
  }
130
148
  return routes;
131
149
  }
@@ -137,8 +155,7 @@ function matchRoute(pattern, pathname) {
137
155
  const prefix = patParts.slice(0, -1);
138
156
  if (urlParts.length < prefix.length) return null;
139
157
  for (let i = 0; i < prefix.length; i++) {
140
- if (prefix[i].startsWith(":")) continue;
141
- if (prefix[i] !== urlParts[i]) return null;
158
+ if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
142
159
  }
143
160
  return { "*": urlParts.slice(prefix.length).join("/") };
144
161
  }
@@ -146,7 +163,9 @@ function matchRoute(pattern, pathname) {
146
163
  const params = {};
147
164
  for (let i = 0; i < patParts.length; i++) {
148
165
  if (patParts[i].startsWith(":")) {
149
- params[patParts[i].slice(1)] = decodeURIComponent(urlParts[i]);
166
+ const value = decodeURIComponent(urlParts[i]);
167
+ if (value.includes("..") || value.includes("//")) return null;
168
+ params[patParts[i].slice(1)] = value;
150
169
  } else if (patParts[i] !== urlParts[i]) {
151
170
  return null;
152
171
  }
@@ -162,13 +181,14 @@ async function importHandler(filePath) {
162
181
  return null;
163
182
  }
164
183
  const cached = moduleCache.get(filePath);
165
- if (cached && cached.mtime === mtime) return cached.handler;
184
+ if (cached?.mtime === mtime) return cached.handler;
166
185
  try {
167
186
  const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
168
187
  const handler = mod.default ?? null;
169
188
  moduleCache.set(filePath, { mtime, handler });
170
189
  return handler;
171
- } catch {
190
+ } catch (e) {
191
+ console.error(`[bini-api] import error: ${filePath}`, e?.message);
172
192
  moduleCache.delete(filePath);
173
193
  return null;
174
194
  }
@@ -177,14 +197,14 @@ function readBody(req) {
177
197
  return new Promise((resolve, reject) => {
178
198
  const chunks = [];
179
199
  let size = 0;
180
- const timeout = setTimeout(() => {
200
+ const timer = setTimeout(() => {
181
201
  req.destroy();
182
202
  reject(new Error("Request body timeout"));
183
203
  }, BODY_TIMEOUT);
184
204
  req.on("data", (chunk) => {
185
205
  size += chunk.byteLength;
186
206
  if (size > BODY_SIZE_LIMIT) {
187
- clearTimeout(timeout);
207
+ clearTimeout(timer);
188
208
  req.destroy();
189
209
  reject(new Error("Request body too large"));
190
210
  return;
@@ -192,11 +212,11 @@ function readBody(req) {
192
212
  chunks.push(chunk);
193
213
  });
194
214
  req.on("end", () => {
195
- clearTimeout(timeout);
215
+ clearTimeout(timer);
196
216
  resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
197
217
  });
198
218
  req.on("error", (err) => {
199
- clearTimeout(timeout);
219
+ clearTimeout(timer);
200
220
  reject(err);
201
221
  });
202
222
  });
@@ -212,97 +232,106 @@ function normalizeHeaders(raw) {
212
232
  var CORS_HEADERS = {
213
233
  "Access-Control-Allow-Origin": "*",
214
234
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
215
- "Access-Control-Allow-Headers": "Content-Type,Authorization"
235
+ "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
236
+ "Vary": "Origin"
216
237
  };
217
- function isHonoApp(handler) {
218
- return handler && typeof handler.fetch === "function";
238
+ function invokeHono(honoApp, request) {
239
+ return honoApp.fetch(request, process.env);
219
240
  }
220
241
  var routeCache = null;
221
242
  async function handleApiRequest(req, res, next) {
243
+ if (req.method === "OPTIONS") {
244
+ res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
245
+ res.end();
246
+ return;
247
+ }
248
+ routeCache ??= scanApiRoutes(API_DIR);
249
+ const host = req.headers.host ?? "localhost";
250
+ const rawUrl = `http://${host}${req.url ?? "/"}`;
251
+ const method = (req.method ?? "GET").toUpperCase();
252
+ let parsedUrl;
222
253
  try {
223
- if (req.method === "OPTIONS") {
224
- res.writeHead(204, { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" });
225
- res.end();
226
- return;
227
- }
228
- if (!routeCache) {
229
- routeCache = scanApiRoutes(API_DIR);
230
- }
231
- const host = req.headers.host ?? "localhost";
232
- const url = `http://${host}${req.url ?? ""}`;
233
- const pathname = new URL(url).pathname;
234
- const method = (req.method ?? "GET").toUpperCase();
235
- let matchedRoute;
236
- for (const route of routeCache) {
237
- if (matchRoute(route.routePath, pathname) !== null) {
238
- matchedRoute = route;
239
- break;
240
- }
241
- }
242
- if (!matchedRoute) {
243
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
244
- res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
245
- return;
254
+ parsedUrl = new URL(rawUrl);
255
+ } catch {
256
+ res.writeHead(400, { "Content-Type": "application/json" });
257
+ res.end(JSON.stringify({ error: "Bad request URL" }));
258
+ return;
259
+ }
260
+ const { pathname, search } = parsedUrl;
261
+ let matchedRoute = null;
262
+ let params = null;
263
+ for (const route of routeCache) {
264
+ params = matchRoute(route.routePath, pathname);
265
+ if (params !== null) {
266
+ matchedRoute = route;
267
+ break;
246
268
  }
247
- let body;
269
+ }
270
+ if (!matchedRoute) {
271
+ res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
272
+ res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
273
+ return;
274
+ }
275
+ let body;
276
+ if (!["GET", "HEAD"].includes(method)) {
248
277
  try {
249
- body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
278
+ body = await readBody(req);
250
279
  } catch (e) {
251
- res.writeHead(413, { "Content-Type": "application/json" });
280
+ const status = e.message.includes("too large") ? 413 : 408;
281
+ res.writeHead(status, { "Content-Type": "application/json" });
252
282
  res.end(JSON.stringify({ error: e.message }));
253
283
  return;
254
284
  }
255
- const handler = await importHandler(matchedRoute.filePath);
256
- if (!handler) {
257
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
258
- res.end(JSON.stringify({ error: `Failed to load handler for ${matchedRoute.routePath}` }));
259
- return;
260
- }
261
- let webRes;
262
- try {
263
- if (isHonoApp(handler)) {
264
- const newUrl = url.replace(/^https?:\/\/[^\/]+\/api/, `http://${host}`);
265
- const modifiedReq = new Request(newUrl, {
266
- method,
267
- headers: normalizeHeaders(req.headers),
268
- body: body ?? null
269
- });
270
- webRes = await handler.fetch(modifiedReq);
271
- } else if (typeof handler === "function") {
272
- const params = matchRoute(matchedRoute.routePath, pathname);
273
- const reqWithParams = new Request(url, {
274
- method,
275
- headers: {
276
- ...normalizeHeaders(req.headers),
277
- "x-bini-params": JSON.stringify(params ?? {})
278
- },
279
- body: body ?? null
280
- });
281
- const result = await Promise.race([
282
- handler(reqWithParams),
283
- new Promise((_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT))
284
- ]);
285
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
286
- status: 200,
287
- headers: { "Content-Type": "application/json" }
288
- });
289
- } else {
290
- throw new Error("Invalid handler type");
291
- }
292
- } catch (e) {
285
+ }
286
+ const handler = await importHandler(matchedRoute.filePath);
287
+ if (!handler) {
288
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
289
+ res.end(JSON.stringify({ error: "Failed to load handler" }));
290
+ return;
291
+ }
292
+ const normalizedHeaders = normalizeHeaders(req.headers);
293
+ let webRes;
294
+ try {
295
+ if (typeof handler.fetch === "function") {
296
+ const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
297
+ webRes = await invokeHono(handler, new Request(honoUrl, {
298
+ method,
299
+ headers: normalizedHeaders,
300
+ body: body ? new Uint8Array(body) : null
301
+ }));
302
+ } else if (typeof handler === "function") {
303
+ const reqWithParams = new Request(rawUrl, {
304
+ method,
305
+ headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
306
+ body: body ? new Uint8Array(body) : null
307
+ });
308
+ const result = await Promise.race([
309
+ handler(reqWithParams),
310
+ new Promise(
311
+ (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
312
+ )
313
+ ]);
314
+ webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
315
+ status: 200,
316
+ headers: { "Content-Type": "application/json" }
317
+ });
318
+ } else {
293
319
  res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
294
- res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
320
+ res.end(JSON.stringify({ error: "Handler has no valid default export" }));
295
321
  return;
296
322
  }
297
- const finalHeaders = { ...CORS_HEADERS };
298
- webRes.headers.forEach((v, k) => {
299
- finalHeaders[k] = v;
300
- });
301
- res.writeHead(webRes.status, finalHeaders);
302
- res.end(Buffer.from(await webRes.arrayBuffer()));
303
323
  } catch (e) {
304
- next();
324
+ console.error("[bini-api] handler error:", e?.message ?? e);
325
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
326
+ res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
327
+ return;
305
328
  }
329
+ const finalHeaders = { ...CORS_HEADERS };
330
+ webRes.headers.forEach((v, k) => {
331
+ finalHeaders[k] = v;
332
+ });
333
+ res.writeHead(webRes.status, finalHeaders);
334
+ res.end(Buffer.from(await webRes.arrayBuffer()));
306
335
  }
307
336
  var MIME = {
308
337
  ".html": "text/html; charset=utf-8",
@@ -343,8 +372,7 @@ async function sendFile(filePath, req, res) {
343
372
  return;
344
373
  }
345
374
  const etag = getETag(stat);
346
- const ifNoneMatch = req.headers["if-none-match"];
347
- if (ifNoneMatch === etag) {
375
+ if (req.headers["if-none-match"] === etag) {
348
376
  res.writeHead(304);
349
377
  res.end();
350
378
  return;
@@ -367,12 +395,9 @@ async function sendFile(filePath, req, res) {
367
395
  }
368
396
  async function serveStatic(req, res, next) {
369
397
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
370
- if (pathname.startsWith("/api")) {
371
- return next();
372
- }
398
+ if (pathname.startsWith("/api")) return next();
373
399
  const filePath = path.join(DIST_DIR, pathname);
374
400
  try {
375
- await fs.promises.access(filePath);
376
401
  const stat = await fs.promises.stat(filePath);
377
402
  if (stat.isFile()) {
378
403
  await sendFile(filePath, req, res);
@@ -384,7 +409,6 @@ async function serveStatic(req, res, next) {
384
409
  try {
385
410
  await fs.promises.access(indexPath);
386
411
  await sendFile(indexPath, req, res);
387
- return;
388
412
  } catch {
389
413
  next();
390
414
  }
@@ -408,10 +432,10 @@ function compose(middlewares) {
408
432
  };
409
433
  }
410
434
  async function start() {
411
- await loadEnv(process.cwd());
412
435
  if (!fs.existsSync(DIST_DIR)) {
413
436
  console.error(`
414
- ${C.RED}\u2717${C.RESET} dist/ not found. Run ${C.CYAN}npm run build${C.RESET} first.
437
+ ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
438
+ Run ${C.CYAN}npm run build${C.RESET} first.
415
439
  `);
416
440
  process.exit(1);
417
441
  }
@@ -438,6 +462,7 @@ async function start() {
438
462
  });
439
463
  server.keepAliveTimeout = 65e3;
440
464
  server.headersTimeout = 66e3;
465
+ startKeyboardLoop(port);
441
466
  server.listen(port, "0.0.0.0", () => {
442
467
  printBanner(port);
443
468
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.3",
4
- "description": "Zero-dependency production server for bini-router apps — static files, API routes, SPA fallback",
3
+ "version": "1.0.6",
4
+ "description": "Production server for bini-router apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.js",
@@ -31,9 +31,6 @@
31
31
  "lint": "tsc --noEmit",
32
32
  "clean": "rm -rf dist"
33
33
  },
34
- "dependencies": {
35
- "bini-env": "1.0.8"
36
- },
37
34
  "engines": {
38
35
  "node": ">=20.19.0"
39
36
  },
@@ -41,7 +38,6 @@
41
38
  "bini",
42
39
  "bini-js",
43
40
  "bini-router",
44
- "bini-env",
45
41
  "server",
46
42
  "spa",
47
43
  "vite",
@@ -63,8 +59,9 @@
63
59
  "url": "https://github.com/Binidu01/bini-server/issues"
64
60
  },
65
61
  "devDependencies": {
66
- "@types/node": "^25.3.5",
62
+ "@types/node": "^25.7.0",
67
63
  "tsup": "^8.5.1",
68
- "typescript": "^5.9.3"
64
+ "typescript": "^6.0.3",
65
+ "dotenv": "^17.4.2"
69
66
  }
70
67
  }