bini-server 1.0.10 → 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/README.md +278 -200
- package/dist/cli.js +302 -264
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +301 -263
- package/dist/index.js.map +1 -0
- package/package.json +18 -14
package/dist/cli.js
CHANGED
|
@@ -15,7 +15,7 @@ __export(src_exports, {
|
|
|
15
15
|
start: () => start
|
|
16
16
|
});
|
|
17
17
|
import http from "http";
|
|
18
|
-
import fs from "fs";
|
|
18
|
+
import fs, { createReadStream } from "fs";
|
|
19
19
|
import path from "path";
|
|
20
20
|
import os from "os";
|
|
21
21
|
import net from "net";
|
|
@@ -23,42 +23,129 @@ import crypto from "crypto";
|
|
|
23
23
|
import readline from "readline";
|
|
24
24
|
import { exec } from "child_process";
|
|
25
25
|
import { pathToFileURL } from "url";
|
|
26
|
+
import { Readable } from "stream";
|
|
26
27
|
import { pipeline } from "stream/promises";
|
|
27
|
-
import {
|
|
28
|
-
function detectEnvFiles(root) {
|
|
29
|
-
const nodeEnv = process.env.NODE_ENV ?? "production";
|
|
30
|
-
return [
|
|
31
|
-
".env.local",
|
|
32
|
-
`.env.${nodeEnv}.local`,
|
|
33
|
-
`.env.${nodeEnv}`,
|
|
34
|
-
".env"
|
|
35
|
-
].filter((f) => fs.existsSync(path.join(root, f)));
|
|
36
|
-
}
|
|
28
|
+
import { loadEnvFiles, envFilesFor } from "bini-env/node";
|
|
37
29
|
function getEnvVar(key, defaultValue) {
|
|
38
30
|
const biniKey = `BINI_${key}`;
|
|
39
|
-
if (process.env[biniKey] !== void 0)
|
|
40
|
-
return process.env[biniKey];
|
|
41
|
-
}
|
|
31
|
+
if (process.env[biniKey] !== void 0) return process.env[biniKey];
|
|
42
32
|
const viteKey = `VITE_${key}`;
|
|
43
|
-
if (process.env[viteKey] !== void 0)
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
if (process.env[key] !== void 0) {
|
|
47
|
-
return process.env[key];
|
|
48
|
-
}
|
|
33
|
+
if (process.env[viteKey] !== void 0) return process.env[viteKey];
|
|
34
|
+
if (process.env[key] !== void 0) return process.env[key];
|
|
49
35
|
return defaultValue;
|
|
50
36
|
}
|
|
51
|
-
function getEnvVarBoolean(key, defaultValue) {
|
|
52
|
-
const value = getEnvVar(key);
|
|
53
|
-
if (value === void 0) return defaultValue;
|
|
54
|
-
return value !== "false" && value !== "0" && value !== "";
|
|
55
|
-
}
|
|
56
37
|
function getEnvVarNumber(key, defaultValue) {
|
|
57
38
|
const value = getEnvVar(key);
|
|
58
39
|
if (value === void 0) return defaultValue;
|
|
59
40
|
const parsed = parseInt(value, 10);
|
|
60
41
|
return isNaN(parsed) ? defaultValue : parsed;
|
|
61
42
|
}
|
|
43
|
+
function readConfig() {
|
|
44
|
+
const distDir = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
|
|
45
|
+
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, "");
|
|
49
|
+
return {
|
|
50
|
+
defaultPort: getEnvVarNumber("PORT", 3e3),
|
|
51
|
+
bodyTimeout: getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3,
|
|
52
|
+
handlerTimeout: getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3,
|
|
53
|
+
bodySizeLimit: getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024),
|
|
54
|
+
distDir,
|
|
55
|
+
compiledApiDir: apiDir + path.sep,
|
|
56
|
+
apiDir,
|
|
57
|
+
apiEntry,
|
|
58
|
+
base,
|
|
59
|
+
isProd: process.env.NODE_ENV === "production"
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function refreshConfig() {
|
|
63
|
+
config = readConfig();
|
|
64
|
+
}
|
|
65
|
+
function resolveApiEntry() {
|
|
66
|
+
return fs.existsSync(config.apiEntry) ? config.apiEntry : null;
|
|
67
|
+
}
|
|
68
|
+
function stripBase(pathname) {
|
|
69
|
+
const base = config.base;
|
|
70
|
+
if (!base) return pathname || "/";
|
|
71
|
+
if (pathname === base || pathname === base + "/") return "/";
|
|
72
|
+
if (pathname.startsWith(base + "/")) return pathname.slice(base.length) || "/";
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
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;
|
|
148
|
+
}
|
|
62
149
|
function getNetworkIp() {
|
|
63
150
|
const ifaces = os.networkInterfaces();
|
|
64
151
|
const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
|
|
@@ -81,17 +168,21 @@ function getNetworkIp() {
|
|
|
81
168
|
return null;
|
|
82
169
|
}
|
|
83
170
|
function printBanner(port) {
|
|
84
|
-
const envFiles2 =
|
|
171
|
+
const envFiles2 = envFilesFor(process.cwd(), process.env.NODE_ENV ?? "production");
|
|
85
172
|
const networkIp = getNetworkIp();
|
|
86
173
|
console.log(`
|
|
87
|
-
${C.
|
|
174
|
+
${C.CYAN}\xDF Bini.js${C.RESET} (production)`);
|
|
88
175
|
if (envFiles2.length > 0) {
|
|
89
|
-
|
|
176
|
+
const rel = envFiles2.map((f) => path.relative(process.cwd(), f));
|
|
177
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Environments: ${rel.join(", ")}`);
|
|
90
178
|
}
|
|
91
179
|
console.log(` ${C.GREEN}\u279C${C.RESET} Local: ${C.CYAN}http://localhost:${port}/${C.RESET}`);
|
|
92
180
|
if (networkIp) {
|
|
93
181
|
console.log(` ${C.GREEN}\u279C${C.RESET} Network: ${C.CYAN}http://${networkIp}:${port}/${C.RESET}`);
|
|
94
182
|
}
|
|
183
|
+
if (config.base) {
|
|
184
|
+
console.log(` ${C.GREEN}\u279C${C.RESET} Base: ${C.CYAN}${config.base}${C.RESET}`);
|
|
185
|
+
}
|
|
95
186
|
console.log(` ${C.DIM}${C.GREEN}\u279C${C.RESET} ${C.DIM}press ${C.RESET}h + enter${C.DIM} to show help${C.RESET}`);
|
|
96
187
|
console.log("");
|
|
97
188
|
}
|
|
@@ -106,31 +197,26 @@ async function isPortFree(port) {
|
|
|
106
197
|
async function findFreePort(start3) {
|
|
107
198
|
for (let port = start3; port < start3 + 100; port++) {
|
|
108
199
|
if (await isPortFree(port)) {
|
|
109
|
-
if (port !== start3) {
|
|
110
|
-
console.log(`
|
|
111
|
-
${C.YELLOW}\u26A0${C.RESET} Port ${start3} in use \u2014 using ${port} instead.`);
|
|
112
|
-
}
|
|
113
200
|
return port;
|
|
114
201
|
}
|
|
202
|
+
console.log(`Port ${port} is in use, trying another one...`);
|
|
115
203
|
}
|
|
116
204
|
throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
|
|
117
205
|
}
|
|
118
206
|
function startKeyboardLoop(port) {
|
|
119
|
-
if (!process.stdin.isTTY)
|
|
120
|
-
return;
|
|
121
|
-
}
|
|
207
|
+
if (!process.stdin.isTTY) return;
|
|
122
208
|
const rl = readline.createInterface({ input: process.stdin });
|
|
123
209
|
rl.on("line", (line) => {
|
|
124
210
|
switch (line.trim()) {
|
|
125
211
|
case "h":
|
|
126
212
|
console.log("");
|
|
127
213
|
console.log(" Shortcuts");
|
|
128
|
-
console.log(` ${C.DIM}press ${C.RESET}o + enter${C.
|
|
129
|
-
console.log(` ${C.DIM}press ${C.RESET}q + enter${C.
|
|
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}`);
|
|
130
216
|
console.log("");
|
|
131
217
|
break;
|
|
132
218
|
case "o": {
|
|
133
|
-
const url = `http://localhost:${port}/`;
|
|
219
|
+
const url = `http://localhost:${port}${config.base || ""}/`;
|
|
134
220
|
const cmd = process.platform === "win32" ? `start ${url}` : process.platform === "darwin" ? `open ${url}` : `xdg-open ${url}`;
|
|
135
221
|
exec(cmd);
|
|
136
222
|
break;
|
|
@@ -141,102 +227,6 @@ function startKeyboardLoop(port) {
|
|
|
141
227
|
});
|
|
142
228
|
rl.on("close", () => process.exit(0));
|
|
143
229
|
}
|
|
144
|
-
function getRouteCache() {
|
|
145
|
-
if (!routeCache) {
|
|
146
|
-
const start3 = Date.now();
|
|
147
|
-
routeCache = scanApiRoutes(API_DIR);
|
|
148
|
-
routeIndex.clear();
|
|
149
|
-
for (let i = 0; i < routeCache.length; i++) {
|
|
150
|
-
routeIndex.set(routeCache[i].routePath, routeCache[i]);
|
|
151
|
-
}
|
|
152
|
-
if (process.env.NODE_ENV === "development") {
|
|
153
|
-
console.log(`[bini-server] Routes scanned in ${Date.now() - start3}ms`);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
return routeCache;
|
|
157
|
-
}
|
|
158
|
-
function scanApiRoutes(dir, baseRoute = "", depth = 0) {
|
|
159
|
-
const routes = [];
|
|
160
|
-
if (depth > 100 || !fs.existsSync(dir)) return routes;
|
|
161
|
-
let entries;
|
|
162
|
-
try {
|
|
163
|
-
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
164
|
-
} catch {
|
|
165
|
-
return routes;
|
|
166
|
-
}
|
|
167
|
-
for (let i = 0; i < entries.length; i++) {
|
|
168
|
-
const entry = entries[i];
|
|
169
|
-
if (SKIP_PATTERN.test(entry.name)) continue;
|
|
170
|
-
const fullPath = path.join(dir, entry.name);
|
|
171
|
-
if (entry.isDirectory()) {
|
|
172
|
-
const isCatchAll2 = CATCH_ALL_PATTERN.test(entry.name);
|
|
173
|
-
const isDynamic2 = DYNAMIC_PATTERN.test(entry.name);
|
|
174
|
-
const segment = isCatchAll2 ? "*" : isDynamic2 ? `:${entry.name.slice(1, -1)}` : entry.name;
|
|
175
|
-
const childRoutes = scanApiRoutes(fullPath, `${baseRoute}/${segment}`, depth + 1);
|
|
176
|
-
for (let j = 0; j < childRoutes.length; j++) {
|
|
177
|
-
routes.push(childRoutes[j]);
|
|
178
|
-
}
|
|
179
|
-
continue;
|
|
180
|
-
}
|
|
181
|
-
const ext = path.extname(entry.name);
|
|
182
|
-
if (!API_EXTS.has(ext)) continue;
|
|
183
|
-
const base = path.basename(entry.name, ext);
|
|
184
|
-
const isCatchAll = base.startsWith("[...") && base.endsWith("]");
|
|
185
|
-
const isDynamic = base.startsWith("[") && base.endsWith("]");
|
|
186
|
-
let routePath;
|
|
187
|
-
if (isCatchAll) routePath = `${baseRoute}/*`;
|
|
188
|
-
else if (base === "index") routePath = baseRoute || "/";
|
|
189
|
-
else if (isDynamic) routePath = `${baseRoute}/:${base.slice(1, -1)}`;
|
|
190
|
-
else routePath = `${baseRoute}/${base}`;
|
|
191
|
-
routes.push({ routePath: `/api${routePath}`, filePath: fullPath });
|
|
192
|
-
}
|
|
193
|
-
return routes;
|
|
194
|
-
}
|
|
195
|
-
function matchRoute(pattern, pathname) {
|
|
196
|
-
const patParts = pattern.split("/").filter(Boolean);
|
|
197
|
-
const urlParts = pathname.split("/").filter(Boolean);
|
|
198
|
-
const isCatchAll = patParts[patParts.length - 1] === "*";
|
|
199
|
-
if (isCatchAll) {
|
|
200
|
-
const prefix = patParts.slice(0, -1);
|
|
201
|
-
if (urlParts.length < prefix.length) return null;
|
|
202
|
-
for (let i = 0; i < prefix.length; i++) {
|
|
203
|
-
if (!prefix[i].startsWith(":") && prefix[i] !== urlParts[i]) return null;
|
|
204
|
-
}
|
|
205
|
-
return { "*": urlParts.slice(prefix.length).join("/") };
|
|
206
|
-
}
|
|
207
|
-
if (patParts.length !== urlParts.length) return null;
|
|
208
|
-
const params = {};
|
|
209
|
-
for (let i = 0; i < patParts.length; i++) {
|
|
210
|
-
if (patParts[i].startsWith(":")) {
|
|
211
|
-
const value = decodeURIComponent(urlParts[i]);
|
|
212
|
-
if (value.includes("..") || value.includes("//")) return null;
|
|
213
|
-
params[patParts[i].slice(1)] = value;
|
|
214
|
-
} else if (patParts[i] !== urlParts[i]) {
|
|
215
|
-
return null;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
return params;
|
|
219
|
-
}
|
|
220
|
-
async function importHandler(filePath) {
|
|
221
|
-
let mtime = 0;
|
|
222
|
-
try {
|
|
223
|
-
mtime = fs.statSync(filePath).mtimeMs;
|
|
224
|
-
} catch {
|
|
225
|
-
return null;
|
|
226
|
-
}
|
|
227
|
-
const cached = moduleCache.get(filePath);
|
|
228
|
-
if (cached?.mtime === mtime) return cached.handler;
|
|
229
|
-
try {
|
|
230
|
-
const mod = await import(pathToFileURL(filePath).href + "?t=" + mtime);
|
|
231
|
-
const handler = mod.default ?? null;
|
|
232
|
-
moduleCache.set(filePath, { mtime, handler });
|
|
233
|
-
return handler;
|
|
234
|
-
} catch (e) {
|
|
235
|
-
console.error(`[bini-api] import error: ${filePath}`, e?.message);
|
|
236
|
-
moduleCache.delete(filePath);
|
|
237
|
-
return null;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
230
|
function readBody(req) {
|
|
241
231
|
return new Promise((resolve, reject) => {
|
|
242
232
|
const chunks = [];
|
|
@@ -244,10 +234,10 @@ function readBody(req) {
|
|
|
244
234
|
const timer = setTimeout(() => {
|
|
245
235
|
req.destroy();
|
|
246
236
|
reject(new Error("Request body timeout"));
|
|
247
|
-
},
|
|
237
|
+
}, config.bodyTimeout);
|
|
248
238
|
req.on("data", (chunk) => {
|
|
249
239
|
size += chunk.byteLength;
|
|
250
|
-
if (size >
|
|
240
|
+
if (size > config.bodySizeLimit) {
|
|
251
241
|
clearTimeout(timer);
|
|
252
242
|
req.destroy();
|
|
253
243
|
reject(new Error("Request body too large"));
|
|
@@ -273,118 +263,137 @@ function normalizeHeaders(raw) {
|
|
|
273
263
|
}
|
|
274
264
|
return out;
|
|
275
265
|
}
|
|
276
|
-
function
|
|
277
|
-
|
|
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;
|
|
278
276
|
}
|
|
279
|
-
|
|
280
|
-
if (
|
|
281
|
-
const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
|
|
282
|
-
res.writeHead(204, headers);
|
|
283
|
-
res.end();
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
const routes = getRouteCache();
|
|
287
|
-
const host = req.headers.host ?? "localhost";
|
|
288
|
-
const rawUrl = `http://${host}${req.url ?? "/"}`;
|
|
289
|
-
const method = (req.method ?? "GET").toUpperCase();
|
|
290
|
-
let parsedUrl;
|
|
277
|
+
function isApiRequest(url) {
|
|
278
|
+
if (!url) return false;
|
|
291
279
|
try {
|
|
292
|
-
|
|
280
|
+
return toApiPath(new URL(url, "http://localhost").pathname) !== null;
|
|
293
281
|
} catch {
|
|
294
|
-
|
|
295
|
-
res.end(JSON.stringify({ error: "Bad request URL" }));
|
|
296
|
-
return;
|
|
282
|
+
return false;
|
|
297
283
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
matchedRoute = route;
|
|
310
|
-
break;
|
|
284
|
+
}
|
|
285
|
+
async function loadApiFetch() {
|
|
286
|
+
if (apiFetch) return apiFetch;
|
|
287
|
+
if (apiLoadPromise) return apiLoadPromise;
|
|
288
|
+
apiLoadPromise = (async () => {
|
|
289
|
+
try {
|
|
290
|
+
const entry = resolveApiEntry();
|
|
291
|
+
if (!entry) throw new Error(`${config.apiEntry} not found`);
|
|
292
|
+
const mod = await import(pathToFileURL(entry).href);
|
|
293
|
+
if (typeof mod.fetch !== "function") {
|
|
294
|
+
throw new Error(`${entry} does not export fetch()`);
|
|
311
295
|
}
|
|
296
|
+
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
|
+
);
|
|
312
310
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
311
|
+
return apiFetch;
|
|
312
|
+
})();
|
|
313
|
+
return apiLoadPromise;
|
|
314
|
+
}
|
|
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
|
+
function sendJson(res, status, body, extra = {}) {
|
|
325
|
+
res.writeHead(status, { "content-type": "application/json", ...extra });
|
|
326
|
+
res.end(JSON.stringify(body));
|
|
327
|
+
}
|
|
328
|
+
async function sendWebResponse(res, webRes, method) {
|
|
329
|
+
const headers = {};
|
|
330
|
+
webRes.headers.forEach((v, k) => {
|
|
331
|
+
if (k.toLowerCase() !== "set-cookie") headers[k.toLowerCase()] = v;
|
|
332
|
+
});
|
|
333
|
+
const cookies = webRes.headers.getSetCookie?.();
|
|
334
|
+
if (cookies && cookies.length > 0) headers["set-cookie"] = cookies;
|
|
335
|
+
res.writeHead(webRes.status, headers);
|
|
336
|
+
if (method === "HEAD" || !webRes.body) {
|
|
337
|
+
res.end();
|
|
318
338
|
return;
|
|
319
339
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
body = await readBody(req);
|
|
324
|
-
} catch (e) {
|
|
325
|
-
const status = e.message.includes("too large") ? 413 : 408;
|
|
326
|
-
res.writeHead(status, { "Content-Type": "application/json" });
|
|
327
|
-
res.end(JSON.stringify({ error: e.message }));
|
|
328
|
-
return;
|
|
329
|
-
}
|
|
340
|
+
try {
|
|
341
|
+
await pipeline(Readable.fromWeb(webRes.body), res);
|
|
342
|
+
} catch {
|
|
330
343
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
344
|
+
}
|
|
345
|
+
function withTimeout(p, ms) {
|
|
346
|
+
let timer;
|
|
347
|
+
return Promise.race([
|
|
348
|
+
p,
|
|
349
|
+
new Promise((_, reject) => {
|
|
350
|
+
timer = setTimeout(() => reject(new Error("Handler timeout")), ms);
|
|
351
|
+
})
|
|
352
|
+
]).finally(() => clearTimeout(timer));
|
|
353
|
+
}
|
|
354
|
+
function publicErrorMessage(e) {
|
|
355
|
+
return config.isProd ? "Internal server error" : e instanceof Error ? e.message : String(e);
|
|
356
|
+
}
|
|
357
|
+
async function handleApiRequest(req, res) {
|
|
358
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
359
|
+
const host = req.headers.host ?? "localhost";
|
|
360
|
+
let parsedUrl;
|
|
361
|
+
try {
|
|
362
|
+
parsedUrl = new URL(`http://${host}${req.url ?? "/"}`);
|
|
363
|
+
} catch {
|
|
364
|
+
return sendJson(res, 400, { error: "Bad request URL" });
|
|
337
365
|
}
|
|
338
|
-
|
|
339
|
-
|
|
366
|
+
if (toApiPath(parsedUrl.pathname) === null) return sendJson(res, 404, { error: "Not Found" });
|
|
367
|
+
const fetchApi = await loadApiFetch();
|
|
368
|
+
let webReq;
|
|
340
369
|
try {
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
const reqWithParams = new Request(rawUrl, {
|
|
350
|
-
method,
|
|
351
|
-
headers: { ...normalizedHeaders, "x-bini-params": JSON.stringify(params ?? {}) },
|
|
352
|
-
body: body ? new Uint8Array(body) : null
|
|
353
|
-
});
|
|
354
|
-
const result = await Promise.race([
|
|
355
|
-
handler(reqWithParams),
|
|
356
|
-
new Promise(
|
|
357
|
-
(_, reject) => setTimeout(() => reject(new Error("Handler timeout")), HANDLER_TIMEOUT)
|
|
358
|
-
)
|
|
359
|
-
]);
|
|
360
|
-
webRes = result instanceof Response ? result : new Response(JSON.stringify(result), {
|
|
361
|
-
status: 200,
|
|
362
|
-
headers: { "Content-Type": "application/json" }
|
|
370
|
+
webReq = await toWebRequest(req, host);
|
|
371
|
+
} catch (e) {
|
|
372
|
+
const message = e?.message ?? "Bad request";
|
|
373
|
+
return sendJson(res, message.includes("too large") ? 413 : 408, { error: message });
|
|
374
|
+
}
|
|
375
|
+
const ctx = {
|
|
376
|
+
waitUntil(p) {
|
|
377
|
+
p.catch(() => {
|
|
363
378
|
});
|
|
364
|
-
} else {
|
|
365
|
-
const headers = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
366
|
-
res.writeHead(500, { "Content-Type": "application/json", ...headers });
|
|
367
|
-
res.end(JSON.stringify({ error: "Handler has no valid default export" }));
|
|
368
|
-
return;
|
|
369
379
|
}
|
|
380
|
+
};
|
|
381
|
+
try {
|
|
382
|
+
const webRes = await withTimeout(
|
|
383
|
+
fetchApi(webReq, process.env, ctx),
|
|
384
|
+
config.handlerTimeout
|
|
385
|
+
);
|
|
386
|
+
await sendWebResponse(res, webRes, method);
|
|
370
387
|
} catch (e) {
|
|
371
|
-
console.error("[bini-api] handler error:", e
|
|
372
|
-
|
|
373
|
-
res.
|
|
374
|
-
res.end(JSON.stringify({ error: e?.message ?? "Internal server error" }));
|
|
375
|
-
return;
|
|
388
|
+
console.error("[bini-api] handler error:", e);
|
|
389
|
+
if (!res.headersSent) sendJson(res, 500, { error: publicErrorMessage(e) });
|
|
390
|
+
else res.end();
|
|
376
391
|
}
|
|
377
|
-
const finalHeaders = CORS_ENABLED ? { ...CORS_HEADERS } : {};
|
|
378
|
-
webRes.headers.forEach((v, k) => {
|
|
379
|
-
finalHeaders[k] = v;
|
|
380
|
-
});
|
|
381
|
-
res.writeHead(webRes.status, finalHeaders);
|
|
382
|
-
res.end(Buffer.from(await webRes.arrayBuffer()));
|
|
383
392
|
}
|
|
384
393
|
function getETag(stat) {
|
|
385
394
|
return crypto.createHash("md5").update(`${stat.size}-${stat.mtimeMs}`).digest("hex").slice(0, 16);
|
|
386
395
|
}
|
|
387
|
-
async function sendFile(filePath, req, res) {
|
|
396
|
+
async function sendFile(filePath, req, res, status = 200) {
|
|
388
397
|
const ext = path.extname(filePath).toLowerCase();
|
|
389
398
|
const mimeType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
390
399
|
const isAsset = filePath.includes(`${path.sep}assets${path.sep}`);
|
|
@@ -397,12 +406,12 @@ async function sendFile(filePath, req, res) {
|
|
|
397
406
|
return;
|
|
398
407
|
}
|
|
399
408
|
const etag = getETag(stat);
|
|
400
|
-
if (req.headers["if-none-match"] === etag) {
|
|
409
|
+
if (status === 200 && req.headers["if-none-match"] === etag) {
|
|
401
410
|
res.writeHead(304);
|
|
402
411
|
res.end();
|
|
403
412
|
return;
|
|
404
413
|
}
|
|
405
|
-
res.writeHead(
|
|
414
|
+
res.writeHead(status, {
|
|
406
415
|
"Content-Type": mimeType,
|
|
407
416
|
"Content-Length": stat.size,
|
|
408
417
|
"Cache-Control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
|
|
@@ -419,18 +428,58 @@ async function sendFile(filePath, req, res) {
|
|
|
419
428
|
}
|
|
420
429
|
}
|
|
421
430
|
async function serveStatic(req, res, next) {
|
|
422
|
-
const
|
|
423
|
-
if (
|
|
424
|
-
const
|
|
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");
|
|
425
453
|
try {
|
|
426
|
-
const stat = await fs.promises.stat(
|
|
454
|
+
const stat = await fs.promises.stat(staticFilePath);
|
|
427
455
|
if (stat.isFile()) {
|
|
428
|
-
await sendFile(
|
|
456
|
+
await sendFile(staticFilePath, req, res);
|
|
429
457
|
return;
|
|
430
458
|
}
|
|
431
459
|
} catch {
|
|
432
460
|
}
|
|
433
|
-
const
|
|
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");
|
|
474
|
+
try {
|
|
475
|
+
const stat = await fs.promises.stat(notFoundPath);
|
|
476
|
+
if (stat.isFile()) {
|
|
477
|
+
await sendFile(notFoundPath, req, res, 404);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
} catch {
|
|
481
|
+
}
|
|
482
|
+
const indexPath = path.join(config.distDir, "index.html");
|
|
434
483
|
try {
|
|
435
484
|
await fs.promises.access(indexPath);
|
|
436
485
|
await sendFile(indexPath, req, res);
|
|
@@ -449,7 +498,7 @@ function compose(middlewares) {
|
|
|
449
498
|
} catch (e) {
|
|
450
499
|
if (!res.headersSent) {
|
|
451
500
|
res.writeHead(500, { "Content-Type": "application/json" });
|
|
452
|
-
res.end(JSON.stringify({ error: e
|
|
501
|
+
res.end(JSON.stringify({ error: publicErrorMessage(e) }));
|
|
453
502
|
}
|
|
454
503
|
}
|
|
455
504
|
};
|
|
@@ -457,18 +506,22 @@ function compose(middlewares) {
|
|
|
457
506
|
};
|
|
458
507
|
}
|
|
459
508
|
async function start() {
|
|
460
|
-
|
|
509
|
+
loadEnvFiles(process.cwd(), process.env.NODE_ENV ?? "production");
|
|
510
|
+
refreshConfig();
|
|
511
|
+
if (!fs.existsSync(config.distDir)) {
|
|
461
512
|
console.error(`
|
|
462
|
-
${C.RED}\u2717${C.RESET} dist/ not found at ${
|
|
513
|
+
${C.RED}\u2717${C.RESET} dist/ not found at ${config.distDir}.
|
|
463
514
|
Run ${C.CYAN}npm run build${C.RESET} first.
|
|
464
515
|
`);
|
|
465
516
|
process.exit(1);
|
|
466
517
|
}
|
|
467
|
-
|
|
518
|
+
await loadApiFetch();
|
|
519
|
+
getShellRoutes();
|
|
520
|
+
const port = await findFreePort(config.defaultPort);
|
|
468
521
|
const handler = compose([
|
|
469
522
|
async (req, res, next) => {
|
|
470
|
-
if (!req.url
|
|
471
|
-
await handleApiRequest(req, res
|
|
523
|
+
if (!isApiRequest(req.url)) return next();
|
|
524
|
+
await handleApiRequest(req, res);
|
|
472
525
|
},
|
|
473
526
|
serveStatic,
|
|
474
527
|
(_req, res) => {
|
|
@@ -499,17 +552,11 @@ async function start() {
|
|
|
499
552
|
process.on("SIGTERM", shutdown);
|
|
500
553
|
process.on("SIGINT", shutdown);
|
|
501
554
|
}
|
|
502
|
-
var
|
|
555
|
+
var config, C, shellRouteCache, apiFetch, apiLoadPromise, MIME_TYPES;
|
|
503
556
|
var init_src = __esm({
|
|
504
557
|
"src/index.ts"() {
|
|
505
558
|
"use strict";
|
|
506
|
-
|
|
507
|
-
BODY_TIMEOUT = getEnvVarNumber("BODY_TIMEOUT_SECS", 30) * 1e3;
|
|
508
|
-
HANDLER_TIMEOUT = getEnvVarNumber("HANDLER_TIMEOUT_SECS", 30) * 1e3;
|
|
509
|
-
BODY_SIZE_LIMIT = getEnvVarNumber("BODY_SIZE_LIMIT", 10 * 1024 * 1024);
|
|
510
|
-
API_DIR = path.join(process.cwd(), getEnvVar("API_DIR") ?? "src/app/api");
|
|
511
|
-
DIST_DIR = path.join(process.cwd(), getEnvVar("DIST_DIR") ?? "dist");
|
|
512
|
-
CORS_ENABLED = getEnvVarBoolean("CORS_ENABLED", true);
|
|
559
|
+
config = readConfig();
|
|
513
560
|
C = {
|
|
514
561
|
CYAN: "\x1B[36m",
|
|
515
562
|
RESET: "\x1B[0m",
|
|
@@ -519,19 +566,9 @@ var init_src = __esm({
|
|
|
519
566
|
BOLD: "\x1B[1m",
|
|
520
567
|
DIM: "\x1B[2m"
|
|
521
568
|
};
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
SKIP_PATTERN = /^[_.]/;
|
|
526
|
-
routeCache = null;
|
|
527
|
-
routeIndex = /* @__PURE__ */ new Map();
|
|
528
|
-
moduleCache = /* @__PURE__ */ new Map();
|
|
529
|
-
CORS_HEADERS = {
|
|
530
|
-
"Access-Control-Allow-Origin": "*",
|
|
531
|
-
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD",
|
|
532
|
-
"Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
|
|
533
|
-
"Vary": "Origin"
|
|
534
|
-
};
|
|
569
|
+
shellRouteCache = null;
|
|
570
|
+
apiFetch = null;
|
|
571
|
+
apiLoadPromise = null;
|
|
535
572
|
MIME_TYPES = {
|
|
536
573
|
".html": "text/html; charset=utf-8",
|
|
537
574
|
".js": "application/javascript",
|
|
@@ -575,3 +612,4 @@ start2().catch((err) => {
|
|
|
575
612
|
console.error(err);
|
|
576
613
|
process.exit(1);
|
|
577
614
|
});
|
|
615
|
+
//# sourceMappingURL=cli.js.map
|