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