'use strict'; // 新版界面(web/dist 的生产构建)挂在 /next/ 下:试用、演示模式默认开启;云端仅在 WEB_NEXT=1 时开启。 // 带扩展名的路径按资源文件查找,找不到就 404;其余 /next、/next/* 一律返回 index.html(单页应用回退)。 // 路径解码后必须仍落在 web/dist 之内,否则按未知地址 404。 const fs = require('node:fs'); const path = require('node:path'); const { fail } = require('../../core/ledger'); const DIST_DIR = path.join(__dirname, '..', '..', 'web', 'dist'); const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.mjs': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.txt': 'text/plain; charset=utf-8', '.map': 'application/json; charset=utf-8', }; const isNextPath = pathname => pathname === '/next' || pathname.startsWith('/next/'); function webNextEnabled(app) { return app.mode === 'demo' || app.mode === 'trial' || process.env.WEB_NEXT === '1'; } function readFile(file) { try { const stat = fs.statSync(file); return stat.isFile() ? fs.readFileSync(file) : null; } catch { return null; } } function serveWebNext(res, pathname, isPost, { distDir = DIST_DIR } = {}) { if (isPost) fail('地址不存在', 404); let relative; try { relative = decodeURIComponent(pathname.slice('/next'.length)); } catch { fail('地址不存在', 404); } if (relative.includes('\0') || relative.includes('\\')) fail('地址不存在', 404); const root = path.resolve(distDir); const target = path.resolve(root, '.' + path.posix.normalize('/' + relative)); if (target !== root && !target.startsWith(root + path.sep)) fail('地址不存在', 404); const last = relative.split('/').pop(); const asset = last.includes('.'); const file = asset ? target : path.join(root, 'index.html'); const type = TYPES[path.extname(file).toLowerCase()]; const body = type ? readFile(file) : null; if (!body) fail('地址不存在', 404); // 直接写出原始字节:通用 send() 会把 JSON 类型的内容再序列化一次。 res.writeHead(200, { 'Content-Type': type }); res.end(body); } module.exports = { serveWebNext, webNextEnabled, isNextPath, DIST_DIR };