257 lines
14 KiB
JavaScript
257 lines
14 KiB
JavaScript
// 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:8091
|
||
// 线上浏览器直接请求后端域名(见 js/api.js 的 API_HOSTS),这里的域名判断只用于本地调试
|
||
// 环境变量:PORT 端口(默认 8091);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 { spawn } from 'node:child_process';
|
||
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';
|
||
import { readCadEngine, cadWorker } from './cad-engine.mjs';
|
||
|
||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||
const ROOT = resolve(process.env.SITE_ROOT || (basename(HERE) === 'scripts' ? join(HERE, '..') : HERE));
|
||
const CAD_ENGINE_SOURCE = process.env.VIBEMAKE_CAD_ENGINE_DIST || (existsSync(join(ROOT, 'cad/engine.json')) ? join(ROOT, 'cad') : null);
|
||
const CAD_ENGINE = CAD_ENGINE_SOURCE ? readCadEngine(CAD_ENGINE_SOURCE) : null;
|
||
const PORT = Number(process.env.PORT || 8091);
|
||
const PCB_APP_ROOT = resolve(process.env.PCB_APP_ROOT || join(ROOT, '../ziro-designer-main/designer'));
|
||
const PCB_DEV_TARGET = process.env.PCB_DEV_TARGET === 'off'
|
||
? null
|
||
: process.env.PCB_DEV_TARGET
|
||
? new URL(process.env.PCB_DEV_TARGET)
|
||
: !process.env.SITE_ROOT && existsSync(join(PCB_APP_ROOT, 'package.json'))
|
||
? new URL('http://127.0.0.1:5173')
|
||
: null;
|
||
let pcbDevProcess = null;
|
||
const PCB_API_MODE = process.env.PCB_API_MODE || 'real';
|
||
if (!['real', 'mock'].includes(PCB_API_MODE)) throw new Error('PCB_API_MODE must be real or mock');
|
||
if (PCB_DEV_TARGET && !process.env.PCB_DEV_TARGET && process.env.PCB_DEV !== 'off') {
|
||
const vite = join(PCB_APP_ROOT, 'node_modules/vite/bin/vite.js');
|
||
if (existsSync(vite)) {
|
||
pcbDevProcess = spawn(process.execPath, [vite, '--mode', PCB_API_MODE === 'mock' ? 'mock' : 'development', '--host', '127.0.0.1', '--strictPort'], {
|
||
cwd: PCB_APP_ROOT,
|
||
stdio: 'inherit',
|
||
env: { ...process.env, VITE_PCB_API_MODE: PCB_API_MODE },
|
||
});
|
||
} else {
|
||
console.warn(`PCB Vite dependency not found at ${vite}; /pcb/ proxy will fail until it is installed.`);
|
||
}
|
||
}
|
||
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);
|
||
});
|
||
const archive = /^\/api\/workspace\/projects\/[^/]+\/archive(?:\?|$)/.test(req.url);
|
||
upstream.setTimeout(archive ? 400_000 : 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);
|
||
}
|
||
|
||
function isPcbRoute(pathname) {
|
||
return pathname === '/pcb' || pathname.startsWith('/pcb/');
|
||
}
|
||
|
||
function proxyPcb(req, res) {
|
||
const target = PCB_DEV_TARGET;
|
||
const { connection, host, origin, ...headers } = req.headers;
|
||
const upstream = http.request({
|
||
hostname: target.hostname,
|
||
port: target.port || 80,
|
||
method: req.method,
|
||
path: req.url,
|
||
headers: { ...headers, host: target.host, ...(origin ? { origin: target.origin } : {}) },
|
||
}, (response) => {
|
||
res.writeHead(response.statusCode, response.headers);
|
||
response.pipe(res);
|
||
});
|
||
upstream.on('error', (error) => {
|
||
if (res.headersSent) {
|
||
res.destroy();
|
||
return;
|
||
}
|
||
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
||
res.end(`PCB development server unavailable at ${target.origin}: ${error.code || error.message}`);
|
||
});
|
||
res.on('close', () => { if (!res.writableFinished) upstream.destroy(); });
|
||
req.pipe(upstream);
|
||
}
|
||
|
||
// ---------- 页面路由 ----------
|
||
const PAGES = { '/': 'index.html', '/explore': 'explore.html', '/studio': 'studio.html', '/cad': 'cad.html', '/cad/editor': 'cad/editor/index.html', '/pcb': 'pcb/index.html', '/workspace': 'workspace.html' };
|
||
function pageFor(pathname) {
|
||
pathname = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname; // /explore/ 和 /explore 一样
|
||
if (pathname === '/cad' && existsSync(join(ROOT, 'cad/index.html'))) return 'cad/index.html';
|
||
return PAGES[pathname]
|
||
|| (/^\/pcb(?:\/.*)?$/.test(pathname) && !extname(pathname) && 'pcb/index.html')
|
||
|| (/^\/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': /[\/]cad[\/]_assets[\/]/.test(file) || (CAD_ENGINE && file.startsWith(join(CAD_ENGINE.root, '_assets') + sep)) ? 'public, max-age=31536000, immutable' : 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');
|
||
if (CAD_ENGINE && url.pathname === '/cad/sw.js') {
|
||
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-cache' });
|
||
return res.end(cadWorker(CAD_ENGINE.manifest));
|
||
}
|
||
// 旧地址 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;
|
||
}
|
||
if (CAD_ENGINE && (url.pathname === '/cad/engine.json' || url.pathname.startsWith('/cad/_assets/'))) {
|
||
const known = url.pathname === '/cad/engine.json' || CAD_ENGINE.manifest.files.some((entry) => entry.path === url.pathname);
|
||
if (!known) return notFound(res);
|
||
return sendFile(req, res, join(CAD_ENGINE.root, url.pathname.slice('/cad/'.length)));
|
||
}
|
||
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);
|
||
}
|
||
|
||
const server = 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 (PCB_DEV_TARGET && isPcbRoute(new URL(req.url, 'http://localhost').pathname)) proxyPcb(req, res);
|
||
else if (req.method === 'GET' || req.method === 'HEAD') serveStatic(req, res);
|
||
else res.writeHead(405).end();
|
||
});
|
||
server.on('upgrade', (req, socket, head) => {
|
||
const pathname = new URL(req.url, 'http://localhost').pathname;
|
||
if (!PCB_DEV_TARGET || !isPcbRoute(pathname)) {
|
||
socket.destroy();
|
||
return;
|
||
}
|
||
const upstream = http.request({
|
||
hostname: PCB_DEV_TARGET.hostname,
|
||
port: PCB_DEV_TARGET.port || 80,
|
||
path: req.url,
|
||
headers: { ...req.headers, host: PCB_DEV_TARGET.host, origin: PCB_DEV_TARGET.origin },
|
||
});
|
||
upstream.on('upgrade', (response, upstreamSocket, upstreamHead) => {
|
||
socket.write(`HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n`);
|
||
for (let i = 0; i < response.rawHeaders.length; i += 2)
|
||
socket.write(`${response.rawHeaders[i]}: ${response.rawHeaders[i + 1]}\r\n`);
|
||
socket.write('\r\n');
|
||
if (head.length) upstreamSocket.write(head);
|
||
if (upstreamHead.length) socket.write(upstreamHead);
|
||
upstreamSocket.pipe(socket);
|
||
socket.pipe(upstreamSocket);
|
||
upstreamSocket.on('error', () => socket.destroy());
|
||
upstreamSocket.on('close', () => socket.destroy());
|
||
socket.on('error', () => upstreamSocket.destroy());
|
||
socket.on('close', () => upstreamSocket.destroy());
|
||
});
|
||
upstream.on('response', (response) => {
|
||
socket.end(`HTTP/${response.httpVersion} ${response.statusCode} ${response.statusMessage}\r\n\r\n`);
|
||
});
|
||
upstream.on('error', () => socket.destroy());
|
||
socket.on('error', () => upstream.destroy());
|
||
socket.on('close', () => upstream.destroy());
|
||
upstream.end();
|
||
});
|
||
server.listen(PORT, () => {
|
||
console.log(`vibemake 已启动 端口 ${PORT} 页面目录 ${ROOT}`);
|
||
if (PCB_DEV_TARGET) console.log(` /pcb/ → ${PCB_DEV_TARGET.origin}(${PCB_API_MODE === 'mock' ? '开发模拟' : '真实接口'}模式,同源代理)`);
|
||
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}(本地演示数据)`);
|
||
});
|
||
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||
process.once(signal, () => {
|
||
pcbDevProcess?.kill(signal);
|
||
server.close(() => process.exit(0));
|
||
});
|
||
}
|