// ==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(); })();