bini-server 2.0.0 → 2.0.1

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
@@ -1,6 +1,6 @@
1
1
  // src/index.ts
2
2
  import http from "http";
3
- import fs from "fs";
3
+ import fs, { createReadStream } from "fs";
4
4
  import path from "path";
5
5
  import os from "os";
6
6
  import net from "net";
@@ -8,17 +8,9 @@ import crypto from "crypto";
8
8
  import readline from "readline";
9
9
  import { exec } from "child_process";
10
10
  import { pathToFileURL } from "url";
11
+ import { Readable } from "stream";
11
12
  import { pipeline } from "stream/promises";
12
- import { createReadStream } from "fs";
13
- function detectEnvFiles(root) {
14
- const nodeEnv = process.env.NODE_ENV ?? "production";
15
- return [
16
- ".env.local",
17
- `.env.${nodeEnv}.local`,
18
- `.env.${nodeEnv}`,
19
- ".env"
20
- ].filter((f) => fs.existsSync(path.join(root, f)));
21
- }
13
+ import { loadEnvFiles, envFilesFor } from "bini-env/node";
22
14
  function getEnvVar(key, defaultValue) {
23
15
  const biniKey = `BINI_${key}`;
24
16
  if (process.env[biniKey] !== void 0) return process.env[biniKey];
@@ -27,24 +19,38 @@ function getEnvVar(key, defaultValue) {
27
19
  if (process.env[key] !== void 0) return process.env[key];
28
20
  return defaultValue;
29
21
  }
30
- function getEnvVarBoolean(key, defaultValue) {
31
- const value = getEnvVar(key);
32
- if (value === void 0) return defaultValue;
33
- return value !== "false" && value !== "0" && value !== "";
34
- }
35
22
  function getEnvVarNumber(key, defaultValue) {
36
23
  const value = getEnvVar(key);
37
24
  if (value === void 0) return defaultValue;
38
25
  const parsed = parseInt(value, 10);
39
26
  return isNaN(parsed) ? defaultValue : parsed;
40
27
  }
41
- var DEFAULT_PORT = getEnvVarNumber("PORT", 3e3);
42
- var BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
43
- var HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
44
- var BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
45
- var API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
46
- var DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
47
- var CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
28
+ function readConfig() {
29
+ const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
30
+ 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, "");
34
+ return {
35
+ defaultPort: getEnvVarNumber("PORT", 3e3),
36
+ bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
37
+ handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
38
+ bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
39
+ distDir,
40
+ compiledApiDir: apiDir + path.sep,
41
+ apiDir,
42
+ apiEntry,
43
+ base,
44
+ isProd: process.env.NODE_ENV === "production"
45
+ };
46
+ }
47
+ var config = readConfig();
48
+ function refreshConfig() {
49
+ config = readConfig();
50
+ }
51
+ function resolveApiEntry() {
52
+ return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
53
+ }
48
54
  var C = {
49
55
  CYAN: "\x1B[36m",
50
56
  RESET: "\x1B[0m",
@@ -54,15 +60,22 @@ var C = {
54
60
  BOLD: "\x1B[1m",
55
61
  DIM: "\x1B[2m"
56
62
  };
63
+ function stripBase(pathname) {
64
+ const base = config.base;
65
+ if (!base) return pathname || "/";
66
+ if (pathname === base || pathname === base + "/") return "/";
67
+ if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
68
+ return null;
69
+ }
57
70
  function scanShellRoutes() {
58
71
  const shellRoutes = /* @__PURE__ */ new Set();
59
- const rootDir = DIST_DIR;
72
+ const rootDir = config.distDir;
60
73
  function walkDir(dir, currentPath) {
61
74
  try {
62
75
  const entries = fs.readdirSync(dir, { withFileTypes: true });
63
76
  for (const entry of entries) {
64
77
  if (!entry.isDirectory()) continue;
65
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
78
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "api") continue;
66
79
  const fullPath = path.join(dir, entry.name);
67
80
  const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
68
81
  if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
@@ -91,26 +104,41 @@ function getShellRoutes() {
91
104
  }
92
105
  function findMatchingShellRoute(pathname) {
93
106
  const shellRoutes = getShellRoutes();
94
- const cleanPath = pathname.replace(/^\/|\/$/g, "");
95
- const pathSegments = cleanPath.split("/").filter(Boolean);
107
+ const pathSegments = pathname.replace(/^\/|\/$/g, "").split("/").filter(Boolean);
96
108
  for (const shellRoute of shellRoutes) {
97
- const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
98
- const shellSegments = cleanShell.split("/").filter(Boolean);
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
+ }
99
131
  if (shellSegments.length !== pathSegments.length) continue;
100
132
  let matches = true;
101
133
  for (let i = 0; i < shellSegments.length; i++) {
102
- const segment = shellSegments[i];
103
- if (segment.startsWith("[") && segment.endsWith("]")) {
104
- continue;
105
- }
106
- if (segment !== pathSegments[i]) {
134
+ const seg = shellSegments[i];
135
+ if (seg.startsWith("[") && seg.endsWith("]")) continue;
136
+ if (seg !== pathSegments[i]) {
107
137
  matches = false;
108
138
  break;
109
139
  }
110
140
  }
111
- if (matches) {
112
- return shellRoute;
113
- }
141
+ if (matches) return shellRoute;
114
142
  }
115
143
  return null;
116
144
  }
@@ -136,17 +164,21 @@ function getNetworkIp() {
136
164
  return null;
137
165
  }
138
166
  function printBanner(port) {
139
- const envFiles = detectEnvFiles(process.cwd());
167
+ const envFiles = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
140
168
  const networkIp = getNetworkIp();
141
169
  console.log(`
142
- ${C.BOLD}${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
170
+ ${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
143
171
  if (envFiles.length > 0) {
144
- console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${envFiles.join(", ")}`);
172
+ const rel = envFiles.map((f) => path.relative(process.cwd(), f));
173
+ console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
145
174
  }
146
175
  console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
147
176
  if (networkIp) {
148
177
  console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
149
178
  }
179
+ if (config.base) {
180
+ console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
181
+ }
150
182
  console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
151
183
  console.log("");
152
184
  }
@@ -161,12 +193,9 @@ async function isPortFree(port) {
161
193
  async function findFreePort(start2) {
162
194
  for (let port = start2; port < start2 + 100; port++) {
163
195
  if (await isPortFree(port)) {
164
- if (port !== start2) {
165
- console.log(`
166
- ${C.YELLOW}\u26A0${C.RESET} Port ${start2} in use \u2014 using ${port} instead.`);
167
- }
168
196
  return port;
169
197
  }
198
+ console.log(`Port ${port} is in use, trying another one...`);
170
199
  }
171
200
  throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
172
201
  }
@@ -183,7 +212,7 @@ function startKeyboardLoop(port) {
183
212
  console.log("");
184
213
  break;
185
214
  case "o": {
186
- const url = `http://localhost:${port}/`;
215
+ const url = `http://localhost:${port}${config.base || ""}/`;
187
216
  const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
188
217
  exec(cmd);
189
218
  break;
@@ -194,109 +223,6 @@ function startKeyboardLoop(port) {
194
223
  });
195
224
  rl.on("close", () => process.exit(0));
196
225
  }
197
- var routeCache = null;
198
- var routeIndex = /* @__PURE__ */ new Map();
199
- var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
200
- var CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
201
- var DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
202
- var SKIP_PATTERN = /^[_.]/;
203
- function getRouteCache() {
204
- if (!routeCache) {
205
- const start2 = Date.now();
206
- routeCache = scanApiRoutes(API_DIR);
207
- routeIndex.clear();
208
- for (let i = 0; i < routeCache.length; i++) {
209
- routeIndex.set(routeCache[i].routePath, routeCache[i]);
210
- }
211
- if (process.env.NODE_ENV === "development") {
212
- console.log(`[bini-server] API routes scanned in ${Date.now() - start2}ms`);
213
- }
214
- }
215
- return routeCache;
216
- }
217
- function scanApiRoutes(dir, baseRoute = "", depth = 0) {
218
- const routes = [];
219
- if (depth > 100 || !fs.existsSync(dir)) return routes;
220
- let entries;
221
- try {
222
- entries = fs.readdirSync(dir, { withFileTypes: true });
223
- } catch {
224
- return routes;
225
- }
226
- for (let i = 0; i < entries.length; i++) {
227
- const entry = entries[i];
228
- if (SKIP_PATTERN.test(entry.name)) continue;
229
- const fullPath = path.join(dir, entry.name);
230
- if (entry.isDirectory()) {
231
- const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
232
- const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
233
- const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
234
- const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
235
- for (let j = 0; j < childRoutes.length; j++) {
236
- routes.push(childRoutes[j]);
237
- }
238
- continue;
239
- }
240
- const ext = path.extname(entry.name);
241
- if (!API_EXTS.has(ext)) continue;
242
- const base = path.basename(entry.name, ext);
243
- const isCatchAll = base.startsWith("[...") && base.endsWith("]");
244
- const isDynamic = base.startsWith("[") && base.endsWith("]");
245
- let routePath;
246
- if (isCatchAll) routePath = `${baseRoute}/*`;
247
- else if (base === "index") routePath = baseRoute || "/";
248
- else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
249
- else routePath = `${baseRoute}/${base}`;
250
- routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
251
- }
252
- return routes;
253
- }
254
- function matchRoute(pattern, pathname) {
255
- const patParts = pattern.split("/").filter(Boolean);
256
- const urlParts = pathname.split("/").filter(Boolean);
257
- const isCatchAll = patParts[patParts.length - 1] === "*";
258
- if (isCatchAll) {
259
- const prefix = patParts.slice(0, -1);
260
- if (urlParts.length < prefix.length) return null;
261
- for (let i = 0; i < prefix.length; i++) {
262
- if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
263
- }
264
- return { "*": urlParts.slice(prefix.length).join("/") };
265
- }
266
- if (patParts.length !== urlParts.length) return null;
267
- const params = {};
268
- for (let i = 0; i < patParts.length; i++) {
269
- if (patParts[i].startsWith(":")) {
270
- const value = decodeURIComponent(urlParts[i]);
271
- if (value.includes("..") || value.includes("//")) return null;
272
- params[patParts[i].slice(1)] = value;
273
- } else if (patParts[i] !== urlParts[i]) {
274
- return null;
275
- }
276
- }
277
- return params;
278
- }
279
- var moduleCache = /* @__PURE__ */ new Map();
280
- async function importHandler(filePath) {
281
- let mtime = 0;
282
- try {
283
- mtime = fs.statSync(filePath).mtimeMs;
284
- } catch {
285
- return null;
286
- }
287
- const cached = moduleCache.get(filePath);
288
- if (cached?.mtime === mtime) return cached.handler;
289
- try {
290
- const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
291
- const handler = mod.default ?? null;
292
- moduleCache.set(filePath, { mtime, handler });
293
- return handler;
294
- } catch (e) {
295
- console.error(`[bini-api] import error: ${filePath}`, e?.message);
296
- moduleCache.delete(filePath);
297
- return null;
298
- }
299
- }
300
226
  function readBody(req) {
301
227
  return new Promise((resolve, reject) => {
302
228
  const chunks = [];
@@ -304,10 +230,10 @@ function readBody(req) {
304
230
  const timer = setTimeout(() => {
305
231
  req.destroy();
306
232
  reject(new Error("Request body timeout"));
307
- }, BODY_TIMEOUT);
233
+ }, config.bodyTimeout);
308
234
  req.on("data", (chunk) => {
309
235
  size += chunk.byteLength;
310
- if (size > BODY_SIZE_LIMIT) {
236
+ if (size > config.bodySizeLimit) {
311
237
  clearTimeout(timer);
312
238
  req.destroy();
313
239
  reject(new Error("Request body too large"));
@@ -333,121 +259,139 @@ function normalizeHeaders(raw) {
333
259
  }
334
260
  return out;
335
261
  }
336
- var CORS_HEADERS = {
337
- "Access-Control-Allow-Origin": "*",
338
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
339
- "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
340
- "Vary": "Origin"
341
- };
342
- async function handleApiRequest(req, res, next) {
343
- if (req.method === "OPTIONS") {
344
- const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
345
- res.writeHead(204, headers);
346
- res.end();
347
- return;
348
- }
349
- const routes = getRouteCache();
350
- const host = req.headers.host ?? "localhost";
351
- const rawUrl = `http://${host}${req.url ?? "/"}`;
352
- const method = (req.method ?? "GET").toUpperCase();
353
- let parsedUrl;
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;
354
275
  try {
355
- parsedUrl = new URL(rawUrl);
276
+ return toApiPath(new URL(url, "http://localhost").pathname) !== null;
356
277
  } catch {
357
- res.writeHead(400, { "Content-Type": "application/json" });
358
- res.end(JSON.stringify({ error: "Bad request URL" }));
359
- return;
278
+ return false;
360
279
  }
361
- const { pathname, search } = parsedUrl;
362
- let matchedRoute = null;
363
- let params = null;
364
- if (routeIndex.has(pathname)) {
365
- matchedRoute = routeIndex.get(pathname);
366
- params = {};
367
- } else {
368
- for (let i = 0; i < routes.length; i++) {
369
- const route = routes[i];
370
- params = matchRoute(route.routePath, pathname);
371
- if (params !== null) {
372
- matchedRoute = route;
373
- break;
280
+ }
281
+ var apiFetch = null;
282
+ var apiLoadPromise = null;
283
+ async function loadApiFetch() {
284
+ if (apiFetch) return apiFetch;
285
+ if (apiLoadPromise) return apiLoadPromise;
286
+ apiLoadPromise = (async () => {
287
+ try {
288
+ const entry = resolveApiEntry();
289
+ if (!entry) throw new Error(`${config.apiEntry} not found`);
290
+ const mod = await import(pathToFileURL(entry).href);
291
+ if (typeof mod.fetch !== "function") {
292
+ throw new Error(`${entry} does not export fetch()`);
374
293
  }
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
+ );
375
308
  }
376
- }
377
- if (!matchedRoute) {
378
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
379
- res.writeHead(404, { "Content-Type": "application/json", ...headers });
380
- res.end(JSON.stringify({ error: `No API handler for ${pathname}` }));
309
+ return apiFetch;
310
+ })();
311
+ return apiLoadPromise;
312
+ }
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
+ function sendJson(res, status, body, extra = {}) {
323
+ res.writeHead(status, { "content-type": "application/json", ...extra });
324
+ res.end(JSON.stringify(body));
325
+ }
326
+ async function sendWebResponse(res, webRes, method) {
327
+ const headers = {};
328
+ webRes.headers.forEach((v, k) => {
329
+ if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
330
+ });
331
+ const cookies = webRes.headers.getSetCookie?.();
332
+ if (cookies && cookies.length > 0) headers["set-cookie"] = cookies;
333
+ res.writeHead(webRes.status, headers);
334
+ if (method === "HEAD" || !webRes.body) {
335
+ res.end();
381
336
  return;
382
337
  }
383
- let body;
384
- if (!["GET", "HEAD"].includes(method)) {
385
- try {
386
- body = await readBody(req);
387
- } catch (e) {
388
- const status = e.message.includes("too large") ? 413 : 408;
389
- res.writeHead(status, { "Content-Type": "application/json" });
390
- res.end(JSON.stringify({ error: e.message }));
391
- return;
392
- }
338
+ try {
339
+ await pipeline(Readable.fromWeb(webRes.body), res);
340
+ } catch {
393
341
  }
394
- const handler = await importHandler(matchedRoute.filePath);
395
- if (!handler) {
396
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
397
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
398
- res.end(JSON.stringify({ error: "Failed to load handler" }));
399
- return;
342
+ }
343
+ function withTimeout(p, ms) {
344
+ let timer;
345
+ return Promise.race([
346
+ p,
347
+ new Promise((_, reject) => {
348
+ timer = setTimeout(() => reject(new Error("Handler timeout")), ms);
349
+ })
350
+ ]).finally(() => clearTimeout(timer));
351
+ }
352
+ function publicErrorMessage(e) {
353
+ return config.isProd ? "Internal server error" : e instanceof Error ? e.message : String(e);
354
+ }
355
+ async function handleApiRequest(req, res) {
356
+ const method = (req.method ?? "GET").toUpperCase();
357
+ const host = req.headers.host ?? "localhost";
358
+ let parsedUrl;
359
+ try {
360
+ parsedUrl = new URL(`http://${host}${req.url ?? "/"}`);
361
+ } catch {
362
+ return sendJson(res, 400, { error: "Bad request URL" });
400
363
  }
401
- const normalizedHeaders = normalizeHeaders(req.headers);
402
- let webRes;
364
+ if (toApiPath(parsedUrl.pathname) === null) return sendJson(res, 404, { error: "Not Found" });
365
+ const fetchApi = await loadApiFetch();
366
+ let webReq;
403
367
  try {
404
- if (typeof handler.fetch === "function") {
405
- const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
406
- webRes = await handler.fetch(new Request(honoUrl, {
407
- method,
408
- headers: normalizedHeaders,
409
- body: body ? new Uint8Array(body) : null
410
- }));
411
- } else if (typeof handler === "function") {
412
- const reqWithParams = new Request(rawUrl, {
413
- method,
414
- headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
415
- body: body ? new Uint8Array(body) : null
416
- });
417
- const result = await Promise.race([
418
- handler(reqWithParams),
419
- new Promise(
420
- (_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
421
- )
422
- ]);
423
- webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
424
- status: 200,
425
- headers: { "Content-Type": "application/json" }
368
+ webReq = await toWebRequest(req, host);
369
+ } catch (e) {
370
+ const message = e?.message ?? "Bad request";
371
+ return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
372
+ }
373
+ const ctx = {
374
+ waitUntil(p) {
375
+ p.catch(() => {
426
376
  });
427
- } else {
428
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
429
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
430
- res.end(JSON.stringify({ error: "Handler has no valid default export" }));
431
- return;
432
377
  }
378
+ };
379
+ try {
380
+ const webRes = await withTimeout(
381
+ fetchApi(webReq, process.env, ctx),
382
+ config.handlerTimeout
383
+ );
384
+ await sendWebResponse(res, webRes, method);
433
385
  } catch (e) {
434
- console.error("[bini-api] handler error:", e?.message ?? e);
435
- const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
436
- res.writeHead(500, { "Content-Type": "application/json", ...headers });
437
- res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
438
- return;
386
+ console.error("[bini-api] handler error:", e);
387
+ if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
388
+ else res.end();
439
389
  }
440
- const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
441
- webRes.headers.forEach((v, k) => {
442
- finalHeaders[k] = v;
443
- });
444
- res.writeHead(webRes.status, finalHeaders);
445
- res.end(Buffer.from(await webRes.arrayBuffer()));
446
390
  }
447
391
  function getETag(stat) {
448
392
  return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
449
393
  }
450
- async function sendFile(filePath, req, res) {
394
+ async function sendFile(filePath, req, res, status = 200) {
451
395
  const ext = path.extname(filePath).toLowerCase();
452
396
  const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
453
397
  const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
@@ -460,12 +404,12 @@ async function sendFile(filePath, req, res) {
460
404
  return;
461
405
  }
462
406
  const etag = getETag(stat);
463
- if (req.headers["if-none-match"] === etag) {
407
+ if (status === 200 && req.headers["if-none-match"] === etag) {
464
408
  res.writeHead(304);
465
409
  res.end();
466
410
  return;
467
411
  }
468
- res.writeHead(200, {
412
+ res.writeHead(status, {
469
413
  "Content-Type": mimeType,
470
414
  "Content-Length": stat.size,
471
415
  "Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
@@ -505,11 +449,17 @@ var MIME_TYPES = {
505
449
  ".map": "application/json"
506
450
  };
507
451
  async function serveStatic(req, res, next) {
508
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
509
- if (pathname.startsWith("/api")) return 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
+ }
510
459
  const hasExtension = path.extname(pathname).length > 0;
511
460
  if (hasExtension) {
512
- const filePath = path.join(DIST_DIR, pathname);
461
+ const filePath = path.join(config.distDir, pathname);
462
+ if (filePath.startsWith(config.compiledApiDir)) return next();
513
463
  try {
514
464
  const stat = await fs.promises.stat(filePath);
515
465
  if (stat.isFile()) {
@@ -520,7 +470,7 @@ async function serveStatic(req, res, next) {
520
470
  }
521
471
  return next();
522
472
  }
523
- const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
473
+ const staticFilePath = path.join(config.distDir, pathname === "/" ? "" : pathname, "index.html");
524
474
  try {
525
475
  const stat = await fs.promises.stat(staticFilePath);
526
476
  if (stat.isFile()) {
@@ -531,7 +481,7 @@ async function serveStatic(req, res, next) {
531
481
  }
532
482
  const matchingShell = findMatchingShellRoute(pathname);
533
483
  if (matchingShell) {
534
- const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
484
+ const shellPath = path.join(config.distDir, matchingShell, "index.html");
535
485
  try {
536
486
  const stat = await fs.promises.stat(shellPath);
537
487
  if (stat.isFile()) {
@@ -541,7 +491,16 @@ async function serveStatic(req, res, next) {
541
491
  } catch {
542
492
  }
543
493
  }
544
- const indexPath = path.join(DIST_DIR, "index.html");
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");
545
504
  try {
546
505
  await fs.promises.access(indexPath);
547
506
  await sendFile(indexPath, req, res);
@@ -560,7 +519,7 @@ function compose(middlewares) {
560
519
  } catch (e) {
561
520
  if (!res.headersSent) {
562
521
  res.writeHead(500, { "Content-Type": "application/json" });
563
- res.end(JSON.stringify({ error: e?.message ?? "Internal Server Error" }));
522
+ res.end(JSON.stringify({ error: publicErrorMessage(e) }));
564
523
  }
565
524
  }
566
525
  };
@@ -568,19 +527,22 @@ function compose(middlewares) {
568
527
  };
569
528
  }
570
529
  async function start() {
571
- if (!fs.existsSync(DIST_DIR)) {
530
+ loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
531
+ refreshConfig();
532
+ if (!fs.existsSync(config.distDir)) {
572
533
  console.error(`
573
- ${C.RED}\u2717${C.RESET} dist/ not found at ${DIST_DIR}.
534
+ ${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
574
535
  Run ${C.CYAN}npm run build${C.RESET} first.
575
536
  `);
576
537
  process.exit(1);
577
538
  }
539
+ await loadApiFetch();
578
540
  getShellRoutes();
579
- const port = await findFreePort(DEFAULT_PORT);
541
+ const port = await findFreePort(config.defaultPort);
580
542
  const handler = compose([
581
543
  async (req, res, next) => {
582
- if (!req.url?.startsWith("/api")) return next();
583
- await handleApiRequest(req, res, next);
544
+ if (!isApiRequest(req.url)) return next();
545
+ await handleApiRequest(req, res);
584
546
  },
585
547
  serveStatic,
586
548
  (_req, res) => {
@@ -614,3 +576,4 @@ async function start() {
614
576
  export {
615
577
  start
616
578
  };
579
+ //# sourceMappingURL=index.js.map