chore: 初始化仓库并清理项目
- 新增 .gitignore / .gitattributes:忽略 .run-tmp、依赖与系统/编辑器文件,统一换行符 - 删除 .run-tmp(约 460 MB 浏览器配置目录与一次性调试脚本), 将实跑报告引用的日志与截图移入 docs/evidence、docs/screenshots - 新增根 README(安装、配置、开发、隐私与已知限制)与 package.json(npm run dev / check) - 整理 courseTick 步骤编号,移除未使用的 CFG.resumeOnPause / CFG.nextDelayMs - 修正热加载器描述与实跑报告中的旧文件名、失效的 .run-tmp 链接
This commit is contained in:
commit
7d6493bca5
22 files changed
+2991
No files matched your search
@@ -0,0 +1,55 @@
|
||||
# 开发热加载(保存即生效)
|
||||
|
||||
目标:在编辑器里改 `yun-xue-tang-assistant.user.js`,保存后浏览器里的脚本自动换成新版本,
|
||||
**不用复制粘贴、不用重装、不用刷新页面**。
|
||||
|
||||
## 结构
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `../yun-xue-tang-assistant.user.js` | 业务脚本本体(唯一需要修改的文件) |
|
||||
| `serve.mjs` | 本地 HTTP 服务,向浏览器提供源码与版本哈希(127.0.0.1:8899) |
|
||||
| `dev-loader.user.js` | Tampermonkey 里的薄加载器,轮询版本、释放旧实例、注入新实例 |
|
||||
| `start-dev.cmd` | 双击启动服务 |
|
||||
|
||||
原理:加载器每 1 秒请求 `/version`,发现哈希变化就调用旧实例暴露的
|
||||
`window.__ytDispose()`(清定时器 / 监听器 / 面板),再把新源码以 `<script>` 形式注入页面主世界。
|
||||
因为脚本依赖页面里的 `__vue__`(登录组件),注入必须发生在主世界,不能走普通沙箱。
|
||||
|
||||
## 一次性安装
|
||||
|
||||
1. 双击 `dev/start-dev.cmd` 启动本地服务(保持窗口开着)。
|
||||
2. 浏览器打开 <http://127.0.0.1:8899/>,点「安装 / 更新热加载器」,Tampermonkey 弹窗确认安装。
|
||||
> 手动方式:Tampermonkey 面板 → 添加新脚本 → 粘贴 `dev/dev-loader.user.js` 全文 → 保存。
|
||||
3. **停用或删除** Tampermonkey 里原来那份「云学堂助手」完整脚本。
|
||||
(两份同时跑会出现两个面板、双份定时器,行为会乱。)
|
||||
4. 打开 <https://kfmic.yunxuetang.cn/login.html>,F12 控制台应看到:
|
||||
`[云学堂·热加载] 已注入 xxxxx 字节源码`。
|
||||
|
||||
## 日常使用
|
||||
|
||||
- 改完 `yun-xue-tang-assistant.user.js` 直接保存 → 约 1 秒内页面控制台打印
|
||||
`[云学堂·热加载] 热更新 → <新哈希>`,面板会重建,视频播放不中断。
|
||||
- 批量刷课的进度存在 `localStorage`(`yt-batch-v2`),热替换 / 刷新都不会丢。
|
||||
- 改坏了(语法错误):加载器会拒绝注入并弹出左下角红条提示,**旧版本继续运行**,修好再保存即可。
|
||||
- 想完全回到「手动刷新才生效」:把加载器里的 `MODE` 改成 `'reload'`。
|
||||
|
||||
## 常见问题
|
||||
|
||||
| 现象 | 处理 |
|
||||
| --- | --- |
|
||||
| 左下角红条「未连上本地开发服务」 | 服务没启动,或端口被占用;运行 `dev/start-dev.cmd` |
|
||||
| 改完没反应 | 看控制台是否有 `热更新` 日志;确认改的是工作目录里的那份文件 |
|
||||
| 页面出现两个面板 | 旧完整脚本没停用,去 Tampermonkey 停用它 |
|
||||
| 端口冲突 | `node dev/serve.mjs 8900`,同时把加载器里的 `SERVER` 常量改成对应端口 |
|
||||
| 服务没开也想用 | 加载器回退到上次缓存的源码(`GM_getValue('yt-dev-src')`) |
|
||||
|
||||
## 关闭开发模式
|
||||
|
||||
停用热加载器 + 重新安装一次完整脚本(把 `.user.js` 全文粘进 Tampermonkey)即可。
|
||||
脚本本身不依赖任何本地服务,`@grant none`,可独立运行。
|
||||
|
||||
## 开机自启(可选)
|
||||
|
||||
把 `dev/start-dev.cmd` 的快捷方式放进
|
||||
`%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup`,开机即后台常驻。
|
||||
@@ -0,0 +1,215 @@
|
||||
// ==UserScript==
|
||||
// @name 云学堂助手 · 开发热加载器
|
||||
// @namespace yxt.assistant.local
|
||||
// @version 1.0.0
|
||||
// @description 从本机 http://127.0.0.1:8899 拉取 yun-xue-tang-assistant.user.js,保存文件后约 1 秒内自动热替换,免复制粘贴
|
||||
// @author local
|
||||
// @match *://*.yunxuetang.cn/*
|
||||
// @grant GM_xmlhttpRequest
|
||||
// @grant GM_getValue
|
||||
// @grant GM_setValue
|
||||
// @grant unsafeWindow
|
||||
// @connect 127.0.0.1
|
||||
// @connect localhost
|
||||
// @run-at document-idle
|
||||
// ==/UserScript==
|
||||
|
||||
/*
|
||||
* 这是「开发期」用的薄加载器,本身不含业务逻辑:
|
||||
* 1. 页面加载时从本地开发服务拉取最新源码并注入页面主世界;
|
||||
* 2. 每 1 秒问一次 /version,哈希变了就「先释放旧实例、再注入新实例」;
|
||||
* 3. 服务没开时回退到上一次缓存的源码,保证照常可用;
|
||||
* 4. 新源码语法错误时拒绝注入,旧实例继续运行(不会把页面搞挂)。
|
||||
*
|
||||
* 依赖:先运行 dev/start-dev.cmd(或 node dev/serve.mjs)启动本地服务。
|
||||
* 生效方式:MODE = 'hot' 不刷新页面;'reload' 变更后整页刷新。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const SERVER = 'http://127.0.0.1:8899';
|
||||
const MODE = 'hot'; // 'hot' | 'reload'
|
||||
const POLL_MS = 1000; // 轮询间隔
|
||||
const RETRY_MS = 15000; // 服务不可用时的重试间隔
|
||||
const CACHE_KEY = 'yt-dev-src'; // 最近一次成功拉取的源码
|
||||
const TAG = '[云学堂·热加载]';
|
||||
const isTop = (function () {
|
||||
try { return window.top === window.self; } catch (e) { return true; }
|
||||
})();
|
||||
|
||||
const page = (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window;
|
||||
|
||||
let appliedHash = '';
|
||||
let failures = 0;
|
||||
let timer = 0;
|
||||
|
||||
// ---------- 网络 ----------
|
||||
function httpGet(url, timeoutMs) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
if (typeof GM_xmlhttpRequest !== 'function') {
|
||||
reject(new Error('GM_xmlhttpRequest 不可用(请检查脚本授权)'));
|
||||
return;
|
||||
}
|
||||
GM_xmlhttpRequest({
|
||||
method: 'GET',
|
||||
url: url + (url.indexOf('?') < 0 ? '?' : '&') + '_=' + Date.now(),
|
||||
timeout: timeoutMs || 8000,
|
||||
headers: { 'Cache-Control': 'no-cache', Pragma: 'no-cache' },
|
||||
onload: function (r) {
|
||||
if (r.status >= 200 && r.status < 300) resolve(r.responseText || '');
|
||||
else reject(new Error('HTTP ' + r.status));
|
||||
},
|
||||
onerror: function () { reject(new Error('无法连接 ' + SERVER)); },
|
||||
ontimeout: function () { reject(new Error('请求超时')); },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 注入 ----------
|
||||
function syntaxErrorOf(src) {
|
||||
try {
|
||||
new Function(src); // 只编译不执行,用来提前发现语法错误
|
||||
return null;
|
||||
} catch (e) {
|
||||
if (e && e.name === 'SyntaxError') return e;
|
||||
return null; // 环境不允许 eval 时跳过校验
|
||||
}
|
||||
}
|
||||
|
||||
function disposePrevious() {
|
||||
try {
|
||||
if (page && typeof page.__ytDispose === 'function') {
|
||||
page.__ytDispose();
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(TAG, '旧实例释放失败', e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function inject(src) {
|
||||
const el = document.createElement('script');
|
||||
el.type = 'text/javascript';
|
||||
el.setAttribute('data-yt-dev-injected', '1');
|
||||
el.textContent = src;
|
||||
(document.head || document.documentElement).appendChild(el);
|
||||
el.remove();
|
||||
}
|
||||
|
||||
function apply(src) {
|
||||
if (!src || src.length < 500) {
|
||||
console.error(TAG, '拉到的源码异常(长度 ' + String(src && src.length) + '),已忽略');
|
||||
return false;
|
||||
}
|
||||
const err = syntaxErrorOf(src);
|
||||
if (err) {
|
||||
console.error(TAG, '新源码有语法错误,保留旧实例:', err);
|
||||
badge('新代码语法错误:' + err.message);
|
||||
return false;
|
||||
}
|
||||
|
||||
const hadInstance = !!(page && (page.__ytAuto || document.getElementById('yt-auto-panel')));
|
||||
const disposed = disposePrevious();
|
||||
// 首次注入不存在旧实例,直接注入;之后若旧实例没有 __ytDispose 或指定了 reload 模式,才刷新整页
|
||||
if (hadInstance && (MODE === 'reload' || !disposed)) {
|
||||
console.log(TAG, MODE === 'reload' ? '源码变更,刷新页面' : '旧实例无 __ytDispose,刷新页面');
|
||||
location.reload();
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
inject(src);
|
||||
GM_setValue(CACHE_KEY, src);
|
||||
clearBadge();
|
||||
console.log(TAG, '已注入 ' + src.length + ' 字节源码');
|
||||
if (isTop && !page.__ytAuto && !document.getElementById('yt-auto-panel')) {
|
||||
// 站点 CSP 若禁掉 inline script,退一步用页面主世界的 eval(需要 unsafe-eval)
|
||||
try { page.eval(src); } catch (e) { /* 两种方式都不行再看下一条 */ }
|
||||
if (!page.__ytAuto && !document.getElementById('yt-auto-panel')) {
|
||||
badge('源码已注入但未生效:页面 CSP 可能拦截了注入,请查看控制台');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error(TAG, '注入失败:', e);
|
||||
badge('注入失败:' + (e && e.message ? e.message : e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 失败提示 ----------
|
||||
let badgeEl = null;
|
||||
function badge(msg) {
|
||||
if (!isTop) return;
|
||||
try {
|
||||
if (!badgeEl) {
|
||||
badgeEl = document.createElement('div');
|
||||
badgeEl.style.cssText = [
|
||||
'position:fixed', 'left:12px', 'bottom:12px', 'z-index:2147483647',
|
||||
'background:#7d2f2f', 'color:#fff', 'padding:6px 10px', 'border-radius:6px',
|
||||
'font:12px/1.5 system-ui,"Microsoft YaHei",sans-serif', 'max-width:420px',
|
||||
'box-shadow:0 4px 14px rgba(0,0,0,.35)', 'white-space:pre-wrap',
|
||||
].join(';');
|
||||
document.body.appendChild(badgeEl);
|
||||
}
|
||||
badgeEl.textContent = TAG + ' ' + msg;
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
function clearBadge() {
|
||||
if (badgeEl && badgeEl.parentNode) badgeEl.parentNode.removeChild(badgeEl);
|
||||
badgeEl = null;
|
||||
}
|
||||
|
||||
// ---------- 轮询 ----------
|
||||
function schedule(ms) {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(poll, ms || (failures ? RETRY_MS : POLL_MS));
|
||||
}
|
||||
|
||||
function poll() {
|
||||
httpGet(SERVER + '/version', 4000).then(function (body) {
|
||||
failures = 0;
|
||||
let v;
|
||||
try { v = JSON.parse(body); } catch (e) { return; }
|
||||
if (!v || !v.hash || v.hash === appliedHash) return;
|
||||
return httpGet(SERVER + '/src').then(function (src) {
|
||||
if (apply(src)) {
|
||||
appliedHash = v.hash;
|
||||
console.log(TAG, '热更新 → ' + v.hash);
|
||||
} else {
|
||||
appliedHash = v.hash; // 坏版本不再反复重试,修好后再变哈希
|
||||
}
|
||||
});
|
||||
}).catch(function (e) {
|
||||
failures++;
|
||||
if (failures === 1) console.warn(TAG, '开发服务不可用,稍后重试:', e.message);
|
||||
}).then(function () {
|
||||
schedule();
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 启动 ----------
|
||||
function boot() {
|
||||
httpGet(SERVER + '/version', 3000).then(function (body) {
|
||||
const v = JSON.parse(body);
|
||||
return httpGet(SERVER + '/src').then(function (src) {
|
||||
appliedHash = v.hash || '';
|
||||
return apply(src);
|
||||
});
|
||||
}).catch(function (e) {
|
||||
const cached = GM_getValue(CACHE_KEY, '');
|
||||
if (cached) {
|
||||
console.warn(TAG, '开发服务不可用,使用缓存源码:', e.message);
|
||||
apply(cached);
|
||||
} else {
|
||||
console.error(TAG, '开发服务不可用且无缓存。请先运行 dev/start-dev.cmd');
|
||||
badge('未连上本地开发服务(' + SERVER + ')\n请运行 dev/start-dev.cmd');
|
||||
}
|
||||
}).then(function () {
|
||||
if (isTop) schedule(POLL_MS);
|
||||
});
|
||||
}
|
||||
|
||||
boot();
|
||||
})();
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#!/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 `<!doctype html><meta charset="utf-8"><title>YXT Assistant · 本地开发服务</title>
|
||||
<style>body{font:14px/1.7 system-ui,"Microsoft YaHei";max-width:760px;margin:40px auto;padding:0 16px;color:#222}
|
||||
code{background:#f2f2f4;padding:1px 5px;border-radius:4px}a{color:#2f7d5b}
|
||||
.ok{color:#2f7d5b;font-weight:600}</style>
|
||||
<h2>云学堂自动刷课 · 本地开发服务 <span class="ok">运行中</span></h2>
|
||||
<p>源码文件:<code>${path.join(ROOT, 'yun-xue-tang-assistant.user.js')}</code></p>
|
||||
<ul>
|
||||
<li><a href="/loader.user.js">安装 / 更新热加载器</a>(Tampermonkey 会弹出安装页)</li>
|
||||
<li><a href="/src">查看当前源码</a></li>
|
||||
<li><a href="/version">版本哈希</a></li>
|
||||
</ul>
|
||||
<p>改完源码保存后,浏览器页面约 1 秒内自动热替换,无需刷新、无需重装脚本。</p>`;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
cd /d "%~dp0.."
|
||||
title YXT Cruise · 本地开发服务
|
||||
where node >nul 2>nul
|
||||
if errorlevel 1 (
|
||||
echo 未找到 node.exe,请先安装 Node.js(https://nodejs.org/)
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
node "%~dp0serve.mjs" %*
|
||||
if errorlevel 1 pause
|
||||
Reference in new issue
Block a user