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