bini-server 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12,23 +12,17 @@ import { Readable } from "stream";
12
12
  import { pipeline } from "stream/promises";
13
13
  import { loadEnvFiles, envFilesFor } from "bini-env/node";
14
14
  function getEnvVar(key, defaultValue) {
15
- const biniKey = `BINI_${key}`;
16
- if (process.env[biniKey] !== void 0) return process.env[biniKey];
17
- const viteKey = `VITE_${key}`;
18
- if (process.env[viteKey] !== void 0) return process.env[viteKey];
19
- if (process.env[key] !== void 0) return process.env[key];
20
- return defaultValue;
15
+ return process.env[`BINI_${key}`] ?? process.env[`VITE_${key}`] ?? process.env[key] ?? defaultValue;
21
16
  }
22
17
  function getEnvVarNumber(key, defaultValue) {
23
- const value = getEnvVar(key);
24
- if (value === void 0) return defaultValue;
25
- const parsed = parseInt(value, 10);
26
- return isNaN(parsed) ? defaultValue : parsed;
18
+ const raw = getEnvVar(key);
19
+ if (raw === void 0) return defaultValue;
20
+ const n = parseInt(raw, 10);
21
+ return isNaN(n) ? defaultValue : n;
27
22
  }
28
23
  function readConfig() {
29
24
  const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
30
25
  const apiDir = path.join(distDir, "api");
31
- const apiEntry = path.join(apiDir, "index.mjs");
32
26
  const rawBase = (getEnvVar("BASE") ?? "").trim();
33
27
  const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + rawBase.replace(/^\/+|\/+$/g, "");
34
28
  return {
@@ -39,7 +33,7 @@ function readConfig() {
39
33
  distDir,
40
34
  compiledApiDir: apiDir + path.sep,
41
35
  apiDir,
42
- apiEntry,
36
+ apiEntry: path.join(apiDir, "index.mjs"),
43
37
  base,
44
38
  isProd: process.env.NODE_ENV === "production"
45
39
  };
@@ -57,87 +51,79 @@ var C = {
57
51
  GREEN: "\x1B[32m",
58
52
  RED: "\x1B[31m",
59
53
  YELLOW: "\x1B[33m",
60
- BOLD: "\x1B[1m",
61
54
  DIM: "\x1B[2m"
62
55
  };
63
56
  function stripBase(pathname) {
64
- const base = config.base;
57
+ const { base } = config;
65
58
  if (!base) return pathname || "/";
66
59
  if (pathname === base || pathname === base + "/") return "/";
67
60
  if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
68
61
  return null;
69
62
  }
63
+ function toApiPath(pathname) {
64
+ let p = pathname;
65
+ const { base } = config;
66
+ if (base) {
67
+ if (p === base || p.startsWith(base + "/")) p = p.slice(base.length) || "/";
68
+ else return null;
69
+ }
70
+ if (p === "/api") return "/";
71
+ if (p.startsWith("/api/")) return p.slice(4);
72
+ return null;
73
+ }
74
+ function isApiRequest(url) {
75
+ if (!url) return false;
76
+ try {
77
+ return toApiPath(new URL(url, "http://localhost").pathname) !== null;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
70
82
  function scanShellRoutes() {
71
- const shellRoutes = /* @__PURE__ */ new Set();
72
- const rootDir = config.distDir;
73
- function walkDir(dir, currentPath) {
83
+ const routes = /* @__PURE__ */ new Set();
84
+ function walk(dir, prefix) {
85
+ let entries;
74
86
  try {
75
- const entries = fs.readdirSync(dir, { withFileTypes: true });
76
- for (const entry of entries) {
77
- if (!entry.isDirectory()) continue;
78
- if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
79
- const fullPath = path.join(dir, entry.name);
80
- const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
81
- if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
82
- const indexPath = path.join(fullPath, "index.html");
83
- if (fs.existsSync(indexPath)) {
84
- shellRoutes.add(`/${routePath}`);
85
- }
86
- }
87
- walkDir(fullPath, routePath);
88
- }
87
+ entries = fs.readdirSync(dir, { withFileTypes: true });
89
88
  } catch {
89
+ return;
90
+ }
91
+ for (const entry of entries) {
92
+ if (!entry.isDirectory()) continue;
93
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
94
+ const fullPath = path.join(dir, entry.name);
95
+ const routePath = prefix ? `${prefix}/${entry.name}` : entry.name;
96
+ if (entry.name.startsWith("[") && entry.name.endsWith("]") && fs.existsSync(path.join(fullPath, "index.html"))) {
97
+ routes.add(`/${routePath}`);
98
+ }
99
+ walk(fullPath, routePath);
90
100
  }
91
101
  }
92
- try {
93
- walkDir(rootDir, "");
94
- } catch {
95
- }
96
- return shellRoutes;
102
+ walk(config.distDir, "");
103
+ return routes;
97
104
  }
98
105
  var shellRouteCache = null;
99
106
  function getShellRoutes() {
100
- if (!shellRouteCache) {
101
- shellRouteCache = scanShellRoutes();
102
- }
103
- return shellRouteCache;
107
+ return shellRouteCache ??= scanShellRoutes();
104
108
  }
105
109
  function findMatchingShellRoute(pathname) {
106
- const shellRoutes = getShellRoutes();
107
110
  const pathSegments = pathname.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
108
- for (const shellRoute of shellRoutes) {
111
+ for (const shellRoute of getShellRoutes()) {
109
112
  const shellSegments = shellRoute.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
110
113
  if (shellSegments.length === 0) continue;
111
114
  const last = shellSegments[shellSegments.length - 1];
112
115
  const isRequiredCatchAll = last.startsWith("[...") && !last.startsWith("[[...");
113
- const isOptionalCatchAll = last.startsWith("[[...");
114
- const isCatchAll = isRequiredCatchAll || isOptionalCatchAll;
115
- if (isCatchAll) {
116
+ const isOptionalCatchAll = last.startsWith("[[") && last.endsWith("]]");
117
+ if (isRequiredCatchAll || isOptionalCatchAll) {
116
118
  const prefix = shellSegments.slice(0, -1);
117
119
  if (pathSegments.length < prefix.length) continue;
118
120
  if (isRequiredCatchAll && pathSegments.length === prefix.length) continue;
119
- let matches2 = true;
120
- for (let i = 0; i < prefix.length; i++) {
121
- const seg = prefix[i];
122
- if (seg.startsWith("[") && seg.endsWith("]")) continue;
123
- if (seg !== pathSegments[i]) {
124
- matches2 = false;
125
- break;
126
- }
127
- }
121
+ const matches2 = prefix.every((seg, i) => seg.startsWith("[") && seg.endsWith("]") || seg === pathSegments[i]);
128
122
  if (matches2) return shellRoute;
129
123
  continue;
130
124
  }
131
125
  if (shellSegments.length !== pathSegments.length) continue;
132
- let matches = true;
133
- for (let i = 0; i < shellSegments.length; i++) {
134
- const seg = shellSegments[i];
135
- if (seg.startsWith("[") && seg.endsWith("]")) continue;
136
- if (seg !== pathSegments[i]) {
137
- matches = false;
138
- break;
139
- }
140
- }
126
+ const matches = shellSegments.every((seg, i) => seg.startsWith("[") && seg.endsWith("]") || seg === pathSegments[i]);
141
127
  if (matches) return shellRoute;
142
128
  }
143
129
  return null;
@@ -145,6 +131,7 @@ function findMatchingShellRoute(pathname) {
145
131
  function getNetworkIp() {
146
132
  const ifaces = os.networkInterfaces();
147
133
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
134
+ const candidates = [];
148
135
  for (const name in ifaces) {
149
136
  if (SKIP.test(name)) continue;
150
137
  for (const iface of ifaces[name] ?? []) {
@@ -153,15 +140,10 @@ function getNetworkIp() {
153
140
  if (a === 169 && b === 254) continue;
154
141
  const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
155
142
  if (isPrivate) return iface.address;
143
+ candidates.push(iface.address);
156
144
  }
157
145
  }
158
- for (const name in ifaces) {
159
- if (SKIP.test(name)) continue;
160
- for (const iface of ifaces[name] ?? []) {
161
- if (!iface.internal && iface.family === "IPv4") return iface.address;
162
- }
163
- }
164
- return null;
146
+ return candidates[0] ?? null;
165
147
  }
166
148
  function printBanner(port) {
167
149
  const envFiles = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
@@ -182,7 +164,7 @@ function printBanner(port) {
182
164
  console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
183
165
  console.log("");
184
166
  }
185
- async function isPortFree(port) {
167
+ function isPortFree(port) {
186
168
  return new Promise((resolve) => {
187
169
  const server = net.createServer();
188
170
  server.once("error", () => resolve(false));
@@ -192,9 +174,7 @@ async function isPortFree(port) {
192
174
  }
193
175
  async function findFreePort(start2) {
194
176
  for (let port = start2; port < start2 + 100; port++) {
195
- if (await isPortFree(port)) {
196
- return port;
197
- }
177
+ if (await isPortFree(port)) return port;
198
178
  console.log(`Port ${port} is in use, trying another one...`);
199
179
  }
200
180
  throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
@@ -259,66 +239,59 @@ function normalizeHeaders(raw) {
259
239
  }
260
240
  return out;
261
241
  }
262
- function toApiPath(pathname) {
263
- let p = pathname;
264
- const base = config.base;
265
- if (base) {
266
- if (p === base || p.startsWith(base + "/")) p = p.slice(base.length) || "/";
267
- else return null;
268
- }
269
- if (p === "/api") return "/";
270
- if (p.startsWith("/api/")) return p.slice(4);
271
- return null;
272
- }
273
- function isApiRequest(url) {
274
- if (!url) return false;
275
- try {
276
- return toApiPath(new URL(url, "http://localhost").pathname) !== null;
277
- } catch {
278
- return false;
279
- }
242
+ async function toWebRequest(req, host) {
243
+ const method = (req.method ?? "GET").toUpperCase();
244
+ const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
245
+ return new Request(`http://${host}${req.url ?? "/"}`, {
246
+ method,
247
+ headers: normalizeHeaders(req.headers),
248
+ body: body ? new Uint8Array(body) : null
249
+ });
280
250
  }
281
251
  var apiFetch = null;
282
252
  var apiLoadPromise = null;
253
+ function noApiFetch() {
254
+ return async () => new Response(
255
+ JSON.stringify({ error: "No API routes compiled" }),
256
+ { status: 503, headers: { "content-type": "application/json" } }
257
+ );
258
+ }
259
+ function failedApiFetch() {
260
+ return async () => new Response(
261
+ JSON.stringify({ error: "API failed to load" }),
262
+ { status: 500, headers: { "content-type": "application/json" } }
263
+ );
264
+ }
283
265
  async function loadApiFetch() {
284
266
  if (apiFetch) return apiFetch;
285
267
  if (apiLoadPromise) return apiLoadPromise;
286
268
  apiLoadPromise = (async () => {
269
+ const entry = resolveApiEntry();
270
+ if (!entry) {
271
+ try {
272
+ await import(pathToFileURL(config.apiEntry).href);
273
+ } catch (e) {
274
+ const tag = process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
275
+ console.warn(`
276
+ ${tag} failed to load handler for /api:`, e);
277
+ }
278
+ apiFetch = noApiFetch();
279
+ return apiFetch;
280
+ }
287
281
  try {
288
- const entry = resolveApiEntry();
289
- if (!entry) throw new Error(`${config.apiEntry} not found`);
290
282
  const mod = await import(pathToFileURL(entry).href);
291
- if (typeof mod.fetch !== "function") {
292
- throw new Error(`${entry} does not export fetch()`);
283
+ if (typeof mod.fetch === "function") {
284
+ apiFetch = mod.fetch;
285
+ } else {
286
+ apiFetch = failedApiFetch();
293
287
  }
294
- apiFetch = mod.fetch;
295
- } catch (err) {
296
- const msg = err instanceof Error ? err.message : String(err);
297
- console.warn(
298
- `
299
- ${C.YELLOW}\u26A0${C.RESET} No compiled API in ${config.apiDir}.
300
- ${C.DIM}${msg}${C.RESET}
301
- API requests will return 404. Run ${C.CYAN}npm run build${C.RESET} to compile it.
302
- `
303
- );
304
- apiFetch = async () => new Response(
305
- JSON.stringify({ error: "No API routes compiled" }),
306
- { status: 404, headers: { "content-type": "application/json" } }
307
- );
288
+ } catch {
289
+ apiFetch = failedApiFetch();
308
290
  }
309
291
  return apiFetch;
310
292
  })();
311
293
  return apiLoadPromise;
312
294
  }
313
- async function toWebRequest(req, host) {
314
- const method = (req.method ?? "GET").toUpperCase();
315
- const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
316
- return new Request(`http://${host}${req.url ?? "/"}`, {
317
- method,
318
- headers: normalizeHeaders(req.headers),
319
- body: body ? new Uint8Array(body) : null
320
- });
321
- }
322
295
  function sendJson(res, status, body, extra = {}) {
323
296
  res.writeHead(status, { "content-type": "application/json", ...extra });
324
297
  res.end(JSON.stringify(body));
@@ -361,8 +334,10 @@ async function handleApiRequest(req, res) {
361
334
  } catch {
362
335
  return sendJson(res, 400, { error: "Bad request URL" });
363
336
  }
364
- if (toApiPath(parsedUrl.pathname) === null) return sendJson(res, 404, { error: "Not Found" });
365
- const fetchApi = await loadApiFetch();
337
+ if (toApiPath(parsedUrl.pathname) === null) {
338
+ return sendJson(res, 404, { error: "Not Found" });
339
+ }
340
+ await loadApiFetch();
366
341
  let webReq;
367
342
  try {
368
343
  webReq = await toWebRequest(req, host);
@@ -370,30 +345,52 @@ async function handleApiRequest(req, res) {
370
345
  const message = e?.message ?? "Bad request";
371
346
  return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
372
347
  }
373
- const ctx = {
374
- waitUntil(p) {
375
- p.catch(() => {
376
- });
377
- }
378
- };
348
+ const ctx = { waitUntil(p) {
349
+ p.catch(() => {
350
+ });
351
+ } };
379
352
  try {
380
353
  const webRes = await withTimeout(
381
- fetchApi(webReq, process.env, ctx),
354
+ apiFetch(webReq, process.env, ctx),
382
355
  config.handlerTimeout
383
356
  );
384
357
  await sendWebResponse(res, webRes, method);
385
358
  } catch (e) {
386
- console.error("[bini-api] handler error:", e);
359
+ const tag = process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
360
+ console.error(`
361
+ ${tag} failed to handle ${method} ${parsedUrl.pathname}:`, e);
387
362
  if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
388
363
  else res.end();
389
364
  }
390
365
  }
366
+ var MIME_TYPES = {
367
+ ".html": "text/html; charset=utf-8",
368
+ ".js": "application/javascript",
369
+ ".mjs": "application/javascript",
370
+ ".css": "text/css",
371
+ ".json": "application/json",
372
+ ".png": "image/png",
373
+ ".jpg": "image/jpeg",
374
+ ".jpeg": "image/jpeg",
375
+ ".gif": "image/gif",
376
+ ".svg": "image/svg+xml",
377
+ ".ico": "image/x-icon",
378
+ ".webp": "image/webp",
379
+ ".avif": "image/avif",
380
+ ".woff": "font/woff",
381
+ ".woff2": "font/woff2",
382
+ ".ttf": "font/ttf",
383
+ ".eot": "application/vnd.ms-fontobject",
384
+ ".txt": "text/plain",
385
+ ".xml": "application/xml",
386
+ ".webmanifest": "application/manifest+json",
387
+ ".map": "application/json"
388
+ };
391
389
  function getETag(stat) {
392
390
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
393
391
  }
394
392
  async function sendFile(filePath, req, res, status = 200) {
395
393
  const ext = path.extname(filePath).toLowerCase();
396
- const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
397
394
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
398
395
  let stat;
399
396
  try {
@@ -410,7 +407,7 @@ async function sendFile(filePath, req, res, status = 200) {
410
407
  return;
411
408
  }
412
409
  res.writeHead(status, {
413
- "Content-Type": mimeType,
410
+ "Content-Type": MIME_TYPES[ext] ?? "application/octet-stream",
414
411
  "Content-Length": stat.size,
415
412
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
416
413
  "ETag": etag,
@@ -425,88 +422,39 @@ async function sendFile(filePath, req, res, status = 200) {
425
422
  } catch {
426
423
  }
427
424
  }
428
- var MIME_TYPES = {
429
- ".html": "text/html; charset=utf-8",
430
- ".js": "application/javascript",
431
- ".mjs": "application/javascript",
432
- ".css": "text/css",
433
- ".json": "application/json",
434
- ".png": "image/png",
435
- ".jpg": "image/jpeg",
436
- ".jpeg": "image/jpeg",
437
- ".gif": "image/gif",
438
- ".svg": "image/svg+xml",
439
- ".ico": "image/x-icon",
440
- ".webp": "image/webp",
441
- ".avif": "image/avif",
442
- ".woff": "font/woff",
443
- ".woff2": "font/woff2",
444
- ".ttf": "font/ttf",
445
- ".eot": "application/vnd.ms-fontobject",
446
- ".txt": "text/plain",
447
- ".xml": "application/xml",
448
- ".webmanifest": "application/manifest+json",
449
- ".map": "application/json"
450
- };
425
+ async function trySendFile(filePath, req, res, status = 200) {
426
+ try {
427
+ const stat = await fs.promises.stat(filePath);
428
+ if (!stat.isFile()) return false;
429
+ await sendFile(filePath, req, res, status);
430
+ return true;
431
+ } catch {
432
+ return false;
433
+ }
434
+ }
451
435
  async function serveStatic(req, res, next) {
452
436
  const rawPathname = new URL(req.url ?? "/", "http://localhost").pathname;
453
437
  if (toApiPath(rawPathname) !== null) return next();
454
438
  const pathname = stripBase(rawPathname);
455
439
  if (pathname === null) return next();
456
- if (pathname.includes("\0") || pathname.split("/").some((s) => s === "..")) {
457
- return next();
458
- }
440
+ if (pathname.includes("\0") || pathname.split("/").some((s) => s === "..")) return next();
459
441
  const hasExtension = path.extname(pathname).length > 0;
460
442
  if (hasExtension) {
461
443
  const filePath = path.join(config.distDir, pathname);
462
444
  if (filePath.startsWith(config.compiledApiDir)) return next();
463
- try {
464
- const stat = await fs.promises.stat(filePath);
465
- if (stat.isFile()) {
466
- await sendFile(filePath, req, res);
467
- return;
468
- }
469
- } catch {
470
- }
445
+ if (await trySendFile(filePath, req, res)) return;
471
446
  return next();
472
447
  }
473
- const staticFilePath = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
474
- try {
475
- const stat = await fs.promises.stat(staticFilePath);
476
- if (stat.isFile()) {
477
- await sendFile(staticFilePath, req, res);
478
- return;
479
- }
480
- } catch {
481
- }
448
+ const staticIndex = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
449
+ if (await trySendFile(staticIndex, req, res)) return;
482
450
  const matchingShell = findMatchingShellRoute(pathname);
483
451
  if (matchingShell) {
484
- const shellPath = path.join(config.distDir, matchingShell, "index.html");
485
- try {
486
- const stat = await fs.promises.stat(shellPath);
487
- if (stat.isFile()) {
488
- await sendFile(shellPath, req, res);
489
- return;
490
- }
491
- } catch {
492
- }
493
- }
494
- const notFoundPath = path.join(config.distDir, "404.html");
495
- try {
496
- const stat = await fs.promises.stat(notFoundPath);
497
- if (stat.isFile()) {
498
- await sendFile(notFoundPath, req, res, 404);
499
- return;
500
- }
501
- } catch {
502
- }
503
- const indexPath = path.join(config.distDir, "index.html");
504
- try {
505
- await fs.promises.access(indexPath);
506
- await sendFile(indexPath, req, res);
507
- } catch {
508
- next();
452
+ const shellIndex = path.join(config.distDir, matchingShell, "index.html");
453
+ if (await trySendFile(shellIndex, req, res)) return;
509
454
  }
455
+ if (await trySendFile(path.join(config.distDir, "404.html"), req, res, 404)) return;
456
+ if (await trySendFile(path.join(config.distDir, "index.html"), req, res)) return;
457
+ next();
510
458
  }
511
459
  function compose(middlewares) {
512
460
  return async (req, res) => {
@@ -536,7 +484,6 @@ async function start() {
536
484
  `);
537
485
  process.exit(1);
538
486
  }
539
- await loadApiFetch();
540
487
  getShellRoutes();
541
488
  const port = await findFreePort(config.defaultPort);
542
489
  const handler = compose([
@@ -563,9 +510,7 @@ async function start() {
563
510
  server.headersTimeout = 66e3;
564
511
  server.maxHeadersCount = 2e3;
565
512
  startKeyboardLoop(port);
566
- server.listen(port, "0.0.0.0", () => {
567
- printBanner(port);
568
- });
513
+ server.listen(port, "0.0.0.0", () => printBanner(port));
569
514
  const shutdown = () => {
570
515
  server.close(() => process.exit(0));
571
516
  setTimeout(() => process.exit(1), 1e4).unref();