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