Files
vibemake/scripts/server.mjs
T
Jerry 1c837766cd feat: integrate robot assembly and simulation with resilient loading
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
2026-10-30 18:38:39 +08:00

146 lines
8.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// vibemake 本地开发服务器(线上是静态网站部署,用 node scripts/build.mjs 打包 dist,不需要这个文件)
// - 提供页面和静态文件,页面路由不带 .html:/ /explore /studio /cad /pcb /project/<编号> /workspace /workspace/<编号>
// - 把 /api 转发到后端(后端没开跨域,浏览器不能直接请求后端域名,必须同域转发)
// - 按访问的域名选择后端:
// dev-vibemake.robotquan.com、localhost、127.0.0.1、局域网 IP → https://dev-vibemake-api.robotquan.com
// vibemake.robotquan.com 等正式域名 → https://vibemake-api.robotquan.com
//
// 本地:node scripts/server.mjs → http://localhost:8090
// 线上浏览器直接请求后端域名(见 js/api.js 的 API_HOSTS),这里的域名判断只用于本地调试
// 环境变量:PORT 端口(默认 8090);API_TARGET 强制所有域名都转发到这个后端;API_DEV / API_PROD 改两个后端地址;
// SITE_ROOT 页面文件目录(默认:在 scripts/ 里运行时是项目根目录,在 dist/ 里运行时是 dist 本身)
import http from 'node:http';
import https from 'node:https';
import zlib from 'node:zlib';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { basename, dirname, extname, join, normalize, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { MODEL_ASSET_ROUTE } from '../js/model-assets.js';
import { proxyModelAsset } from './model-assets-proxy.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(process.env.SITE_ROOT || (basename(HERE) === 'scripts' ? join(HERE, '..') : HERE));
const PORT = Number(process.env.PORT || 8090);
const API_DEV = process.env.API_DEV || 'https://dev-vibemake-api.robotquan.com';
const API_PROD = process.env.API_PROD || 'https://vibemake-api.robotquan.com';
// ---------- 按域名选后端 ----------
const DEV_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|dev-[^.]+\..+|.*\.local)$/i;
function backendFor(req) {
if (process.env.API_TARGET) return new URL(process.env.API_TARGET);
// 前面有 nginx / 1Panel 反向代理时,优先看它带过来的原始域名
const host = String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim().replace(/:\d+$/, '');
return new URL(DEV_HOST.test(host) ? API_DEV : API_PROD);
}
// ---------- /api 转发 ----------
function proxy(req, res) {
const target = backendFor(req);
const client = target.protocol === 'https:' ? https : http;
// 对后端来说是服务端请求:不带浏览器的 Origin / Referer,Host 换成后端域名
const { origin, referer, host, connection, ...headers } = req.headers;
const upstream = client.request({
protocol: target.protocol, hostname: target.hostname, port: target.port || (target.protocol === 'https:' ? 443 : 80),
method: req.method, path: req.url, headers: { ...headers, host: target.host },
}, (up) => {
const out = { ...up.headers };
// AI 助手的 SSE:告诉前面的 nginx 不要缓冲,逐条转发
if (String(up.headers['content-type'] || '').includes('text/event-stream')) out['x-accel-buffering'] = 'no';
res.writeHead(up.statusCode, out);
up.pipe(res);
});
upstream.setTimeout(120_000, () => upstream.destroy(new Error('后端响应超时')));
upstream.on('error', (err) => {
if (res.headersSent) { res.destroy(); return; }
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ code: 'PROXY_ERROR', message: `连不上后端 ${target.origin}:${err.code || err.message}`, data: null, requestId: null }));
});
res.on('close', () => { if (!res.writableFinished) upstream.destroy(); }); // 前端取消请求时一起断开
req.pipe(upstream);
}
// ---------- 页面路由 ----------
const PAGES = { '/': 'index.html', '/explore': 'explore.html', '/studio': 'studio.html', '/cad': 'cad.html', '/pcb': 'pcb.html', '/workspace': 'workspace.html' };
function pageFor(pathname) {
pathname = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; // /explore/ 和 /explore 一样
return PAGES[pathname]
|| (/^\/project(\/[^/]+)?\/?$/.test(pathname) && 'project.html')
|| (/^\/workspace\/[^/]+\/?$/.test(pathname) && 'workspace.html');
}
// ---------- 静态文件 ----------
const TYPES = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml',
'.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json', '.urdf': 'application/xml', '.xml': 'application/xml', '.stl': 'model/stl',
'.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.obj': 'text/plain', '.dae': 'model/vnd.collada+xml',
'.wasm': 'application/wasm',
};
const COMPRESS = /\.(html|js|mjs|css|json|md|svg|urdf|xml|stl|obj|dae|gltf)$/i;
const LONG_CACHE = /\.(stl|dae|obj|glb|gltf|urdf|png|jpe?g|webp|svg|ico)$/i;
const HIDDEN = /(^|\/)(\.|server\.mjs$|package\.json$|scripts\/|sandbox\/|docs\/|README\.md$|DEPLOY\.md$|nginx\.conf)/;
function sendFile(req, res, file) {
let st;
try { st = statSync(file); } catch { notFound(res); return; }
if (st.isDirectory()) { notFound(res); return; }
const etag = `W/"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
const headers = {
'Content-Type': TYPES[extname(file).toLowerCase()] || 'application/octet-stream',
// 页面、脚本、样式每次确认是否更新(发新版后刷新就能拿到);模型和图片缓存 7 天
'Cache-Control': LONG_CACHE.test(file) ? 'public, max-age=604800' : 'no-cache',
ETag: etag,
'Last-Modified': st.mtime.toUTCString(),
Vary: 'Accept-Encoding',
};
if (req.headers['if-none-match'] === etag) { res.writeHead(304, headers).end(); return; }
if (req.method === 'HEAD') { res.writeHead(200, { ...headers, 'Content-Length': st.size }).end(); return; }
if (COMPRESS.test(file) && st.size > 1024 && /\bgzip\b/.test(req.headers['accept-encoding'] || '')) {
res.writeHead(200, { ...headers, 'Content-Encoding': 'gzip' });
createReadStream(file).pipe(zlib.createGzip({ level: 6 })).pipe(res);
return;
}
res.writeHead(200, { ...headers, 'Content-Length': st.size });
createReadStream(file).pipe(res);
}
function notFound(res) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Not found');
}
function serveStatic(req, res) {
const url = new URL(req.url, 'http://x');
// 旧地址 xxx.html 跳到新地址
const old = url.pathname.match(/^\/(index|explore|studio|cad|pcb|project|workspace)\.html$/);
if (old) {
let to = old[1] === 'index' ? '/' : `/${old[1]}`;
res.writeHead(301, { Location: `${to}/${url.search}` }).end();
return;
}
const page = pageFor(url.pathname);
if (page) {
// 源码目录里是 studio.html;打包后的 dist 里是 studio/index.html
const flat = join(ROOT, page);
sendFile(req, res, existsSync(flat) ? flat : join(ROOT, page.replace(/\.html$/, ''), 'index.html'));
return;
}
let path;
try { path = decodeURIComponent(url.pathname); } catch { notFound(res); return; }
const file = normalize(join(ROOT, path));
if (!file.startsWith(ROOT + sep) || HIDDEN.test(path.slice(1))) { notFound(res); return; }
sendFile(req, res, file);
}
http.createServer((req, res) => {
if (req.url === '/api' || req.url.startsWith('/api/')) proxy(req, res);
else if (req.url.startsWith(`${MODEL_ASSET_ROUTE}/`)) proxyModelAsset(req, res);
else if (req.method === 'GET' || req.method === 'HEAD') serveStatic(req, res);
else res.writeHead(405).end();
}).listen(PORT, () => {
console.log(`vibemake 已启动 端口 ${PORT} 页面目录 ${ROOT}`);
console.log(` dev-* / localhost / 127.0.0.1 / 局域网 /api → ${process.env.API_TARGET || API_DEV}`);
console.log(` 其他域名(正式) /api → ${process.env.API_TARGET || API_PROD}`);
console.log(` 本地:http://localhost:${PORT}(后端数据) http://127.0.0.1:${PORT}(本地演示数据)`);
});