bini-server 2.0.1 → 2.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.
package/dist/cli.js CHANGED
@@ -21,188 +21,170 @@ import os from "os";
21
21
  import net from "net";
22
22
  import crypto from "crypto";
23
23
  import readline from "readline";
24
- import { exec } from "child_process";
24
+ import zlib from "zlib";
25
+ import { spawn } from "child_process";
25
26
  import { pathToFileURL } from "url";
26
27
  import { Readable } from "stream";
27
28
  import { pipeline } from "stream/promises";
28
29
  import { loadEnvFiles, envFilesFor } from "bini-env/node";
30
+ import { toApiPath as runtimeToApiPath } from "bini-router/runtime";
29
31
  function getEnvVar(key, defaultValue) {
30
- const biniKey = `BINI_${key}`;
31
- if (process.env[biniKey] !== void 0) return process.env[biniKey];
32
- const viteKey = `VITE_${key}`;
33
- if (process.env[viteKey] !== void 0) return process.env[viteKey];
34
- if (process.env[key] !== void 0) return process.env[key];
35
- return defaultValue;
32
+ return process.env[`BINI_${key}`] ?? process.env[`VITE_${key}`] ?? process.env[key] ?? defaultValue;
36
33
  }
37
34
  function getEnvVarNumber(key, defaultValue) {
38
- const value = getEnvVar(key);
39
- if (value === void 0) return defaultValue;
40
- const parsed = parseInt(value, 10);
41
- return isNaN(parsed) ? defaultValue : parsed;
35
+ const raw = getEnvVar(key);
36
+ if (raw === void 0) return defaultValue;
37
+ const n = parseInt(raw, 10);
38
+ return isNaN(n) ? defaultValue : n;
39
+ }
40
+ function getBiniFlag(name) {
41
+ const v = process.env[`BINI_${name}`]?.trim().toLowerCase();
42
+ return v === "1" || v === "true" || v === "yes" || v === "on";
42
43
  }
43
44
  function readConfig() {
44
- const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
45
+ const distDir = path.resolve(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
45
46
  const apiDir = path.join(distDir, "api");
46
- const apiEntry = path.join(apiDir, "index.mjs");
47
- const rawBase = (getEnvVar("BASE") ?? "").trim();
48
- const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + rawBase.replace(/^\/+|\/+$/g, "");
47
+ const prefixedBase = process.env.BINI_BASE ?? process.env.VITE_BASE;
48
+ const legacyBase = prefixedBase === void 0 && process.env.BASE !== void 0;
49
+ const rawBase = (prefixedBase ?? process.env.BASE ?? "").trim();
50
+ const base = !rawBase || rawBase === "/" || rawBase === "." || rawBase === "./" ? "" : "/" + trimSlashes(rawBase);
49
51
  return {
50
52
  defaultPort: getEnvVarNumber("PORT", 3e3),
53
+ portExplicit: getEnvVar("PORT") !== void 0,
54
+ host: process.env.BINI_HOST?.trim() || "0.0.0.0",
55
+ trustProxy: getBiniFlag("TRUST_PROXY"),
56
+ compress: getBiniFlag("COMPRESS"),
51
57
  bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
52
58
  handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
53
59
  bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
54
60
  distDir,
55
- compiledApiDir: apiDir + path.sep,
56
61
  apiDir,
57
- apiEntry,
62
+ apiEntry: path.join(apiDir, "index.mjs"),
58
63
  base,
64
+ legacyBase,
59
65
  isProd: process.env.NODE_ENV === "production"
60
66
  };
61
67
  }
62
68
  function refreshConfig() {
63
69
  config = readConfig();
64
70
  }
65
- function resolveApiEntry() {
66
- return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
71
+ function warnTag() {
72
+ return process.stdout.isTTY ? `\x1B[33m[WARN]\x1B[0m` : `[WARN]`;
73
+ }
74
+ function trimSlashes(s) {
75
+ let a = 0;
76
+ let b = s.length;
77
+ while (a < b && s[a] === "/") a++;
78
+ while (b > a && s[b - 1] === "/") b--;
79
+ return s.slice(a, b);
80
+ }
81
+ function stripQuery(s) {
82
+ const q = s.indexOf("?");
83
+ const h = s.indexOf("#");
84
+ const i = q === -1 ? h : h === -1 ? q : Math.min(q, h);
85
+ return i === -1 ? s : s.slice(0, i);
86
+ }
87
+ function getRawPath(url) {
88
+ return stripQuery(url);
67
89
  }
68
90
  function stripBase(pathname) {
69
- const base = config.base;
91
+ const { base } = config;
70
92
  if (!base) return pathname || "/";
71
93
  if (pathname === base || pathname === base + "/") return "/";
72
94
  if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
73
95
  return null;
74
96
  }
75
- function scanShellRoutes() {
76
- const shellRoutes = /* @__PURE__ */ new Set();
77
- const rootDir = config.distDir;
78
- function walkDir(dir, currentPath) {
79
- try {
80
- const entries = fs.readdirSync(dir, { withFileTypes: true });
81
- for (const entry of entries) {
82
- if (!entry.isDirectory()) continue;
83
- if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
84
- const fullPath = path.join(dir, entry.name);
85
- const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
86
- if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
87
- const indexPath = path.join(fullPath, "index.html");
88
- if (fs.existsSync(indexPath)) {
89
- shellRoutes.add(`/${routePath}`);
90
- }
91
- }
92
- walkDir(fullPath, routePath);
93
- }
94
- } catch {
95
- }
96
- }
97
- try {
98
- walkDir(rootDir, "");
99
- } catch {
100
- }
101
- return shellRoutes;
102
- }
103
- function getShellRoutes() {
104
- if (!shellRouteCache) {
105
- shellRouteCache = scanShellRoutes();
106
- }
107
- return shellRouteCache;
108
- }
109
- function findMatchingShellRoute(pathname) {
110
- const shellRoutes = getShellRoutes();
111
- const pathSegments = pathname.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
112
- for (const shellRoute of shellRoutes) {
113
- const shellSegments = shellRoute.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
114
- if (shellSegments.length === 0) continue;
115
- const last = shellSegments[shellSegments.length - 1];
116
- const isRequiredCatchAll = last.startsWith("[...") && !last.startsWith("[[...");
117
- const isOptionalCatchAll = last.startsWith("[[...");
118
- const isCatchAll = isRequiredCatchAll || isOptionalCatchAll;
119
- if (isCatchAll) {
120
- const prefix = shellSegments.slice(0, -1);
121
- if (pathSegments.length < prefix.length) continue;
122
- if (isRequiredCatchAll && pathSegments.length === prefix.length) continue;
123
- let matches2 = true;
124
- for (let i = 0; i < prefix.length; i++) {
125
- const seg = prefix[i];
126
- if (seg.startsWith("[") && seg.endsWith("]")) continue;
127
- if (seg !== pathSegments[i]) {
128
- matches2 = false;
129
- break;
130
- }
131
- }
132
- if (matches2) return shellRoute;
133
- continue;
134
- }
135
- if (shellSegments.length !== pathSegments.length) continue;
136
- let matches = true;
137
- for (let i = 0; i < shellSegments.length; i++) {
138
- const seg = shellSegments[i];
139
- if (seg.startsWith("[") && seg.endsWith("]")) continue;
140
- if (seg !== pathSegments[i]) {
141
- matches = false;
142
- break;
143
- }
144
- }
145
- if (matches) return shellRoute;
146
- }
147
- return null;
97
+ function toApiPath(pathname) {
98
+ return runtimeToApiPath(pathname, config.base);
99
+ }
100
+ function resolveInDist(pathname) {
101
+ if (pathname.includes("\0") || pathname.includes("\\")) return null;
102
+ if (pathname.split("/").some((s) => s === "..")) return null;
103
+ const root = path.resolve(config.distDir);
104
+ const abs = path.resolve(root, "." + pathname);
105
+ if (abs !== root && !abs.startsWith(root + path.sep)) return null;
106
+ return abs;
107
+ }
108
+ function isDenied(pathname) {
109
+ const segs = pathname.split("/").filter(Boolean);
110
+ const first = segs[0]?.toLowerCase();
111
+ if (first === "api") return true;
112
+ return segs.some((s) => s.startsWith(".") && s !== ".well-known");
113
+ }
114
+ function isVirtualInterface(name) {
115
+ const n = name.toLowerCase();
116
+ return SKIP_IFACE_PREFIXES.some((p) => n.startsWith(p)) || SKIP_IFACE_PARTS.some((p) => n.includes(p));
148
117
  }
149
118
  function getNetworkIp() {
150
119
  const ifaces = os.networkInterfaces();
151
- const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
120
+ const candidates = [];
152
121
  for (const name in ifaces) {
153
- if (SKIP.test(name)) continue;
122
+ if (isVirtualInterface(name)) continue;
154
123
  for (const iface of ifaces[name] ?? []) {
155
124
  if (iface.internal || iface.family !== "IPv4") continue;
156
125
  const [a, b] = iface.address.split(".").map(Number);
157
126
  if (a === 169 && b === 254) continue;
158
127
  const isPrivate = a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
159
128
  if (isPrivate) return iface.address;
129
+ candidates.push(iface.address);
160
130
  }
161
131
  }
162
- for (const name in ifaces) {
163
- if (SKIP.test(name)) continue;
164
- for (const iface of ifaces[name] ?? []) {
165
- if (!iface.internal && iface.family === "IPv4") return iface.address;
166
- }
167
- }
168
- return null;
132
+ return candidates[0] ?? null;
169
133
  }
170
134
  function printBanner(port) {
171
135
  const envFiles2 = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
172
- const networkIp = getNetworkIp();
136
+ const { host } = config;
137
+ const wildcard = host === "0.0.0.0" || host === "::";
138
+ const loopback = host === "127.0.0.1" || host === "::1" || host === "localhost";
139
+ const networkIp = wildcard ? getNetworkIp() : null;
140
+ const localHost = wildcard || loopback ? "localhost" : host.includes(":") ? `[${host}]` : host;
173
141
  console.log(`
174
142
  ${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
175
143
  if (envFiles2.length > 0) {
176
144
  const rel = envFiles2.map((f) => path.relative(process.cwd(), f));
177
145
  console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
178
146
  }
179
- console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
147
+ console.log(
148
+ ` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://${localHost}:${port}${config.base}/${C.RESET}`
149
+ );
180
150
  if (networkIp) {
181
- console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
151
+ console.log(
152
+ ` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}${config.base}/${C.RESET}`
153
+ );
182
154
  }
183
155
  if (config.base) {
184
156
  console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
185
157
  }
186
- console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
158
+ console.log(
159
+ ` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`
160
+ );
187
161
  console.log("");
188
162
  }
189
- async function isPortFree(port) {
163
+ function isPortFree(port, host) {
190
164
  return new Promise((resolve) => {
191
165
  const server = net.createServer();
192
166
  server.once("error", () => resolve(false));
193
167
  server.once("listening", () => server.close(() => resolve(true)));
194
- server.listen(port, "0.0.0.0");
168
+ server.listen(port, host);
195
169
  });
196
170
  }
197
- async function findFreePort(start3) {
171
+ async function findFreePort(start3, host) {
198
172
  for (let port = start3; port < start3 + 100; port++) {
199
- if (await isPortFree(port)) {
200
- return port;
201
- }
173
+ if (await isPortFree(port, host)) return port;
202
174
  console.log(`Port ${port} is in use, trying another one...`);
203
175
  }
204
176
  throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
205
177
  }
178
+ function openInBrowser(url) {
179
+ const [bin, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
180
+ try {
181
+ const child = spawn(bin, args, { stdio: "ignore", detached: true, windowsHide: true });
182
+ child.on("error", () => {
183
+ });
184
+ child.unref();
185
+ } catch {
186
+ }
187
+ }
206
188
  function startKeyboardLoop(port) {
207
189
  if (!process.stdin.isTTY) return;
208
190
  const rl = readline.createInterface({ input: process.stdin });
@@ -211,16 +193,15 @@ function startKeyboardLoop(port) {
211
193
  case "h":
212
194
  console.log("");
213
195
  console.log(" Shortcuts");
214
- console.log(` ${C.DIM}press ${C.RESET}o + enter${C.RESET} to open in browser${C.RESET}`);
215
- console.log(` ${C.DIM}press ${C.RESET}q + enter${C.RESET} to quit${C.RESET}`);
196
+ console.log(
197
+ ` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`
198
+ );
199
+ console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
216
200
  console.log("");
217
201
  break;
218
- case "o": {
219
- const url = `http://localhost:${port}${config.base || ""}/`;
220
- const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
221
- exec(cmd);
202
+ case "o":
203
+ openInBrowser(`http://localhost:${port}${config.base}/`);
222
204
  break;
223
- }
224
205
  case "q":
225
206
  process.exit(0);
226
207
  }
@@ -231,28 +212,41 @@ function readBody(req) {
231
212
  return new Promise((resolve, reject) => {
232
213
  const chunks = [];
233
214
  let size = 0;
234
- const timer = setTimeout(() => {
235
- req.destroy();
236
- reject(new Error("Request body timeout"));
237
- }, config.bodyTimeout);
238
- req.on("data", (chunk) => {
215
+ let settled = false;
216
+ let timer;
217
+ const stop = () => {
218
+ if (settled) return false;
219
+ settled = true;
220
+ clearTimeout(timer);
221
+ req.off("data", onData);
222
+ req.off("end", onEnd);
223
+ return true;
224
+ };
225
+ const onData = (chunk) => {
239
226
  size += chunk.byteLength;
240
227
  if (size > config.bodySizeLimit) {
241
- clearTimeout(timer);
242
- req.destroy();
243
- reject(new Error("Request body too large"));
228
+ if (stop()) {
229
+ req.pause();
230
+ reject(new HttpError(413, "Request body too large"));
231
+ }
244
232
  return;
245
233
  }
246
234
  chunks.push(chunk);
247
- });
248
- req.on("end", () => {
249
- clearTimeout(timer);
250
- resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
251
- });
235
+ };
236
+ const onEnd = () => {
237
+ if (stop()) resolve(chunks.length > 0 ? Buffer.concat(chunks) : void 0);
238
+ };
252
239
  req.on("error", (err) => {
253
- clearTimeout(timer);
254
- reject(err);
240
+ if (stop()) reject(err);
255
241
  });
242
+ timer = setTimeout(() => {
243
+ if (stop()) {
244
+ req.pause();
245
+ reject(new HttpError(408, "Request body timeout"));
246
+ }
247
+ }, config.bodyTimeout);
248
+ req.on("data", onData);
249
+ req.on("end", onEnd);
256
250
  });
257
251
  }
258
252
  function normalizeHeaders(raw) {
@@ -263,68 +257,81 @@ function normalizeHeaders(raw) {
263
257
  }
264
258
  return out;
265
259
  }
266
- function toApiPath(pathname) {
267
- let p = pathname;
268
- const base = config.base;
269
- if (base) {
270
- if (p === base || p.startsWith(base + "/")) p = p.slice(base.length) || "/";
271
- else return null;
272
- }
273
- if (p === "/api") return "/";
274
- if (p.startsWith("/api/")) return p.slice(4);
275
- return null;
260
+ function firstHeaderValue(v) {
261
+ const s = Array.isArray(v) ? v[0] : v;
262
+ return s?.split(",")[0].trim().toLowerCase() || void 0;
276
263
  }
277
- function isApiRequest(url) {
278
- if (!url) return false;
279
- try {
280
- return toApiPath(new URL(url, "http://localhost").pathname) !== null;
281
- } catch {
282
- return false;
264
+ function requestOrigin(req) {
265
+ let proto = "http";
266
+ let host = req.headers.host ?? "localhost";
267
+ if (config.trustProxy) {
268
+ const fp = firstHeaderValue(req.headers["x-forwarded-proto"]);
269
+ if (fp === "http" || fp === "https") proto = fp;
270
+ const fh = firstHeaderValue(req.headers["x-forwarded-host"]);
271
+ if (fh && allHostChars(fh)) host = fh;
283
272
  }
273
+ return `${proto}://${host}`;
284
274
  }
285
- async function loadApiFetch() {
275
+ function allHostChars(s) {
276
+ for (let i = 0; i < s.length; i++) {
277
+ const c = s.charCodeAt(i);
278
+ const ok = c >= 48 && c <= 57 || // 0-9
279
+ c >= 97 && c <= 122 || // a-z
280
+ c === 46 || // .
281
+ c === 45 || // -
282
+ c === 58 || // :
283
+ c === 91 || // [
284
+ c === 93;
285
+ if (!ok) return false;
286
+ }
287
+ return s.length > 0;
288
+ }
289
+ async function toWebRequest(req, url) {
290
+ const method = (req.method ?? "GET").toUpperCase();
291
+ const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
292
+ return new Request(url, {
293
+ method,
294
+ headers: normalizeHeaders(req.headers),
295
+ body: body ? new Uint8Array(body) : null
296
+ });
297
+ }
298
+ async function ensureApiFetch() {
286
299
  if (apiFetch) return apiFetch;
287
300
  if (apiLoadPromise) return apiLoadPromise;
301
+ const entry = config.apiEntry;
288
302
  apiLoadPromise = (async () => {
289
303
  try {
290
- const entry = resolveApiEntry();
291
- if (!entry) throw new Error(`${config.apiEntry} not found`);
292
304
  const mod = await import(pathToFileURL(entry).href);
293
305
  if (typeof mod.fetch !== "function") {
294
- throw new Error(`${entry} does not export fetch()`);
306
+ throw new Error(`${path.relative(process.cwd(), entry)} does not export a fetch function`);
295
307
  }
296
308
  apiFetch = mod.fetch;
297
- } catch (err) {
298
- const msg = err instanceof Error ? err.message : String(err);
299
- console.warn(
300
- `
301
- ${C.YELLOW}\u26A0${C.RESET} No compiled API in ${config.apiDir}.
302
- ${C.DIM}${msg}${C.RESET}
303
- API requests will return 404. Run ${C.CYAN}npm run build${C.RESET} to compile it.
304
- `
305
- );
306
- apiFetch = async () => new Response(
307
- JSON.stringify({ error: "No API routes compiled" }),
308
- { status: 404, headers: { "content-type": "application/json" } }
309
- );
309
+ apiLoadError = null;
310
+ return apiFetch;
311
+ } catch (e) {
312
+ apiLoadError = e;
313
+ apiLoadPromise = null;
314
+ return null;
310
315
  }
311
- return apiFetch;
312
316
  })();
313
317
  return apiLoadPromise;
314
318
  }
315
- async function toWebRequest(req, host) {
316
- const method = (req.method ?? "GET").toUpperCase();
317
- const body = method !== "GET" && method !== "HEAD" ? await readBody(req) : void 0;
318
- return new Request(`http://${host}${req.url ?? "/"}`, {
319
- method,
320
- headers: normalizeHeaders(req.headers),
321
- body: body ? new Uint8Array(body) : null
322
- });
323
- }
324
319
  function sendJson(res, status, body, extra = {}) {
325
- res.writeHead(status, { "content-type": "application/json", ...extra });
320
+ res.writeHead(status, {
321
+ "content-type": "application/json; charset=utf-8",
322
+ "x-content-type-options": "nosniff",
323
+ ...extra
324
+ });
326
325
  res.end(JSON.stringify(body));
327
326
  }
327
+ function sendText(res, status, text, extra = {}) {
328
+ res.writeHead(status, {
329
+ "content-type": "text/plain; charset=utf-8",
330
+ "x-content-type-options": "nosniff",
331
+ ...extra
332
+ });
333
+ res.end(text);
334
+ }
328
335
  async function sendWebResponse(res, webRes, method) {
329
336
  const headers = {};
330
337
  webRes.headers.forEach((v, k) => {
@@ -356,21 +363,35 @@ function publicErrorMessage(e) {
356
363
  }
357
364
  async function handleApiRequest(req, res) {
358
365
  const method = (req.method ?? "GET").toUpperCase();
359
- const host = req.headers.host ?? "localhost";
366
+ const fetchFn = await ensureApiFetch();
367
+ if (!fetchFn) {
368
+ const pathLabel = (req.url ?? "/api").split("?")[0] || "/api";
369
+ console.error(`
370
+ ${warnTag()} failed to load handler for ${pathLabel}:`, apiLoadError);
371
+ return sendJson(res, 503, {
372
+ error: "failed to load handler",
373
+ path: pathLabel,
374
+ detail: apiLoadError instanceof Error ? apiLoadError.message : String(apiLoadError ?? "API bundle not found")
375
+ });
376
+ }
360
377
  let parsedUrl;
361
378
  try {
362
- parsedUrl = new URL(`http://${host}${req.url ?? "/"}`);
379
+ parsedUrl = new URL(`${requestOrigin(req)}${req.url ?? "/"}`);
363
380
  } catch {
364
381
  return sendJson(res, 400, { error: "Bad request URL" });
365
382
  }
366
- if (toApiPath(parsedUrl.pathname) === null) return sendJson(res, 404, { error: "Not Found" });
367
- const fetchApi = await loadApiFetch();
383
+ const declared = Number(req.headers["content-length"]);
384
+ if (Number.isFinite(declared) && declared > config.bodySizeLimit) {
385
+ return sendJson(res, 413, { error: "Request body too large" }, { connection: "close" });
386
+ }
368
387
  let webReq;
369
388
  try {
370
- webReq = await toWebRequest(req, host);
389
+ webReq = await toWebRequest(req, parsedUrl.href);
371
390
  } catch (e) {
372
- const message = e?.message ?? "Bad request";
373
- return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
391
+ if (e instanceof HttpError) {
392
+ return sendJson(res, e.status, { error: e.message }, { connection: "close" });
393
+ }
394
+ return sendJson(res, 400, { error: e?.message ?? "Bad request" });
374
395
  }
375
396
  const ctx = {
376
397
  waitUntil(p) {
@@ -380,12 +401,16 @@ async function handleApiRequest(req, res) {
380
401
  };
381
402
  try {
382
403
  const webRes = await withTimeout(
383
- fetchApi(webReq, process.env, ctx),
404
+ fetchFn(webReq, process.env, ctx),
384
405
  config.handlerTimeout
385
406
  );
386
407
  await sendWebResponse(res, webRes, method);
387
408
  } catch (e) {
388
- console.error("[bini-api] handler error:", e);
409
+ console.error(
410
+ `
411
+ ${warnTag()} failed to handle ${method} ${parsedUrl.pathname}:`,
412
+ e
413
+ );
389
414
  if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
390
415
  else res.end();
391
416
  }
@@ -393,99 +418,152 @@ async function handleApiRequest(req, res) {
393
418
  function getETag(stat) {
394
419
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
395
420
  }
421
+ function isHashedAsset(relPath) {
422
+ const HASH_LEN = 8;
423
+ if (!relPath.startsWith("assets/")) return false;
424
+ const stem = path.posix.basename(relPath, path.posix.extname(relPath));
425
+ if (stem.length <= HASH_LEN + 1) return false;
426
+ const sep = stem[stem.length - HASH_LEN - 1];
427
+ if (sep !== "-" && sep !== ".") return false;
428
+ let hasDigit = false;
429
+ for (const ch of stem.slice(-HASH_LEN)) {
430
+ const digit = ch >= "0" && ch <= "9";
431
+ const ok = digit || ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_" || ch === "-";
432
+ if (!ok) return false;
433
+ if (digit) hasDigit = true;
434
+ }
435
+ return hasDigit;
436
+ }
437
+ function etagMatches(header, etag) {
438
+ if (!header) return false;
439
+ if (header.trim() === "*") return true;
440
+ const strip = (t) => {
441
+ const s = t.trim();
442
+ return s.startsWith("W/") ? s.slice(2) : s;
443
+ };
444
+ const mine = strip(etag);
445
+ return header.split(",").some((t) => strip(t) === mine);
446
+ }
447
+ function pickEncoding(req) {
448
+ const header = String(req.headers["accept-encoding"] ?? "");
449
+ const accepted = /* @__PURE__ */ new Map();
450
+ for (const part of header.split(",")) {
451
+ const [name, ...params] = part.trim().split(";");
452
+ if (!name) continue;
453
+ const qp = params.map((s) => s.trim()).find((s) => s.startsWith("q="));
454
+ const q = qp ? parseFloat(qp.slice(2)) : 1;
455
+ accepted.set(name.trim().toLowerCase(), isNaN(q) ? 1 : q);
456
+ }
457
+ if ((accepted.get("br") ?? 0) > 0) return "br";
458
+ if ((accepted.get("gzip") ?? 0) > 0) return "gzip";
459
+ return null;
460
+ }
396
461
  async function sendFile(filePath, req, res, status = 200) {
397
462
  const ext = path.extname(filePath).toLowerCase();
398
- const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
399
- const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
400
463
  let stat;
401
464
  try {
402
465
  stat = await fs.promises.stat(filePath);
403
466
  } catch {
404
- res.writeHead(404);
405
- res.end("Not found");
467
+ sendText(res, 404, "Not found");
406
468
  return;
407
469
  }
408
- const etag = getETag(stat);
409
- if (status === 200 && req.headers["if-none-match"] === etag) {
410
- res.writeHead(304);
470
+ const rel = path.relative(config.distDir, filePath).split(path.sep).join("/");
471
+ const compressible = config.compress && COMPRESSIBLE_EXTS.has(ext);
472
+ const encoding = compressible && stat.size >= 1024 ? pickEncoding(req) : null;
473
+ const etag = `"${getETag(stat)}${encoding ? `-${encoding}` : ""}"`;
474
+ const validators = {
475
+ "Cache-Control": isHashedAsset(rel) ? "public, max-age=31536000, immutable" : "no-cache",
476
+ ETag: etag,
477
+ "X-Content-Type-Options": "nosniff"
478
+ };
479
+ if (compressible) validators["Vary"] = "Accept-Encoding";
480
+ if (status === 200 && etagMatches(req.headers["if-none-match"], etag)) {
481
+ res.writeHead(304, validators);
411
482
  res.end();
412
483
  return;
413
484
  }
414
- res.writeHead(status, {
415
- "Content-Type": mimeType,
416
- "Content-Length": stat.size,
417
- "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
418
- "ETag": etag,
419
- "X-Powered-By": "Bini.js"
420
- });
485
+ const headers = {
486
+ ...validators,
487
+ "Content-Type": MIME_TYPES[ext] ?? "application/octet-stream"
488
+ };
489
+ if (encoding) headers["Content-Encoding"] = encoding;
490
+ else headers["Content-Length"] = stat.size;
491
+ res.writeHead(status, headers);
421
492
  if (req.method === "HEAD") {
422
493
  res.end();
423
494
  return;
424
495
  }
496
+ const source = createReadStream(filePath);
425
497
  try {
426
- await pipeline(createReadStream(filePath), res);
498
+ if (encoding === "br") {
499
+ await pipeline(
500
+ source,
501
+ zlib.createBrotliCompress({
502
+ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 }
503
+ }),
504
+ res
505
+ );
506
+ } else if (encoding === "gzip") {
507
+ await pipeline(source, zlib.createGzip(), res);
508
+ } else {
509
+ await pipeline(source, res);
510
+ }
427
511
  } catch {
428
512
  }
429
513
  }
430
- async function serveStatic(req, res, next) {
431
- const rawPathname = new URL(req.url ?? "/", "http://localhost").pathname;
432
- if (toApiPath(rawPathname) !== null) return next();
433
- const pathname = stripBase(rawPathname);
434
- if (pathname === null) return next();
435
- if (pathname.includes("\0") || pathname.split("/").some((s) => s === "..")) {
436
- return next();
437
- }
438
- const hasExtension = path.extname(pathname).length > 0;
439
- if (hasExtension) {
440
- const filePath = path.join(config.distDir, pathname);
441
- if (filePath.startsWith(config.compiledApiDir)) return next();
442
- try {
443
- const stat = await fs.promises.stat(filePath);
444
- if (stat.isFile()) {
445
- await sendFile(filePath, req, res);
446
- return;
447
- }
448
- } catch {
449
- }
450
- return next();
451
- }
452
- const staticFilePath = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
514
+ async function trySendFile(filePath, req, res, status = 200) {
453
515
  try {
454
- const stat = await fs.promises.stat(staticFilePath);
455
- if (stat.isFile()) {
456
- await sendFile(staticFilePath, req, res);
457
- return;
458
- }
516
+ const stat = await fs.promises.stat(filePath);
517
+ if (!stat.isFile()) return false;
518
+ await sendFile(filePath, req, res, status);
519
+ return true;
459
520
  } catch {
521
+ return false;
460
522
  }
461
- const matchingShell = findMatchingShellRoute(pathname);
462
- if (matchingShell) {
463
- const shellPath = path.join(config.distDir, matchingShell, "index.html");
464
- try {
465
- const stat = await fs.promises.stat(shellPath);
466
- if (stat.isFile()) {
467
- await sendFile(shellPath, req, res);
468
- return;
469
- }
470
- } catch {
471
- }
472
- }
473
- const notFoundPath = path.join(config.distDir, "404.html");
523
+ }
524
+ async function serveStatic(req, res, next) {
525
+ const rawPath = getRawPath(req.url ?? "/");
526
+ const stripped = stripBase(rawPath);
527
+ if (stripped === null) return next();
528
+ let pathname;
474
529
  try {
475
- const stat = await fs.promises.stat(notFoundPath);
476
- if (stat.isFile()) {
477
- await sendFile(notFoundPath, req, res, 404);
478
- return;
479
- }
530
+ pathname = decodeURIComponent(stripped);
480
531
  } catch {
532
+ return sendText(res, 400, "Bad request");
481
533
  }
482
- const indexPath = path.join(config.distDir, "index.html");
534
+ const abs = resolveInDist(pathname);
535
+ if (abs === null) return sendText(res, 400, "Bad request");
536
+ if (isDenied(pathname)) return sendText(res, 404, "Not found");
537
+ const ext = path.extname(pathname).toLowerCase();
538
+ let stat = null;
483
539
  try {
484
- await fs.promises.access(indexPath);
485
- await sendFile(indexPath, req, res);
540
+ stat = await fs.promises.stat(abs);
486
541
  } catch {
487
- next();
488
542
  }
543
+ if (stat?.isFile()) {
544
+ if (await trySendFile(abs, req, res)) return;
545
+ } else if (stat?.isDirectory()) {
546
+ if (await trySendFile(path.join(abs, "index.html"), req, res)) return;
547
+ }
548
+ if (!ext && pathname !== "/" && await trySendFile(`${abs.replace(/[\\/]+$/, "")}.html`, req, res)) return;
549
+ if (ASSET_EXTS.has(ext)) return sendText(res, 404, "Not found");
550
+ if (await trySendFile(path.join(config.distDir, "200.html"), req, res)) return;
551
+ if (await trySendFile(path.join(config.distDir, "404.html"), req, res, 404)) return;
552
+ if (await trySendFile(path.join(config.distDir, "index.html"), req, res)) return;
553
+ return sendText(res, 404, "Not found");
554
+ }
555
+ async function gateway(req, res, next) {
556
+ const method = (req.method ?? "GET").toUpperCase();
557
+ const rawPath = getRawPath(req.url ?? "/");
558
+ if (toApiPath(rawPath) !== null) return handleApiRequest(req, res);
559
+ if (method !== "GET" && method !== "HEAD") {
560
+ return sendText(res, 405, "Method Not Allowed", { Allow: "GET, HEAD" });
561
+ }
562
+ if (rawPath === "/__health" || stripBase(rawPath) === "/__health") {
563
+ return sendText(res, 200, "ok", { "Cache-Control": "no-store" });
564
+ }
565
+ if (!rawPath.startsWith("/")) return sendText(res, 400, "Bad request");
566
+ next();
489
567
  }
490
568
  function compose(middlewares) {
491
569
  return async (req, res) => {
@@ -508,29 +586,39 @@ function compose(middlewares) {
508
586
  async function start() {
509
587
  loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
510
588
  refreshConfig();
589
+ if (config.legacyBase) {
590
+ console.warn(
591
+ `
592
+ ${warnTag()} reading base from the unprefixed BASE variable. Other tools set it too; use BINI_BASE instead.`
593
+ );
594
+ }
511
595
  if (!fs.existsSync(config.distDir)) {
512
- console.error(`
596
+ console.error(
597
+ `
513
598
  ${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
514
599
  Run ${C.CYAN}npm run build${C.RESET} first.
515
- `);
600
+ `
601
+ );
516
602
  process.exit(1);
517
603
  }
518
- await loadApiFetch();
519
- getShellRoutes();
520
- const port = await findFreePort(config.defaultPort);
604
+ let port;
605
+ if (config.portExplicit) {
606
+ port = config.defaultPort;
607
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
608
+ console.error(`
609
+ ${C.RED}\u2717${C.RESET} invalid port: ${getEnvVar("PORT")}
610
+ `);
611
+ process.exit(1);
612
+ }
613
+ } else {
614
+ port = await findFreePort(config.defaultPort, config.host);
615
+ }
521
616
  const handler = compose([
522
- async (req, res, next) => {
523
- if (!isApiRequest(req.url)) return next();
524
- await handleApiRequest(req, res);
525
- },
617
+ gateway,
526
618
  serveStatic,
527
- (_req, res) => {
528
- res.writeHead(404, { "Content-Type": "text/plain" });
529
- res.end("Not found");
530
- }
619
+ (_req, res) => sendText(res, 404, "Not found")
531
620
  ]);
532
621
  const server = http.createServer((req, res) => {
533
- res.setHeader("Connection", "keep-alive");
534
622
  handler(req, res).catch(() => {
535
623
  if (!res.headersSent) {
536
624
  res.writeHead(500);
@@ -541,21 +629,57 @@ async function start() {
541
629
  server.keepAliveTimeout = 65e3;
542
630
  server.headersTimeout = 66e3;
543
631
  server.maxHeadersCount = 2e3;
544
- startKeyboardLoop(port);
545
- server.listen(port, "0.0.0.0", () => {
546
- printBanner(port);
632
+ server.once("error", (err) => {
633
+ if (err.code === "EADDRINUSE") {
634
+ console.error(
635
+ `
636
+ ${C.RED}\u2717${C.RESET} port ${port} is already in use on ${config.host}.
637
+ `
638
+ );
639
+ } else {
640
+ console.error(`
641
+ ${C.RED}\u2717${C.RESET} server error:`, err);
642
+ }
643
+ process.exit(1);
547
644
  });
645
+ startKeyboardLoop(port);
646
+ server.listen(port, config.host, () => printBanner(port));
647
+ let shuttingDown = false;
548
648
  const shutdown = () => {
649
+ if (shuttingDown) process.exit(1);
650
+ shuttingDown = true;
549
651
  server.close(() => process.exit(0));
550
- setTimeout(() => process.exit(1), 1e4).unref();
652
+ server.closeIdleConnections();
653
+ setInterval(() => server.closeIdleConnections(), 1e3).unref();
654
+ setTimeout(() => {
655
+ server.closeAllConnections();
656
+ setTimeout(() => process.exit(1), 1e3).unref();
657
+ }, 1e4).unref();
551
658
  };
552
659
  process.on("SIGTERM", shutdown);
553
660
  process.on("SIGINT", shutdown);
661
+ process.on("unhandledRejection", (reason) => {
662
+ console.error(`
663
+ ${warnTag()} unhandledRejection:`, reason);
664
+ process.exit(1);
665
+ });
666
+ process.on("uncaughtException", (err) => {
667
+ console.error(`
668
+ ${warnTag()} uncaughtException:`, err);
669
+ process.exit(1);
670
+ });
554
671
  }
555
- var config, C, shellRouteCache, apiFetch, apiLoadPromise, MIME_TYPES;
672
+ var HttpError, config, C, SKIP_IFACE_PREFIXES, SKIP_IFACE_PARTS, apiFetch, apiLoadPromise, apiLoadError, MIME_TYPES, ASSET_EXTS, COMPRESSIBLE_EXTS;
556
673
  var init_src = __esm({
557
674
  "src/index.ts"() {
558
675
  "use strict";
676
+ HttpError = class extends Error {
677
+ status;
678
+ constructor(status, message) {
679
+ super(message);
680
+ this.status = status;
681
+ }
682
+ };
559
683
  config = readConfig();
560
684
  C = {
561
685
  CYAN: "\x1B[36m",
@@ -563,35 +687,82 @@ var init_src = __esm({
563
687
  GREEN: "\x1B[32m",
564
688
  RED: "\x1B[31m",
565
689
  YELLOW: "\x1B[33m",
566
- BOLD: "\x1B[1m",
567
690
  DIM: "\x1B[2m"
568
691
  };
569
- shellRouteCache = null;
692
+ SKIP_IFACE_PREFIXES = ["veth", "br-", "utun", "tun", "tap"];
693
+ SKIP_IFACE_PARTS = ["docker", "vmnet", "vbox"];
570
694
  apiFetch = null;
571
695
  apiLoadPromise = null;
696
+ apiLoadError = null;
572
697
  MIME_TYPES = {
573
698
  ".html": "text/html; charset=utf-8",
574
- ".js": "application/javascript",
575
- ".mjs": "application/javascript",
576
- ".css": "text/css",
577
- ".json": "application/json",
699
+ ".js": "text/javascript; charset=utf-8",
700
+ ".mjs": "text/javascript; charset=utf-8",
701
+ ".css": "text/css; charset=utf-8",
702
+ ".json": "application/json; charset=utf-8",
578
703
  ".png": "image/png",
579
704
  ".jpg": "image/jpeg",
580
705
  ".jpeg": "image/jpeg",
581
706
  ".gif": "image/gif",
582
- ".svg": "image/svg+xml",
707
+ ".svg": "image/svg+xml; charset=utf-8",
583
708
  ".ico": "image/x-icon",
584
709
  ".webp": "image/webp",
585
710
  ".avif": "image/avif",
586
711
  ".woff": "font/woff",
587
712
  ".woff2": "font/woff2",
588
713
  ".ttf": "font/ttf",
714
+ ".otf": "font/otf",
589
715
  ".eot": "application/vnd.ms-fontobject",
590
- ".txt": "text/plain",
591
- ".xml": "application/xml",
592
- ".webmanifest": "application/manifest+json",
593
- ".map": "application/json"
716
+ ".txt": "text/plain; charset=utf-8",
717
+ ".xml": "application/xml; charset=utf-8",
718
+ ".webmanifest": "application/manifest+json; charset=utf-8",
719
+ ".map": "application/json; charset=utf-8",
720
+ ".pdf": "application/pdf",
721
+ ".wasm": "application/wasm",
722
+ ".mp4": "video/mp4",
723
+ ".webm": "video/webm",
724
+ ".mp3": "audio/mpeg"
594
725
  };
726
+ ASSET_EXTS = /* @__PURE__ */ new Set([
727
+ ".js",
728
+ ".mjs",
729
+ ".css",
730
+ ".map",
731
+ ".json",
732
+ ".txt",
733
+ ".xml",
734
+ ".webmanifest",
735
+ ".png",
736
+ ".jpg",
737
+ ".jpeg",
738
+ ".gif",
739
+ ".svg",
740
+ ".ico",
741
+ ".webp",
742
+ ".avif",
743
+ ".woff",
744
+ ".woff2",
745
+ ".ttf",
746
+ ".otf",
747
+ ".eot",
748
+ ".pdf",
749
+ ".wasm",
750
+ ".mp4",
751
+ ".webm",
752
+ ".mp3"
753
+ ]);
754
+ COMPRESSIBLE_EXTS = /* @__PURE__ */ new Set([
755
+ ".html",
756
+ ".js",
757
+ ".mjs",
758
+ ".css",
759
+ ".json",
760
+ ".svg",
761
+ ".txt",
762
+ ".xml",
763
+ ".webmanifest",
764
+ ".map"
765
+ ]);
595
766
  }
596
767
  });
597
768