#!/usr/bin/env node /** * 云学堂自动刷课 · 本地开发服务器 * * 作用:把工作目录里的 yun-xue-tang-assistant.user.js 暴露给浏览器里的 * Tampermonkey 热加载器(dev/dev-loader.user.js)拉取。 * * 端点: * GET / 说明页 * GET /src 最新脚本源码(no-store) * GET /version { hash, size, mtime },热加载器靠 hash 判断是否变更 * GET /loader.user.js 热加载器本体(用于安装) * * 用法:node dev/serve.mjs [端口] 默认端口 8899 */ import http from 'node:http'; import path from 'node:path'; import crypto from 'node:crypto'; import { readFile, stat } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; const HERE = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(HERE, '..'); const HOST = '127.0.0.1'; const PORT = Number(process.env.YT_DEV_PORT || process.argv[2] || 8899); const FILES = { '/src': path.join(ROOT, 'yun-xue-tang-assistant.user.js'), '/loader.user.js': path.join(HERE, 'dev-loader.user.js'), }; const BASE = `http://${HOST}:${PORT}`; function hashOf(buf) { return crypto.createHash('sha1').update(buf).digest('hex').slice(0, 12); } function send(res, status, body, type, origin) { const headers = { 'Content-Type': type || 'text/plain; charset=utf-8', 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0', Pragma: 'no-cache', 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS', 'X-Content-Type-Options': 'nosniff', }; // 只放行云学堂页面(Tampermonkey 的 GM_xmlhttpRequest 本来也不受 CORS 限制, // 这里拒绝其它站点读取是为了别让随便哪个网页都能拉到你的脚本) if (origin && /^https?:\/\/([a-z0-9-]+\.)*yunxuetang\.cn(:\d+)?$/i.test(origin)) { headers['Access-Control-Allow-Origin'] = origin; headers.Vary = 'Origin'; } res.writeHead(status, headers); res.end(body); } function indexHtml() { return `YXT Assistant · 本地开发服务

云学堂自动刷课 · 本地开发服务 运行中

源码文件:${path.join(ROOT, 'yun-xue-tang-assistant.user.js')}

改完源码保存后,浏览器页面约 1 秒内自动热替换,无需刷新、无需重装脚本。

`; } const server = http.createServer(async (req, res) => { const url = new URL(req.url, BASE); const route = url.pathname.replace(/\/+$/, '') || '/'; const origin = req.headers.origin || ''; const reply = (status, body, type) => send(res, status, body, type, origin); if (req.method === 'OPTIONS') return reply(204, ''); if (route === '/favicon.ico') return reply(204, ''); if (route === '/') { return reply(200, indexHtml(), 'text/html; charset=utf-8'); } if (route === '/version') { try { const file = FILES['/src']; const [buf, st] = await Promise.all([readFile(file), stat(file)]); const body = JSON.stringify({ hash: hashOf(buf), size: buf.length, mtime: st.mtimeMs, at: Date.now(), }); return reply(200, body, 'application/json; charset=utf-8'); } catch (e) { return reply(500, JSON.stringify({ error: String(e.message || e) }), 'application/json; charset=utf-8'); } } const file = FILES[route]; if (file) { try { const buf = await readFile(file); const type = route === '/src' ? 'application/javascript; charset=utf-8' : 'text/plain; charset=utf-8'; if (route === '/src') { console.log(`[${time()}] /src ${buf.length}B ${hashOf(buf)}`); } return reply(200, buf, type); } catch (e) { console.error(`[${time()}] ${route} 读取失败: ${e.message}`); return reply(500, `读取失败: ${e.message}`); } } return reply(404, 'not found: ' + route); }); function time() { return new Date().toLocaleTimeString('zh-CN', { hour12: false }); } server.listen(PORT, HOST, () => { console.log(''); console.log(' YXT Assistant · 本地开发服务已启动'); console.log(' ------------------------------------'); console.log(` 脚本源码 : ${FILES['/src']}`); console.log(` 热加载器 : ${BASE}/loader.user.js`); console.log(` 版本接口 : ${BASE}/version`); console.log(` 首页 : ${BASE}/`); console.log(' ------------------------------------'); console.log(' 保持本窗口开启;关闭窗口 = 停止服务。'); console.log(''); }); server.on('error', (e) => { if (e.code === 'EADDRINUSE') { console.error(`端口 ${PORT} 已被占用。可能服务已在运行,或用 "node dev/serve.mjs 8900" 换端口。`); } else { console.error('服务启动失败:', e); } process.exit(1); }); for (const sig of ['SIGINT', 'SIGTERM']) { process.on(sig, () => { console.log('\n服务已停止。'); server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 1500).unref(); }); }