bini-server 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +20 -88
  2. package/dist/cli.js +114 -81
  3. package/dist/index.js +114 -81
  4. package/package.json +13 -9
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
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
9
 
10
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.
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>
14
14
 
@@ -18,15 +18,15 @@ Serves your `dist/` statically and proxies `/api/*` to your `src/app/api/` handl
18
18
 
19
19
  - ⚡ **Zero dependencies** — pure Node.js built-ins only
20
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)
21
+ - 🌐 **API routes** — serves `/api/*` from your `src/app/api/` handlers (Hono apps + plain functions)
22
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
23
+ - 🌿 **Auto env loading** — `.env` loaded automatically via [bini-env](https://www.npmjs.com/package/bini-env)
24
24
  - 🏷️ **ETag support** — `304 Not Modified` responses for unchanged files
25
25
  - 🛡️ **CORS** — enabled by default on all API responses
26
- - ⏱️ **Timeouts** — 30s body read + 30s handler timeout with proper error responses
26
+ - ⏱️ **Timeouts** — 30s body read timeout + 30s handler timeout
27
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
28
+ - 🔌 **Port auto-increment** — starts at `3000`, increments if busy
29
+ - 🪄 **Graceful shutdown** — handles `SIGTERM` + `SIGINT` with 10s force-exit fallback
30
30
  - 🖥️ **Cross-platform** — works on Windows, macOS, and Linux
31
31
 
32
32
  ---
@@ -80,57 +80,36 @@ Terminal output:
80
80
 
81
81
  ## Environment Variables
82
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.
83
+ `.env` is loaded automatically at startup — all vars are available in `process.env` in your API handlers with no imports needed.
84
84
 
85
85
  ```env
86
- # .env
87
86
  PORT=3000
88
-
89
- # Server-side vars — used by API routes via getEnv() / requireEnv()
90
87
  SMTP_USER=user@smtp.example.com
91
88
  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
89
  ```
97
90
 
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
91
  ---
101
92
 
102
- ## How it works
103
-
104
- bini-server runs a plain Node.js `http` server with a three-layer middleware stack:
93
+ ## Important: ship your `src/` folder
105
94
 
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
- ```
95
+ bini-server runs your API handlers directly from `src/app/api/` — they are **not** compiled into `dist/`. When deploying, make sure your server has access to both `dist/` and `src/app/api/`.
115
96
 
116
- No Vite, no Express, no Fastify — just Node's built-in `http` module.
97
+ For VPS/pm2 this means deploying your full project directory, not just `dist/`. For Railway, Render, and Fly.io this happens automatically since they clone your repository.
117
98
 
118
99
  ---
119
100
 
120
101
  ## Port
121
102
 
122
- Default port is `3000`. Override via environment variable:
123
-
124
- ```bash
125
- PORT=8080 bini-server
126
- ```
127
-
128
- Or in `.env`:
103
+ Default port is `3000`. Override via `.env` or inline:
129
104
 
130
105
  ```env
131
106
  PORT=8080
132
107
  ```
133
108
 
109
+ ```bash
110
+ PORT=8080 bini-server
111
+ ```
112
+
134
113
  If the port is busy, bini-server automatically increments and warns:
135
114
 
136
115
  ```
@@ -141,7 +120,7 @@ If the port is busy, bini-server automatically increments and warns:
141
120
 
142
121
  ## Configurable Directories
143
122
 
144
- By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars if your project uses a different structure:
123
+ By default bini-server reads from `src/app/api/` and `dist/`. Override via env vars:
145
124
 
146
125
  ```env
147
126
  BINI_API_DIR=src/api # default: src/app/api
@@ -150,37 +129,6 @@ BINI_DIST_DIR=build # default: dist
150
129
 
151
130
  ---
152
131
 
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
132
  ## Deployment
185
133
 
186
134
  ### VPS (Ubuntu, Debian, etc.)
@@ -201,7 +149,7 @@ pm2 startup
201
149
 
202
150
  ### Railway
203
151
 
204
- Set start command to `npm start` in your Railway project settings. Railway injects `PORT` automatically.
152
+ Set start command to `npm start`. Railway injects `PORT` automatically.
205
153
 
206
154
  ### Render
207
155
 
@@ -217,32 +165,16 @@ Set start command to `npm start`. Render injects `PORT` automatically.
217
165
 
218
166
  ---
219
167
 
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
168
  ## vs `vite preview`
237
169
 
238
170
  | Feature | `vite preview` | `bini-server` |
239
171
  |---|---|---|
240
172
  | Serves `dist/` | ✅ | ✅ |
241
- | API routes | ✅ via bini-router | ✅ via bini-router |
173
+ | API routes | ✅ | ✅ |
242
174
  | SPA fallback | ✅ | ✅ |
243
- | Auto env loading | ✅ via bini-env | ✅ via bini-env |
175
+ | Auto env loading | ✅ | ✅ |
244
176
  | ETag / 304 support | ❌ | ✅ |
245
- | Production use | ❌ not recommended | ✅ |
177
+ | Production use | ❌ | ✅ |
246
178
  | Body timeout | ❌ | ✅ 30s |
247
179
  | Body size limit | ❌ | ✅ 10MB |
248
180
  | Handler timeout | ❌ | ✅ 30s |
package/dist/cli.js CHANGED
@@ -11,6 +11,21 @@ import { pathToFileURL } from "url";
11
11
  import { pipeline } from "stream/promises";
12
12
  import { createReadStream } from "fs";
13
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
+ })();
14
29
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
15
30
  var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
16
31
  var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
@@ -101,8 +116,18 @@ function scanApiRoutes(dir, baseRoute = "") {
101
116
  if (!API_EXTS.includes(ext)) continue;
102
117
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
103
118
  const isDynamic = base.startsWith("[") && base.endsWith("]");
104
- const routePath = isCatchAll ? `${baseRoute}/*` : base === "index" ? baseRoute || "/" : isDynamic ? `${baseRoute}/:${base.slice(1, -1)}` : `${baseRoute}/${base}`;
105
- routes.push({ routePath, filePath: fullPath });
119
+ 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 });
106
131
  }
107
132
  return routes;
108
133
  }
@@ -136,6 +161,7 @@ async function importHandler(filePath) {
136
161
  try {
137
162
  mtime = fs.statSync(filePath).mtimeMs;
138
163
  } catch {
164
+ return null;
139
165
  }
140
166
  const cached = moduleCache.get(filePath);
141
167
  if (cached && cached.mtime === mtime) return cached.handler;
@@ -144,9 +170,9 @@ async function importHandler(filePath) {
144
170
  const handler = mod.default ?? null;
145
171
  moduleCache.set(filePath, { mtime, handler });
146
172
  return handler;
147
- } catch (e) {
173
+ } catch {
148
174
  moduleCache.delete(filePath);
149
- throw e;
175
+ return null;
150
176
  }
151
177
  }
152
178
  function readBody(req) {
@@ -190,6 +216,9 @@ var CORS_HEADERS = {
190
216
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
191
217
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
192
218
  };
219
+ function isHonoApp(handler) {
220
+ return handler && typeof handler.fetch === "function";
221
+ }
193
222
  var routeCache = null;
194
223
  async function handleApiRequest(req, res, next) {
195
224
  try {
@@ -199,12 +228,24 @@ async function handleApiRequest(req, res, next) {
199
228
  return;
200
229
  }
201
230
  if (!routeCache) {
202
- routeCache = { routes: scanApiRoutes(API_DIR, "/api") };
231
+ routeCache = scanApiRoutes(API_DIR);
203
232
  }
204
233
  const host = req.headers.host ?? "localhost";
205
- const url = `http://${host}${req.url}`;
234
+ const url = `http://${host}${req.url ?? ""}`;
206
235
  const pathname = new URL(url).pathname;
207
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;
248
+ }
208
249
  let body;
209
250
  try {
210
251
  body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
@@ -213,70 +254,55 @@ async function handleApiRequest(req, res, next) {
213
254
  res.end(JSON.stringify({ error: e.message }));
214
255
  return;
215
256
  }
216
- const webReq = new Request(url, {
217
- method,
218
- headers: normalizeHeaders(req.headers),
219
- body: body ?? null
220
- });
221
- for (const route of routeCache.routes) {
222
- let handler;
223
- try {
224
- handler = await importHandler(route.filePath);
225
- } catch (e) {
226
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
227
- res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
228
- return;
229
- }
230
- if (!handler) continue;
231
- let webRes;
232
- try {
233
- if (typeof handler.fetch === "function") {
234
- const result = await Promise.race([
235
- handler.fetch(webReq.clone()),
236
- new Promise(
237
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
238
- )
239
- ]);
240
- webRes = result;
241
- if (webRes.status === 404) continue;
242
- } else if (typeof handler === "function") {
243
- const params = matchRoute(route.routePath, pathname);
244
- if (params === null) continue;
245
- const reqWithParams = new Request(webReq.clone(), {
246
- headers: {
247
- ...normalizeHeaders(req.headers),
248
- "x-bini-params": JSON.stringify(params)
249
- }
250
- });
251
- const result = await Promise.race([
252
- handler(reqWithParams),
253
- new Promise(
254
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
255
- )
256
- ]);
257
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
258
- status: 200,
259
- headers: { "Content-Type": "application/json" }
260
- });
261
- } else {
262
- continue;
263
- }
264
- } catch (e) {
265
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
266
- res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
267
- return;
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");
268
293
  }
269
- const finalHeaders = { ...CORS_HEADERS };
270
- webRes.headers.forEach((v, k) => {
271
- finalHeaders[k] = v;
272
- });
273
- res.writeHead(webRes.status, finalHeaders);
274
- res.end(Buffer.from(await webRes.arrayBuffer()));
294
+ } catch (e) {
295
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
296
+ res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
275
297
  return;
276
298
  }
277
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
278
- res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
279
- } catch {
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
+ } catch (e) {
280
306
  next();
281
307
  }
282
308
  }
@@ -312,7 +338,7 @@ async function sendFile(filePath, req, res) {
312
338
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
313
339
  let stat;
314
340
  try {
315
- stat = fs.statSync(filePath);
341
+ stat = await fs.promises.stat(filePath);
316
342
  } catch {
317
343
  res.writeHead(404);
318
344
  res.end("Not found");
@@ -342,23 +368,33 @@ async function sendFile(filePath, req, res) {
342
368
  }
343
369
  }
344
370
  async function serveStatic(req, res, next) {
345
- const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
371
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
372
+ if (pathname.startsWith("/api")) {
373
+ return next();
374
+ }
346
375
  const filePath = path.join(DIST_DIR, pathname);
347
- if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
348
- await sendFile(filePath, req, res);
349
- return;
376
+ try {
377
+ await fs.promises.access(filePath);
378
+ const stat = await fs.promises.stat(filePath);
379
+ if (stat.isFile()) {
380
+ await sendFile(filePath, req, res);
381
+ return;
382
+ }
383
+ } catch {
350
384
  }
351
385
  const indexPath = path.join(DIST_DIR, "index.html");
352
- if (fs.existsSync(indexPath)) {
386
+ try {
387
+ await fs.promises.access(indexPath);
353
388
  await sendFile(indexPath, req, res);
354
389
  return;
390
+ } catch {
391
+ next();
355
392
  }
356
- next();
357
393
  }
358
394
  function compose(middlewares) {
359
395
  return async (req, res) => {
360
396
  let idx = 0;
361
- async function next() {
397
+ const next = async () => {
362
398
  if (idx >= middlewares.length) return;
363
399
  const fn = middlewares[idx++];
364
400
  try {
@@ -369,7 +405,7 @@ function compose(middlewares) {
369
405
  res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
370
406
  }
371
407
  }
372
- }
408
+ };
373
409
  await next();
374
410
  };
375
411
  }
@@ -407,13 +443,10 @@ async function start() {
407
443
  server.listen(port, "0.0.0.0", () => {
408
444
  printBanner(port);
409
445
  });
410
- function shutdown() {
411
- console.log(`
412
- ${C.YELLOW}\u26A0${C.RESET} Shutting down...
413
- `);
446
+ const shutdown = () => {
414
447
  server.close(() => process.exit(0));
415
448
  setTimeout(() => process.exit(1), 1e4).unref();
416
- }
449
+ };
417
450
  process.on("SIGTERM", shutdown);
418
451
  process.on("SIGINT", shutdown);
419
452
  }
package/dist/index.js CHANGED
@@ -9,6 +9,21 @@ import { pathToFileURL } from "url";
9
9
  import { pipeline } from "stream/promises";
10
10
  import { createReadStream } from "fs";
11
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
+ })();
12
27
  var DEFAULT_PORT = parseInt(process.env.PORT ?? "3000", 10);
13
28
  var API_DIR = path.join(process.cwd(), process.env.BINI_API_DIR ?? "src/app/api");
14
29
  var DIST_DIR = path.join(process.cwd(), process.env.BINI_DIST_DIR ?? "dist");
@@ -99,8 +114,18 @@ function scanApiRoutes(dir, baseRoute = "") {
99
114
  if (!API_EXTS.includes(ext)) continue;
100
115
  const isCatchAll = base.startsWith("[...") && base.endsWith("]");
101
116
  const isDynamic = base.startsWith("[") && base.endsWith("]");
102
- const routePath = isCatchAll ? `${baseRoute}/*` : base === "index" ? baseRoute || "/" : isDynamic ? `${baseRoute}/:${base.slice(1, -1)}` : `${baseRoute}/${base}`;
103
- routes.push({ routePath, filePath: fullPath });
117
+ 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 });
104
129
  }
105
130
  return routes;
106
131
  }
@@ -134,6 +159,7 @@ async function importHandler(filePath) {
134
159
  try {
135
160
  mtime = fs.statSync(filePath).mtimeMs;
136
161
  } catch {
162
+ return null;
137
163
  }
138
164
  const cached = moduleCache.get(filePath);
139
165
  if (cached && cached.mtime === mtime) return cached.handler;
@@ -142,9 +168,9 @@ async function importHandler(filePath) {
142
168
  const handler = mod.default ?? null;
143
169
  moduleCache.set(filePath, { mtime, handler });
144
170
  return handler;
145
- } catch (e) {
171
+ } catch {
146
172
  moduleCache.delete(filePath);
147
- throw e;
173
+ return null;
148
174
  }
149
175
  }
150
176
  function readBody(req) {
@@ -188,6 +214,9 @@ var CORS_HEADERS = {
188
214
  "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
189
215
  "Access-Control-Allow-Headers": "Content-Type,Authorization"
190
216
  };
217
+ function isHonoApp(handler) {
218
+ return handler && typeof handler.fetch === "function";
219
+ }
191
220
  var routeCache = null;
192
221
  async function handleApiRequest(req, res, next) {
193
222
  try {
@@ -197,12 +226,24 @@ async function handleApiRequest(req, res, next) {
197
226
  return;
198
227
  }
199
228
  if (!routeCache) {
200
- routeCache = { routes: scanApiRoutes(API_DIR, "/api") };
229
+ routeCache = scanApiRoutes(API_DIR);
201
230
  }
202
231
  const host = req.headers.host ?? "localhost";
203
- const url = `http://${host}${req.url}`;
232
+ const url = `http://${host}${req.url ?? ""}`;
204
233
  const pathname = new URL(url).pathname;
205
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;
246
+ }
206
247
  let body;
207
248
  try {
208
249
  body = !["GET", "HEAD"].includes(method) ? await readBody(req) : void 0;
@@ -211,70 +252,55 @@ async function handleApiRequest(req, res, next) {
211
252
  res.end(JSON.stringify({ error: e.message }));
212
253
  return;
213
254
  }
214
- const webReq = new Request(url, {
215
- method,
216
- headers: normalizeHeaders(req.headers),
217
- body: body ?? null
218
- });
219
- for (const route of routeCache.routes) {
220
- let handler;
221
- try {
222
- handler = await importHandler(route.filePath);
223
- } catch (e) {
224
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
225
- res.end(JSON.stringify({ error: `Failed to load handler: ${e.message}` }));
226
- return;
227
- }
228
- if (!handler) continue;
229
- let webRes;
230
- try {
231
- if (typeof handler.fetch === "function") {
232
- const result = await Promise.race([
233
- handler.fetch(webReq.clone()),
234
- new Promise(
235
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
236
- )
237
- ]);
238
- webRes = result;
239
- if (webRes.status === 404) continue;
240
- } else if (typeof handler === "function") {
241
- const params = matchRoute(route.routePath, pathname);
242
- if (params === null) continue;
243
- const reqWithParams = new Request(webReq.clone(), {
244
- headers: {
245
- ...normalizeHeaders(req.headers),
246
- "x-bini-params": JSON.stringify(params)
247
- }
248
- });
249
- const result = await Promise.race([
250
- handler(reqWithParams),
251
- new Promise(
252
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
253
- )
254
- ]);
255
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
256
- status: 200,
257
- headers: { "Content-Type": "application/json" }
258
- });
259
- } else {
260
- continue;
261
- }
262
- } catch (e) {
263
- res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
264
- res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
265
- return;
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");
266
291
  }
267
- const finalHeaders = { ...CORS_HEADERS };
268
- webRes.headers.forEach((v, k) => {
269
- finalHeaders[k] = v;
270
- });
271
- res.writeHead(webRes.status, finalHeaders);
272
- res.end(Buffer.from(await webRes.arrayBuffer()));
292
+ } catch (e) {
293
+ res.writeHead(500, { "Content-Type": "application/json", ...CORS_HEADERS });
294
+ res.end(JSON.stringify({ error: e.message ?? "Internal Server Error" }));
273
295
  return;
274
296
  }
275
- res.writeHead(404, { "Content-Type": "application/json", ...CORS_HEADERS });
276
- res.end(JSON.stringify({ error: `No API handler found for ${req.url}` }));
277
- } catch {
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
+ } catch (e) {
278
304
  next();
279
305
  }
280
306
  }
@@ -310,7 +336,7 @@ async function sendFile(filePath, req, res) {
310
336
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
311
337
  let stat;
312
338
  try {
313
- stat = fs.statSync(filePath);
339
+ stat = await fs.promises.stat(filePath);
314
340
  } catch {
315
341
  res.writeHead(404);
316
342
  res.end("Not found");
@@ -340,23 +366,33 @@ async function sendFile(filePath, req, res) {
340
366
  }
341
367
  }
342
368
  async function serveStatic(req, res, next) {
343
- const pathname = new URL(req.url ?? "/", `http://localhost`).pathname;
369
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
370
+ if (pathname.startsWith("/api")) {
371
+ return next();
372
+ }
344
373
  const filePath = path.join(DIST_DIR, pathname);
345
- if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
346
- await sendFile(filePath, req, res);
347
- return;
374
+ try {
375
+ await fs.promises.access(filePath);
376
+ const stat = await fs.promises.stat(filePath);
377
+ if (stat.isFile()) {
378
+ await sendFile(filePath, req, res);
379
+ return;
380
+ }
381
+ } catch {
348
382
  }
349
383
  const indexPath = path.join(DIST_DIR, "index.html");
350
- if (fs.existsSync(indexPath)) {
384
+ try {
385
+ await fs.promises.access(indexPath);
351
386
  await sendFile(indexPath, req, res);
352
387
  return;
388
+ } catch {
389
+ next();
353
390
  }
354
- next();
355
391
  }
356
392
  function compose(middlewares) {
357
393
  return async (req, res) => {
358
394
  let idx = 0;
359
- async function next() {
395
+ const next = async () => {
360
396
  if (idx >= middlewares.length) return;
361
397
  const fn = middlewares[idx++];
362
398
  try {
@@ -367,7 +403,7 @@ function compose(middlewares) {
367
403
  res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
368
404
  }
369
405
  }
370
- }
406
+ };
371
407
  await next();
372
408
  };
373
409
  }
@@ -405,13 +441,10 @@ async function start() {
405
441
  server.listen(port, "0.0.0.0", () => {
406
442
  printBanner(port);
407
443
  });
408
- function shutdown() {
409
- console.log(`
410
- ${C.YELLOW}\u26A0${C.RESET} Shutting down...
411
- `);
444
+ const shutdown = () => {
412
445
  server.close(() => process.exit(0));
413
446
  setTimeout(() => process.exit(1), 1e4).unref();
414
- }
447
+ };
415
448
  process.on("SIGTERM", shutdown);
416
449
  process.on("SIGINT", shutdown);
417
450
  }
package/package.json CHANGED
@@ -1,15 +1,20 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Zero-dependency production server for bini-router apps — static files, API routes, SPA fallback",
5
5
  "type": "module",
6
- "main": "./dist/index.js",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
7
8
  "types": "./dist/index.d.ts",
8
9
  "exports": {
9
10
  ".": {
10
11
  "import": {
11
12
  "types": "./dist/index.d.ts",
12
13
  "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
13
18
  }
14
19
  }
15
20
  },
@@ -27,10 +32,10 @@
27
32
  "clean": "rm -rf dist"
28
33
  },
29
34
  "dependencies": {
30
- "bini-env": "^1.0.6"
35
+ "bini-env": "1.0.8"
31
36
  },
32
37
  "engines": {
33
- "node": ">=18.0.0"
38
+ "node": ">=20.19.0"
34
39
  },
35
40
  "keywords": [
36
41
  "bini",
@@ -52,15 +57,14 @@
52
57
  "homepage": "https://bini.js.org",
53
58
  "repository": {
54
59
  "type": "git",
55
- "url": "https://github.com/Binidu01/bini-server.git"
60
+ "url": "git+https://github.com/Binidu01/bini-server.git"
56
61
  },
57
62
  "bugs": {
58
63
  "url": "https://github.com/Binidu01/bini-server/issues"
59
64
  },
60
65
  "devDependencies": {
61
- "@types/node": "^25",
62
- "bini-env" : "^1.0.6",
63
- "tsup" : "^8",
64
- "typescript" : "^5"
66
+ "@types/node": "^25.3.5",
67
+ "tsup": "^8.5.1",
68
+ "typescript": "^5.9.3"
65
69
  }
66
70
  }