// ==UserScript== // @name GitHub 中文化 + 高速下载加速(多节点自动测速) // @namespace https://github.com/gh-accelerator/userscript // @version 1.2.0 // @description GitHub 界面汉化,并把 release / archive / raw / gist 等文件链接套上国内加速节点。内置 80+ 公益节点,自动测速择优,release 资产与源码包处注入「加速下载」按钮。 // @author gh-accelerator + maboloshi(汉化词库与逻辑) // @copyright https://261998.xyz // @icon https://github.githubassets.com/favicons/favicon.svg // @license GPL-3.0 // @match https://github.com/* // @match https://gist.github.com/* // @match https://skills.github.com/* // @match https://education.github.com/* // @match https://www.githubstatus.com/* // @require https://mirror.nju.edu.cn/github-chinese/locals.js?v=2026-11-15 // @grant GM.xmlHttpRequest // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_setClipboard // @grant GM_notification // @grant GM_addStyle // @grant CAT_userConfig // @grant window.onurlchange // @connect * // @run-at document-start // @noframes // @supportURL https://github.com/maboloshi/github-chinese/issues // ==/UserScript== /* ==UserConfig== 加速设置: 开关: title: 启用下载加速 description: 关闭后不再改写链接、不再注入按钮(界面汉化不受影响) type: switch default: true 模式: title: 选节点方式 description: auto 自动测速择优;manual 固定用下面填的节点 type: select default: auto values: [auto, manual] 指定节点: title: 手动模式使用的节点 description: 仅 manual 模式生效,填前缀域名,例如 https://gh-proxy.com type: text default: https://gh-proxy.com 自动测速: title: 打开页面时自动测速 description: 关闭则沿用上次结果(缓存 6 小时) type: checkbox default: true 测速超时: title: 单节点测速超时 type: number default: 8 min: 3 max: 30 unit: 秒 包含失效节点: title: 测速时也试已知失效的节点 description: 默认跳过,换网络环境或节点恢复后可打开 type: checkbox default: false 注入按钮: title: 注入「加速下载」按钮 type: checkbox default: true 改写链接: title: 改写页面上文件链接的地址 description: 开启后直接点 GitHub 原生下载按钮也会走加速 type: checkbox default: true 高级: 并发测速数: title: 同时探测的节点数量 type: number default: 8 min: 1 max: 16 保留结果数: title: 测速结果保留多少个节点 type: number default: 20 min: 3 max: 80 ==/UserConfig== */ /* 说明:本文件包含两个互相独立的模块。 * 模块一 = GitHub 界面汉化(逻辑与词库来自 maboloshi/github-chinese,GPL-3.0) * 模块二 = GitHub 文件下载加速(节点测速 + 链接改写 + 下载按钮) * 两者共用同一份 @grant / @connect 声明,但各自有独立的 IIFE 与状态, * 任一模块出错都不会影响另一个(汉化词库加载失败时只跳过汉化)。 */ /* ================================================================== * 模块一:GitHub 界面汉化 * ================================================================== */ (function (window, document, undefined) { 'use strict'; /* 本脚本另一部分(加速功能)注入的 UI,汉化不碰。 a[data-gha-orig] 是被改写过地址的 GitHub 链接:它的 title 是加速功能写的说明, 链接文字是文件名(本来就不该翻译),整体跳过最干净。 */ const SKIP_SELECTORS = '.gha-btn, .gha-card, .gha-toast, .gha-float, a[data-gha-orig]'; /* =========================== 全局配置常量 =========================== */ const CONFIG = { LANG: 'zh-CN', // 默认语言 DEV: false, // 默认不开启开发者模式 PAGE_MAP: { // 站点域名 -> 类型映射 'gist.github.com': 'gist', 'www.githubstatus.com': 'status', 'skills.github.com': 'skills', 'education.github.com': 'education' }, DESC_SELECTORS: { // 简介元素的CSS选择器 repository: [ // 登录态是独立的 React 组件,类名形如 SidebarAbout-module_xxxx_description, // 不含未登录态的 description__(#811) 'p[class*="SidebarAbout-module_"][class*="_description"]', // 登录态 React UI(issue #811) '[class*="borderGrid__"] p[class*="description__"]', // 未登录/桌面 About 侧栏 ].join(", "), gist: ".gist-content [itemprop='about']" }, OBSERVER_CONFIG: { // MutationObserver配置 childList: true, subtree: true, characterData: true, attributeFilter: ['value', 'placeholder', 'aria-label', 'data-confirm'] }, TRANS_ENGINES: { // 翻译引擎配置 iflyrec: { name: '讯飞听见', url: 'https://fanyi.iflyrec.com/text-translate', url_api: 'https://fanyi.iflyrec.com/TJHZTranslationService/v2/textAutoTranslation', method: 'POST', headers: { 'Content-Type': 'application/json', 'Origin': 'https://fanyi.iflyrec.com' }, getRequestData: (text) => ({ from: 2, // 英语 to: 1, // 简体中文 type: 1, contents: [{ text: text }] }), responseIdentifier: 'biz[0]?.sectionResult[0]?.dst', // 翻译结果在响应中的路径 }, }, STYLES: ` /* 基础样式变量 */ :root { --ghc-primary-color: #1b95e0; --ghc-bg-color: #f8f9fa; --ghc-border-color: #e1e4e8; --ghc-button-bg: #f6f8fa; } /* 浅色主题样式(默认) */ .translate-button { color: var(--ghc-primary-color); font-size: small; cursor: pointer; margin-top: 5px; display: inline-block; } .translation-result { margin-top: 10px; padding: 8px; border: 1px solid var(--ghc-border-color); background-color: var(--ghc-button-bg); border-radius: 6px; } .translation-credit { font-size: small; color: var(--ghc-primary-color); } .translation-content { margin-top: 5px; white-space: pre-wrap; } /* 暗色主题适配 - 使用 prefers-color-scheme */ @media (prefers-color-scheme: dark) { :root { --ghc-primary-color: #58a6ff; --ghc-bg-color: #0d1117; --ghc-border-color: #30363d; --ghc-button-bg: #21262d; } } /* 词库缺失提示条 */ .ghc-notice { position: fixed; right: 16px; bottom: 16px; z-index: 2147483005; max-width: 320px; padding: 10px 14px; border-radius: 8px; background: #161b22; color: #e6edf3; border: 1px solid rgba(255,255,255,.16); box-shadow: 0 8px 28px rgba(0,0,0,.45); cursor: pointer; font: 12px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", sans-serif; } ` }; /* =========================== 状态管理器 =========================== */ const State = { // 功能开关 featureSet: { enable_RegExp: GM_getValue("enable_RegExp", true), enable_transDesc: GM_getValue("enable_transDesc", true), enable_missedTerms: GM_getValue("enable_missedTerms", false), enable_onurlchange: false, }, // 当前运行时状态 pageConfig: null, // 当前页面配置(null 表示无有效页面) currentURL: window.location.href, // 当前页面URL transEngine: 'iflyrec', // 当前翻译引擎 mutationObserver: null, // DOM变化观察器 observedBody: null, // 当前观察的页面主体 visitAction: null, // 当前 Turbo 访问动作:advance / replace / restore idleSweep: null, // 恢复访问时的空闲补扫句柄 urlChangeHandler: null, // 存储URL变化处理器 dynamicMenus: {}, // 动态菜单ID记录 pendingMutations: [], // 一帧内攒下的 mutation 记录 mutationFlush: null, // 已排期的批次处理句柄 lastTraversal: null, // 最近一次全量遍历的 {url, body},避免同一次载入遍历两遍 }; /* =========================== 安全检查 =========================== */ /** * 提示词库缺失(不阻断脚本,加速功能仍可用) */ function showDictMissingNotice() { const show = () => { if (document.querySelector('.ghc-notice')) return; const el = document.createElement('div'); el.className = 'ghc-notice'; el.textContent = 'GitHub 汉化词库(locals.js)加载失败,本次仅启用下载加速。点击关闭。'; el.addEventListener('click', () => el.remove()); document.body.appendChild(el); setTimeout(() => el.remove(), 12000); }; if (document.body) show(); else window.addEventListener('DOMContentLoaded', show, { once: true }); } /** * 检查词库文件是否加载 * 原实现直接 throw,会让同一个文件里的加速功能也一起失效, * 这里改为返回布尔值,由 init() 决定跳过汉化。 * @returns {boolean} 词库是否可用 */ function checkI18NLoaded() { if (typeof I18N === 'undefined') { console.error('[GitHub 中文化插件] 词库文件 locals.js 未加载,本次跳过界面汉化'); showDictMissingNotice(); return false; } return true; } /** * 错误边界 — 包装函数,捕获异常避免阻断页面正常使用 * @param {Function} fn - 要执行的函数 * @param {string} label - 错误标签 * @returns {Function} 包装后的函数 */ function safe(fn, label) { return function (...args) { try { return fn.apply(this, args); } catch (e) { console.error(`[GitHub 中文化插件] ${label} 出错:`, e); } }; } /* =========================== 初始化入口 =========================== */ function init() { if (!checkI18NLoaded()) return; initLangEnv(); injectStyles(); setupMenuCommands(); watchReactCommits(); setupInitTrans(); setupUrlChangeListener(); setupTurboEvents(); } /** * 初始化并保护中文语言环境 */ function initLangEnv() { // 设置初始语言 document.documentElement.lang = CONFIG.LANG; // 监视语言属性变化,防止被改回英文 const langObserver = new MutationObserver(() => { // 如果检测到语言被改回英文,重新设置 if (document.documentElement.lang === "en") { document.documentElement.lang = CONFIG.LANG; } }); langObserver.observe(document.documentElement, { attributeFilter: ['lang'] }); } /** * 注入自定义样式到页面 */ function injectStyles() { GM_addStyle(CONFIG.STYLES); } /** * 设置初始翻译 * * 即使 @run-at document-start,Tampermonkey 注入脚本也可能晚于 DOMContentLoaded *(扩展冷启动、bfcache 恢复等场景)。因此不能假设注册监听器时事件尚未触发: * readyState 已是 interactive/complete 则直接执行,否则才注册一次性监听器。 */ function setupInitTrans() { function doInitTrans() { applyPage('首次载入'); } if (document.readyState === 'interactive' || document.readyState === 'complete') { // 文档已就绪,直接执行 doInitTrans(); } else { // 等待 DOMContentLoaded window.addEventListener('DOMContentLoaded', doInitTrans, { once: true }); } } /* =========================== URL 变化监听 =========================== */ /** * 设置URL变化监听器 * Tampermonkey 环境使用 onurlchange 事件,其他环境回退到 MutationObserver URL 检测 */ function setupUrlChangeListener() { // 合并同一轮历史事件,在当前事件结束后读取最终的 URL 与 body let historyTimer = null; function scheduleHistoryRefresh() { if (historyTimer !== null) clearTimeout(historyTimer); historyTimer = setTimeout(() => { historyTimer = null; handleUrlChange(); }, 0); } // 只处理同文档历史(Turbo/SPA 的 pushState 回退)。 // bfcache 的跨文档恢复不触发 popstate,而且 DOM 与观察器都原样还原, // 缓存里的文字已经是译文——不需要也不应该再全量重翻,故不监听 pageshow。 window.addEventListener('popstate', scheduleHistoryRefresh); // Tampermonkey 环境下 window.onurlchange 为 null(支持),其他环境为 undefined if (State.featureSet.enable_onurlchange && window.onurlchange === null) { // 创建URL变化处理函数 State.urlChangeHandler = function (event) { console.log("URL变化检测 (Tampermonkey onurlchange)", event); handleUrlChange(); }; window.addEventListener('urlchange', State.urlChangeHandler); console.log("🛠️ 开发者模式:已启用 onurlchange 事件监听"); } else { console.log("当前环境不支持 onurlchange 事件,使用传统URL检测方式"); } } /** * 处理URL变化 */ function handleUrlChange() { const currentURL = window.location.href; const sameRoute = currentURL.split('#')[0] === State.currentURL.split('#')[0]; // 同一路由且 body 未更换(含 bfcache 原样恢复):译文与观察器都还在,直接返回。 // 判断依据不是「有没有缓存」,而是 body 是否还是我们观察的那一个: // Turbo 的快照恢复会替换 body(cloneNode 丢弃监听器),那种才需要重新遍历与挂载。 if (sameRoute && document.body === State.observedBody) { State.currentURL = currentURL; return; } handleTurboLoad(); } /* =========================== Turbo 事件 =========================== */ /** * 设置Turbo框架事件监听 * 处理GitHub的Turbolinks页面切换 */ function setupTurboEvents() { // Turbo 的访问动作:advance(点链接)/ replace / restore(前进后退) document.addEventListener('turbo:visit', event => { State.visitAction = event.detail?.action || null; }); // 新 body 还没插入文档时就把观察器挂上去: // React 水合把译文写回英文的那批变更,从第一帧就被接住 document.addEventListener('turbo:before-render', event => { const newBody = event.detail?.newBody; if (newBody) attachMutationObserver(newBody); }); document.addEventListener('turbo:render', () => handleTurboLoad()); document.addEventListener('turbo:load', () => { handleTurboLoad(); State.visitAction = null; }); } /** * 恢复访问不必同步全量遍历:缓存快照里已经是译文, * 水合回写的英文由预挂的观察器接住;再安排一次空闲补扫, * 兜住「离开时还没翻完」的快照,同时不阻塞渲染。 */ function scheduleIdleTraversal() { if (State.idleSweep !== null) return; const run = () => { State.idleSweep = null; // 等空闲期间又换页了:新导航已经负责过,别再扫一遍 if (State.observedBody !== document.body) return; traversePage('恢复补扫'); }; if (typeof window.requestIdleCallback === 'function') { State.idleSweep = window.requestIdleCallback(run, { timeout: 1500 }); } else { State.idleSweep = setTimeout(run, 200); } } /** * 页面载入 / 导航时挂描述翻译按钮(非 React 页面,如 gist)。 * * GitHub 仓库页同时渲染窄屏(NarrowOnly)与桌面侧栏(HideWhenNarrow)两份 About 描述, * 由 CSS 决定显示哪一份;两份都要挂,否则宽屏没有按钮。 * 仓库页不在这里挂:SSR 树还没被 React 接管,插入节点会触发 hydration mismatch, * 由 watchReactCommits 在 React 提交之后挂。 */ function mountDescButton() { if (!State.featureSet.enable_transDesc) return; const descSelector = CONFIG.DESC_SELECTORS[State.pageConfig?.currentPageType]; if (!descSelector) return; transDesc(descSelector); } /** * React 提交之后补挂描述翻译按钮。 * * GitHub 新版 UI 是 SSR HTML + 客户端 React app(React 19,react-core)。 * 载入时往 SSR 描述后面插按钮会造成 hydration mismatch,React 丢弃 SSR 树重渲染,按钮随之消失。 * react-core 在每次 root 提交后记 performance mark(react-root:commit:), * 以这个「提交结束」事件为准,提交后再挂。机制与实测见 docs/github-react.md。 * 浮层 / 下拉里后来渲染的描述不走 root 提交,由突变批次补挂(batchAddedDesc)。 */ function watchReactCommits() { if (typeof PerformanceObserver !== 'function') return; try { // Chromium 不支持 entryTypes + buffered 的组合(控制台会报错), // 且该组合下 buffered 被忽略;只有单个 type 才能回放注册前的 mark。 new PerformanceObserver((list) => { if (list.getEntries().some(entry => entry.name.startsWith('react-root:commit:'))) { safe(mountDescButton, '描述翻译')(); } }).observe({ type: 'mark', buffered: true }); } catch (e) { console.error('[GitHub 中文化插件] React 提交监听失败:', e); } } /** * 处理Turbo页面加载事件 * 在新页面加载后执行必要的翻译 */ function handleTurboLoad() { applyPage('页面导航'); } /* =========================== 页面应用入口 =========================== */ /** * 应用当前页面 —— 首次载入与 Turbo 换页共用这一条路径。 * * 两条路径曾经各写一份:首次载入不翻标题 / 选择器(晚注入时一直缺译文), * Turbo 载入又会在同一次载入里把整棵树走两遍(DOMContentLoaded + turbo:load)。 * 现在统一到这里,由 hasFreshTraversal() 决定还要不要重走 DOM。 * @param {string} reason - 触发原因(用于调试日志) */ function applyPage(reason) { if (!document.body) return; State.currentURL = window.location.href; updatePageConfig(reason); // before-render 已经挂好的观察器直接沿用;没有页面配置时也要挂上 const preAttached = State.observedBody === document.body && !!State.mutationObserver; if (!preAttached) setupMutationObserver(); const pageConfig = State.pageConfig; if (!pageConfig) return; // 恢复访问时快照里已是译文:交给预挂的观察器和空闲补扫,不做同步全量遍历 if (State.visitAction === 'restore' && preAttached) { scheduleIdleTraversal(); } else if (!hasFreshTraversal()) { traversePage('页面遍历'); } safe(transTitle, '标题翻译')(); // 翻译页面标题 safe(transBySelector, '选择器翻译')(); // 通过选择器翻译特定元素 // 仓库页等 React 提交后再挂(watchReactCommits);gist 等非 React 页面载入即挂 if (pageConfig.currentPageType !== 'repository' || typeof PerformanceObserver !== 'function') { safe(mountDescButton, '描述翻译')(); } } /** * 全量遍历当前 body,成功后才记为「已遍历」;失败留给下一次导航重试 * @param {string} label - 错误标签 */ function traversePage(label) { try { traverseNode(document.body); markPageTraversed(); } catch (e) { console.error(`[GitHub 中文化插件] ${label} 出错:`, e); } } /** * 当前 body 是否已按当前 URL 完整遍历过。 * DOMContentLoaded 与 turbo:load 会先后触发同一次页面载入,第二次不必再走一遍树; * 两次之间的增量变化由 MutationObserver 负责,不依赖这里重扫。 */ function hasFreshTraversal() { return State.lastTraversal !== null && State.lastTraversal.body === document.body && State.lastTraversal.url === window.location.href; } /** * 记录「当前 URL + body 已完整遍历」,供 hasFreshTraversal() 判定 */ function markPageTraversed() { State.lastTraversal = { url: window.location.href, body: document.body }; } /* =========================== 页面配置管理 =========================== */ /** * 更新页面配置 — 页面类型变化时重建 State.pageConfig * 同一页面类型内只更新路径:词库、正则规则和翻译缓存都与具体路径无关, * 站内翻页(议题列表、仓库之间)不必重新展开词库和重算前置过滤。 * @param {string} trigger - 触发更新的原因(用于调试) */ function updatePageConfig(trigger) { const newType = detectPageType(); if (!newType) { State.pageConfig = null; } else if (newType !== State.pageConfig?.currentPageType) { State.pageConfig = buildPageConfig(newType); } else { State.pageConfig.currentPath = window.location.pathname; } console.log(`【Debug】${trigger}触发, 页面类型为 ${State.pageConfig?.currentPageType}`); } /** * 构建页面配置对象 * @param {string} pageType - 页面类型 * @returns {Object} 页面配置对象 */ function buildPageConfig(pageType) { const conf = I18N.conf; const dict = I18N[CONFIG.LANG]; const pageDict = dict[pageType] || {}; // 合并公共('*')与页面特定的选择器列表 const pickSelectors = key => [...(conf[key]['*'] || []), ...(conf[key][pageType] || [])]; const regexpRules = [ // 合并公共和页面特定的正则规则 ...(pageDict.regexp || []), ...(dict.public.regexp || []) ]; return { currentPageType: pageType, // 当前页面类型 currentPath: window.location.pathname, // 当前路径 titleStaticDict: pageDict.title?.static || {}, titleRegexpRules: pageDict.title?.regexp || [], staticDict: { // 合并公共和页面特定的静态词典 ...dict.public.static, ...(pageDict.static || {}) }, regexpRules, // 与 regexpRules 一一对应的「匹配时必然出现的字面量」,用于跳过不可能命中的规则 regexpPrefilters: regexpRules.map(([pattern]) => getRequiredLiteral(pattern)), ignoreMutationSelectors: pickSelectors('ignoreMutationSelectorPage').join(', '), // 忽略的突变选择器 ignoreSelectors: pickSelectors('ignoreSelectorPage').join(', '), // 忽略的选择器 characterData: (conf.characterDataPage || []).includes(pageType), // 是否监视文本节点变化 transSelectors: [ // 翻译选择器规则 ...(dict.public.selector || []), ...(pageDict.selector || []) ], transCache: new Map(), // 当前页面类型的翻译结果缓存(文本 -> 译文/false) }; } /* =========================== 页面类型检测 =========================== */ /** * 全局路由保留首段(与 rePagePath 的全局首段一致,并包含组织页别名 organizations)。 * 这些首段是站点固定路径,不可能是账号名 / 组织名。 */ const RESERVED_ROOTS = new Set([ 'home', 'dashboard', 'feed', 'copilot', 'spark', 'signup', 'account_verifications', 'login', 'logout', 'session', 'sessions', 'password_reset', 'orgs', 'organizations', 'explore', 'topics', 'notifications', 'watching', 'stars', 'issues', 'pulls', 'repos', 'search', 'trending', 'showcases', 'new', 'import', 'settings', 'installations', 'marketplace', 'apps', 'account', 'projects', 'redeem', 'discussions', 'collections', 'sponsors', 'sponsoring', 'github-copilot', 'codespaces', 'developer', 'features', 'security', 'sitemap', 'education', 'mcp', 'users', ]); /** * 当前页面对应的仓库(owner/repo),取自 GitHub 的 octolytics 元数据。 * Turbo 导航期间元数据会短暂缺失,调用方自行处理空串。 * @returns {string} 形如 "owner/repo" 的小写串;缺失时为空串 */ function readRepositoryNwo() { const content = document.head .querySelector('meta[name="octolytics-dimension-repository_nwo"]') ?.content; return (content || '').trim().toLowerCase(); } /** * 从 pathname 推断当前页面归属的账号 / 组织名。 * 保留首段(settings / notifications 等)是站点固定路径,返回 null。 * @returns {string|null} 小写的账号 / 组织名 */ function getOwnerFromPath() { const segments = window.location.pathname.toLowerCase().split('/').filter(Boolean); if (!segments.length) return null; if (segments[0] === 'orgs' || segments[0] === 'organizations') { return segments[1] || null; } // notifications / settings / marketplace 这类保留路径的首段不是账号名 if (RESERVED_ROOTS.has(segments[0])) return null; return segments[0]; } /** * Turbo 导航会暂时拿掉 analytics-location。 * 仅在元数据缺失或无法识别时按路径回退,已有元数据仍优先。 * 全局路由按完整首段排除,避免没有结尾锚点的 rePagePath 把 settings-tools 当成 settings。 */ function isFallbackRepositoryPath(pathname) { const segments = pathname.split('/'); if (segments.length < 3) return false; const owner = segments[1]; const repo = segments[2]; function isSegment(segment) { return /^[A-Za-z0-9._-]+$/.test(segment) && !/^\.+$/.test(segment); } if (!isSegment(owner) || !isSegment(repo)) return false; if (RESERVED_ROOTS.has(owner.toLowerCase())) return false; const extra = segments.slice(3); const isRoot = extra.length === 0 || (extra.length === 1 && extra[0] === ''); if (isRoot) { // //enterprise_plan 与 //sponsoring 属于组织路径,不是仓库根路径 const repoName = repo.toLowerCase(); return repoName !== 'enterprise_plan' && repoName !== 'sponsoring'; } if (extra.some(segment => segment === '' || segment === '.' || segment === '..')) return false; return I18N.conf.rePagePathRepo.test(pathname); } /** * 检测当前页面类型 * @returns {string|boolean} 页面类型或false(如果未识别) */ function detectPageType() { const { PAGE_MAP } = CONFIG; const { hostname, pathname, search } = window.location; // 基础配置 const site = PAGE_MAP[hostname] || 'github'; // 通过站点映射获取基础类型 const isLogin = document.body.classList.contains("logged-in"); const metaLocation = (document.head.querySelector('meta[name="analytics-location"]')?.content || '').trim(); const metaUsable = /\/<(?:user-name|org-login)>/.test(metaLocation); // 页面特征检测 const isSession = document.body.classList.contains("session-authentication"); const isHomepage = pathname === '/' && site === 'github'; const isProfile = document.body.classList.contains("page-profile") || metaLocation === '/'; // 元数据优先;Turbo 暂时拿掉 analytics-location 时再按仓库路径回退 const isRepository = /\/\//.test(metaLocation) || !!readRepositoryNwo() || (!metaUsable && isFallbackRepositoryPath(pathname)); const isOrganization = /\//.test(metaLocation) || /^\/(?:orgs|organizations)/.test(pathname); let pageType; // 根据页面特征确定页面类型 switch (true) { // 使用 switch(true) 模式处理多条件分支 case isSession: // 登录/认证页面 pageType = 'session-authentication'; break; case site !== 'github': // 特殊站点(gist / status / skills / education) pageType = site; break; case isProfile: { // 用户资料页面 const tabParam = new URLSearchParams(search).get('tab'); pageType = pathname.includes('/stars') ? 'page-profile/stars' : tabParam ? `page-profile/${tabParam}` : 'page-profile'; break; } case isHomepage: // 首页/仪表盘 pageType = isLogin ? 'dashboard' : 'homepage'; break; case isRepository: { // 代码仓库页面 const repoMatch = pathname.match(I18N.conf.rePagePathRepo); pageType = repoMatch ? `repository/${repoMatch[1]}` : 'repository'; break; } case isOrganization: { // 组织页面 const orgMatch = pathname.match(I18N.conf.rePagePathOrg); pageType = orgMatch ? `orgs/${orgMatch[1] || orgMatch.slice(-1)[0]}` : 'orgs'; break; } default: { // 默认页面类型 const pathMatch = pathname.match(I18N.conf.rePagePath); pageType = pathMatch ? (pathMatch[1] || pathMatch.slice(-1)[0]) : false; } } // 验证页面类型是否有效 if (pageType === false || !I18N[CONFIG.LANG]?.[pageType]) { const reason = pageType === false ? '路径未匹配任何页面规则' : `词库中缺少 "${pageType}" 的翻译`; console.warn('[i18n] %s', reason, { url: window.location.href, hostname, pathname, site, pageType, isLogin, metaLocation }); return false; } return pageType; } /* =========================== MutationObserver =========================== */ /** * 批次里是否新增了描述节点(含包着描述的祖先子树)。 * react-root:commit 只覆盖 React root 的提交:浮层、下拉菜单、侧栏等运行时渲染 * 走的是普通状态更新,不会重新打 commit mark。这些新插入的描述节点只能靠这份 * 「新增节点」事件补挂(插入发生在 React 已渲染的 DOM 上,不会再触发 hydration mismatch)。 * @param {MutationRecord[]} batch * @param {string} selector - 描述元素的选择器 * @returns {boolean} */ function batchAddedDesc(batch, selector) { return batch.some(({ addedNodes }) => [...addedNodes].some(node => node.nodeType === 1 && (node.matches(selector) || node.querySelector(selector)))); } /** * 处理攒下的突变批次(一帧一次) */ function flushMutationBatch() { State.mutationFlush = null; if (!State.pendingMutations.length) return; const batch = State.pendingMutations; State.pendingMutations = []; if (!State.pageConfig) return; try { processMutations(batch); // 只有仓库首页会渲染 About 浮层;gist 等页面在载入时挂载即可 if (State.pageConfig.currentPageType === 'repository' && batchAddedDesc(batch, CONFIG.DESC_SELECTORS.repository)) { mountDescButton(); } } finally { // 本次遍历产生的写入会再次进入观察器队列,若不丢弃,下一帧会重复遍历自己的译文。 // 这里的记录都来自同步执行的本次批次;页面自己的异步渲染在回调之后才会发生。 State.mutationObserver?.takeRecords(); } } /** * 安排一次批次处理;没有 requestAnimationFrame 的环境(测试/极老浏览器) * 保持同步处理,避免行为变化。 */ function scheduleMutationFlush() { if (State.mutationFlush) return; if (typeof window.requestAnimationFrame === 'function') { const id = window.requestAnimationFrame(flushMutationBatch); State.mutationFlush = { cancel() { window.cancelAnimationFrame?.(id); }, }; } else { flushMutationBatch(); } } /** * 换 body 时丢弃上一份文档攒下的突变,避免继续处理已断开的节点。 */ function resetMutationBatch() { State.pendingMutations = []; if (State.mutationFlush) { State.mutationFlush.cancel(); State.mutationFlush = null; } } /** * 创建DOM变化观察器 * 监听页面变化并触发翻译 */ function createMutationObserver() { return new MutationObserver( safe((mutations) => { const currentURL = window.location.href; // 当没有 onurlchange 支持时,通过 Observer 检测 URL 变化 if (!State.urlChangeHandler && currentURL !== State.currentURL) { State.currentURL = currentURL; updatePageConfig("URL变化 (MutationObserver)"); } State.pendingMutations.push(...mutations); scheduleMutationFlush(); }, 'MutationObserver') ); } /** * 把观察器挂到指定 body 上 — 允许传入尚未插入文档的新 body, * 这样 Turbo 换 body 时,React 水合产生的那批变更从第一帧就被接住。 * @param {Element} body */ function attachMutationObserver(body) { resetMutationBatch(); State.mutationObserver?.disconnect(); State.mutationObserver = createMutationObserver(); State.mutationObserver.observe(body, CONFIG.OBSERVER_CONFIG); State.observedBody = body; } /** * 设置DOM变化观察器(当前文档 body) */ function setupMutationObserver() { State.observedBody = null; if (!document.body) return; attachMutationObserver(document.body); } /** * 处理MutationObserver检测到的变化 * 收集突变节点、过滤忽略选择器、对祖先-后代关系去重,仅遍历顶层节点 * @param {Array} mutations - 变化记录数组 */ function shouldIgnoreMutationNode(node) { const element = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement; if (!element) return true; // 本脚本自己注入的 UI 不参与汉化 if (element.closest?.(SKIP_SELECTORS)) return true; const ignoredSelectors = State.pageConfig?.ignoreMutationSelectors; return !!(ignoredSelectors && element.closest?.(ignoredSelectors)); } function processMutations(mutations) { const { characterData } = State.pageConfig; const nodesToProcess = new Set(); const collect = node => { if (!shouldIgnoreMutationNode(node)) nodesToProcess.add(node); }; // 收集需要处理的节点:新增节点、变化的属性、文本变化(页面开启时) for (const { target, addedNodes, type } of mutations) { if (type === 'childList') { for (const node of addedNodes) collect(node); } else if (type === 'attributes' || (type === 'characterData' && characterData)) { collect(target); } } // 祖先也在集合里时只遍历祖先:后代已在它的子树内,不必重复走 const topNodes = new Set(); for (const node of nodesToProcess) { let ancestor = node.parentElement; while (ancestor && !nodesToProcess.has(ancestor)) ancestor = ancestor.parentElement; if (!ancestor) topNodes.add(node); } if (CONFIG.DEV) console.log("DOM变化(已过滤)", topNodes); // 仅遍历顶层节点 topNodes.forEach(node => { traverseNode(node); }); } /* =========================== DOM 遍历与节点处理 =========================== */ /** * 面包屑里的账号名 / 仓库名是标识符,不是界面文案(#824) * 例:github.com/community/community 不应显示成「社区 / 社区」 * @param {Element} element * @returns {boolean} 是否应跳过该链接 */ function isBreadcrumbIdentifierLink(element) { if (element.tagName !== 'A') return false; if (!element.closest?.('nav[data-component="Breadcrumbs"]')) return false; const linkPath = element.pathname?.toLowerCase().replace(/\/+$/, ''); if (!linkPath) return false; const repository = readRepositoryNwo(); if (repository) { const [owner] = repository.split('/'); return linkPath === `/${owner}` || linkPath === `/${repository}`; } // 元数据缺失时按 pathname 推断:只有「/首段」是账号名时首项才是标识符; // notifications / settings / marketplace 这类保留路径的首项是界面文案,不能拒翻。 const owner = getOwnerFromPath(); return !!owner && linkPath === `/${owner}`; } /** * 遍历节点树并进行翻译 * @param {Node} rootNode - 要遍历的根节点 */ function traverseNode(rootNode) { const start = performance.now(); // 文本节点直接处理 if (rootNode.nodeType === Node.TEXT_NODE) { handleTextNode(rootNode); return; } // 忽略选择器在遍历期间不变,提到过滤器外,避免每个节点都读一遍配置 const ignoreSelectors = State.pageConfig.ignoreSelectors; // 创建TreeWalker遍历节点树 const treeWalker = document.createTreeWalker( rootNode, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, node => { if (node.nodeType === Node.ELEMENT_NODE) { // 本脚本自己注入的 UI 不参与汉化 if (node.closest?.(SKIP_SELECTORS)) { return NodeFilter.FILTER_REJECT; } if (ignoreSelectors && node.matches(ignoreSelectors)) { return NodeFilter.FILTER_REJECT; // 跳过忽略的选择器 } if (isBreadcrumbIdentifierLink(node)) { return NodeFilter.FILTER_REJECT; // 跳过账号名 / 仓库名 } } return NodeFilter.FILTER_ACCEPT; // 接受其他节点 } ); let currentNode; // 遍历所有节点 while ((currentNode = treeWalker.nextNode())) { if (currentNode.nodeType === Node.ELEMENT_NODE) { handleElementNode(currentNode); } else if (currentNode.nodeType === Node.TEXT_NODE) { handleTextNode(currentNode); } } // 性能监控 const duration = performance.now() - start; if (duration > 10) { console.log(`节点遍历耗时: ${duration.toFixed(2)}ms`); } } /** * 处理文本节点 * @param {Node} node - 文本节点 */ function handleTextNode(node) { if (node.length > 500) return; // 跳过长文本节点 // 文本域的子文本是它的默认值(用户内容),翻了就破坏编辑器内容(#727) if (node.parentElement?.tagName === 'TEXTAREA') return; transElementAttrs(node, 'data'); // 翻译文本内容 } /** * 处理元素节点 * @param {Element} node - 元素节点 */ function handleElementNode(node) { // 按标签分派;只有需要继续检查 tooltipped 的分支才走到末尾 switch (node.tagName) { case "RELATIVE-TIME": { // 相对时间元素 if (node.shadowRoot) transTimeElement(node.shadowRoot); return; } case "INPUT": case "TEXTAREA": { // 输入框和文本域 // 标签本身已由通用遍历到达(不在忽略表里),这里只碰界面文案属性: // 文本域的子文本是默认值,由 handleTextNode 拦截,不在这里处理。 // // 注意:这段在 #774(2026-08 把 input/textarea 加进忽略表)之前一直是生效的, // 后来被忽略表挡成死代码、改由旁路补翻;单管线重构后又回到这里。 // 它翻译 value 是长期行为,不是误留的死代码——不要因为“看起来走不到”就删。 transElementAttrs(node, 'ariaLabel'); // 可访问名称(占位符之外的屏幕阅读器文案) if (/^(?:button|submit|reset)$/.test(node.type)) { // value 是按钮文案;只有 submit 带 name 时它同时是原生表单的提交值, // GitHub 现在基本不用原生表单提交,暂不特判——若遇到提交异常先查这里 transElementAttrs(node.dataset, 'confirm'); // 确认对话框文本 transElementAttrs(node, 'value'); // 值属性 } else { transElementAttrs(node, 'placeholder'); // 占位符 } return; } case "OPTGROUP": // 选项组 transElementAttrs(node, 'label'); // 标签文本 return; case "BUTTON": // 按钮 transElementAttrs(node, [ 'title', 'cancelConfirmText' ]); transElementAttrs(node.dataset, [ 'confirm', // 确认文本 'confirmText', // 确认按钮文本 'confirmCancelText', // 取消按钮文本 'disableWith', // 禁用提示 'visibleText' ]); break; case "A": case "SPAN": transElementAttrs(node, 'title'); // 标题提示 transElementAttrs(node.dataset, 'visibleText'); // 可见文本 break; } // 带有 tooltipped 样式的元素 if (typeof node.className === 'string' && node.className.includes('tooltipped')) { transElementAttrs(node, 'ariaLabel'); } } /* =========================== 翻译功能 =========================== */ /** * 翻译页面标题 */ function transTitle() { const { titleStaticDict, titleRegexpRules } = State.pageConfig; const text = document.title; let result = titleStaticDict[text]; // 静态词条未命中才跑正则 if (!result) { for (const [pattern, replacement] of titleRegexpRules) { const translated = text.replace(pattern, replacement); if (translated !== text) { result = translated; break; } } } // 应用翻译结果 if (result) { document.title = result; } } /** * 翻译时间元素 * @param {Element} element - 时间元素 */ function transTimeElement(element) { // 获取时间文本 const text = element.textContent; if (!text) return; // 移除时间文本中的"on" const result = text.replace(/\bon\s+/gi, (match, offset) => offset === 0 ? " " : ""); if (result !== text) { element.textContent = result; // 应用翻译 } } /** * 翻译元素的单个属性 * @param {Object} target - 元素对象或元素数据集 * @param {string} attrName - 要翻译的属性名 */ function transElementAttr(target, attrName) { const text = target[attrName]; if (!text) return; const result = transText(text); if (result) { target[attrName] = result; } } /** * 批量翻译元素的多个属性 * @param {Object} target - 元素对象或元素数据集 * @param {string|string[]} attrs - 要翻译的属性名或属性名数组 */ function transElementAttrs(target, attrs) { if (Array.isArray(attrs)) { for (const attrName of attrs) transElementAttr(target, attrName); } else { transElementAttr(target, attrs); } } /** * 通过选择器翻译特定元素 */ function transBySelector() { State.pageConfig.transSelectors?.forEach(([selector, result]) => { const element = document.querySelector(selector); if (element) { element.textContent = result; // 应用翻译 } }); } /** * 翻译文本内容 * @param {string} text - 要翻译的文本 * @returns {string|boolean} 翻译后的文本或 false */ function transText(text) { // 跳过不需要翻译的文本:不含英文字母和 , . 的文本一律不查词库 //(空文本、纯数字、纯中文都落在这里;有英文的文本才可能命中词条或正则) if (!/[a-zA-Z,.]/.test(text)) { return false; } // 清理文本:去除首尾空格和多余空白(\s 已覆盖不换行空格 \u00a0) const trimmedText = text.trim(); const cleanedText = trimmedText.replace(/\s+/g, ' '); // 获取翻译 const result = fetchTransResult(cleanedText); if (result && result !== cleanedText) { return text.replace(trimmedText, result); } return false; } // 单页翻译结果缓存上限:文本重复率高(导航、按钮、时间),缓存命中率远高于随机内容, // 上限只是防止长时间会话里无限增长。 const TRANS_CACHE_LIMIT = 5000; /** * 清空当前页面的翻译结果缓存 — 正则功能开关变化后必须调用, * 否则会命中「关闭正则时算出的未命中结果」而漏翻。 */ function resetTransCache() { if (State.pageConfig) State.pageConfig.transCache = new Map(); } /** * 提取正则规则「一旦匹配就必然出现在文本里」的字面量,用来跳过不可能命中的规则。 * 只认长度 >= 4 的纯字母连续段,并保守放弃以下情况: * - 带 i 标志(大小写不敏感,includes 会误判) * - 任意位置的 `|`(分支不共享字面量) * - 前后向断言 / 被可选量词修饰的组(字面量可能不出现) * - 字面量本身后跟可选量词(可能零次出现) * 返回 null 表示这条规则必须照常执行。 * @param {RegExp} pattern * @returns {string|null} */ function getRequiredLiteral(pattern) { if (!pattern || pattern.flags.includes('i')) return null; const source = pattern.source; if (source.includes('|')) return null; if (/\(\? char === '?' || char === '*' || char === String.fromCharCode(123); let best = ''; let run = ''; let inClass = false; const flush = end => { if (run.length >= 4 && !optional(source[end]) && run.length > best.length) { best = run; } run = ''; }; for (let i = 0; i < source.length; i += 1) { const char = source[i]; if (char === '\\') { if (!inClass) flush(i); // 转义序列不是字面量字母 i += 1; } else if (inClass) { if (char === ']') inClass = false; } else if (char === '[') { flush(i); inClass = true; } else if (char === ')') { if (optional(source[i + 1])) return null; // 整个组被可选量词修饰 flush(i); } else if (char === '(' || char === '^' || char === '$') { flush(i); } else if (/[A-Za-z]/.test(char)) { run += char; } else { flush(i); } } flush(source.length); return best || null; } /** * 从词库获取翻译 — 直接读取 State.pageConfig * @param {string} text - 要翻译的文本 * @returns {string|boolean} 翻译结果或 false */ function fetchTransResult(text) { if (!State.pageConfig) return false; const pageConfig = State.pageConfig; // 未命中词条记录依赖「每次查询都记账」,开启时绕开缓存以保证行为不变(仅开发者模式)。 const cache = State.featureSet.enable_missedTerms ? null : pageConfig.transCache; if (cache) { const cached = cache.get(text); if (cached !== undefined) return cached; } let result = false; // 静态词典查找 const staticResult = pageConfig.staticDict[text]; if (typeof staticResult === 'string') { result = staticResult; } else if (State.featureSet.enable_RegExp) { // 正则规则查找:先用「必然出现的字面量」跳过不可能命中的规则 const { regexpPrefilters, regexpRules } = pageConfig; for (let index = 0; index < regexpRules.length; index += 1) { const required = regexpPrefilters?.[index]; if (required && !text.includes(required)) continue; const [pattern, replacement] = regexpRules[index]; const translated = text.replace(pattern, replacement); if (translated !== text) { result = translated; break; } } } if (result !== false) { // 命中的词条可能还挂在未命中记录里:命中即清理 MissedTermsManager.cleanup(text, pageConfig.currentPath); } else if (State.featureSet.enable_missedTerms) { // 未命中才记账,并刷新菜单里的计数 MissedTermsManager.record(text, pageConfig.currentPath); refreshMenuStates(); } if (cache) { if (cache.size >= TRANS_CACHE_LIMIT) cache.clear(); cache.set(text, result); } return result; } /* =========================== 远程翻译 =========================== */ /** * 为每个还没挂载的描述元素添加翻译按钮 * @param {string} selector - 描述元素的选择器 */ function transDesc(selector) { for (const host of document.querySelectorAll(selector)) { // 按钮或翻译结果已在描述后面:重复调用不叠按钮 if (host.nextElementSibling?.matches('.translate-button, .translation-result')) { continue; } const button = document.createElement('div'); button.classList.add('translate-button'); button.textContent = '翻译'; button.addEventListener('click', () => handleTransClick(button, host)); host.after(button); } } /** * 处理翻译按钮点击事件 * @param {Element} button - 翻译按钮元素 * @param {Element} element - 要翻译的元素 */ function handleTransClick(button, element) { if (button.disabled) return; button.disabled = true; // 防止重复点击 const descText = element.textContent.trim(); if (!descText) { button.disabled = false; return; } // 发起远程翻译请求 requestRemoteTrans(descText) .then(result => { showTransResult(element, button, result); }) .catch(error => { console.error('翻译失败:', error); button.disabled = false; // 启用按钮以允许重试 }); } /** * 显示翻译结果 * @param {Element} element - 原始元素 * @param {Element} button - 翻译按钮 * @param {string} result - 翻译结果 */ function showTransResult(element, button, result) { const { name, url } = CONFIG.TRANS_ENGINES[State.transEngine]; // 创建结果容器 — 结构与不可信文本分离,防止 XSS const resultContainer = document.createElement('div'); resultContainer.className = 'translation-result'; resultContainer.innerHTML = ` 由 ${name} 翻译👇
`; // API 响应文本使用 textContent,禁止 HTML 解析 resultContainer.querySelector('.translation-content').textContent = result; // 移除按钮并显示结果 button.remove(); element.after(resultContainer); } /** * 请求远程翻译API * @param {string} text - 要翻译的文本 * @returns {Promise} 翻译结果 */ async function requestRemoteTrans(text) { const { url_api, method, headers, getRequestData, responseIdentifier } = CONFIG.TRANS_ENGINES[State.transEngine]; const requestData = getRequestData(text); // 使用GM_xmlhttpRequest发起跨域请求 const responseText = await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method, url: url_api, headers, data: method === 'POST' ? JSON.stringify(requestData) : null, params: method === 'GET' ? requestData : null, // For GET requests timeout: 10000, // 10秒超时 onload: res => resolve(res.responseText), onerror: reject, }); }); // 从响应中提取翻译结果;解析失败与结果缺失都以 reject 结束 const result = getNestedProperty(JSON.parse(responseText), responseIdentifier); if (!result) throw new Error('翻译结果无效'); return result; } /** * 安全获取嵌套对象属性 * 支持路径格式如 'biz[0]?.sectionResult[0]?.dst' * - '?.' 在路径中作为可选链标记被忽略,实际按强制访问处理 * @param {Object} obj - 目标对象 * @param {string} path - 属性路径 * @returns {*} 属性值或 undefined */ function getNestedProperty(obj, path) { // 移除路径中的 ?. 标记(讯飞API返回的路径表示可选,但此处按强制处理) const cleanPath = path.replace(/\?\./g, '.'); return cleanPath.split('.').reduce((acc, part) => { if (!acc) return undefined; const match = part.match(/^(\w+)(?:\[(\d+)\])?$/); if (!match) return undefined; const key = match[1]; const index = match[2]; // 处理数组索引或对象属性 return index !== undefined ? acc[key]?.[index] : acc[key]; }, obj); } /* =========================== 未命中词条管理器 =========================== */ const MissedTermsManager = { /** * 未命中词条数据结构(简洁模式) * { * [pathname]: { * "原始文本1": "", * "原始文本2": "", * ... * } * } */ data: GM_getValue("missedTerms", {}), /** * 记录未命中词条 * @param {string} text - 未翻译的文本 * @param {string} path - 当前页面路径 */ record(text, path) { if (!path) return false; const bucket = this.data[path] || (this.data[path] = {}); if (text in bucket) return false; // 词条已存在 bucket[text] = ""; this.save(); return true; // 新增词条 }, /** * 清理已命中的词条 * @param {string} text - 已翻译的文本 * @param {string} path - 当前页面路径 */ cleanup(text, path) { const bucket = path ? this.data[path] : null; if (!bucket || !(text in bucket)) return false; delete bucket[text]; // 如果该路径下没有词条了,删除路径条目 if (Object.keys(bucket).length === 0) delete this.data[path]; this.save(); return true; }, /** * 清空所有词条 */ clearAll() { this.data = {}; this.save(); }, /** * 获取统计信息 * @returns {Object} 统计信息 */ getStats() { const paths = Object.keys(this.data); const totalTerms = paths.reduce((sum, path) => sum + Object.keys(this.data[path]).length, 0 ); return { totalPaths: paths.length, totalTerms: totalTerms }; }, /** * 导出数据 * @returns {Object} 导出数据 */ exportData() { const data = this.data; const stats = this.getStats(); return { metadata: { exportedAt: new Date().toISOString(), version: "1.0", ...stats }, data }; }, /** * 保存数据到存储 */ save() { GM_setValue("missedTerms", this.data); } }; /* =========================== 用户菜单 =========================== */ /** * 1. 动态菜单管理 */ function refreshMenuStates() { // 注销所有动态菜单 Object.values(State.dynamicMenus).forEach(id => GM_unregisterMenuCommand(id)); State.dynamicMenus = {}; // 仅开发者模式下显示未命中词条相关菜单 if (!CONFIG.DEV) return; // 切换菜单 const toggleLabel = `${State.featureSet.enable_missedTerms ? "禁用" : "启用"} 未命中词条记录`; State.dynamicMenus.toggle = GM_registerMenuCommand(toggleLabel, () => { const newState = !State.featureSet.enable_missedTerms; State.featureSet.enable_missedTerms = newState; GM_setValue("enable_missedTerms", newState); if (!newState) { MissedTermsManager.clearAll(); GM_notification("未命中词条记录已禁用,所有记录已清空"); } else { GM_notification("未命中词条记录已启用"); } refreshMenuStates(); }); // 启用 + 有词条时显示导出和清空菜单 if (State.featureSet.enable_missedTerms) { const stats = MissedTermsManager.getStats(); const hasData = stats.totalTerms > 0; if (hasData) { // 导出菜单 State.dynamicMenus.export = GM_registerMenuCommand( `📥 导出未命中词条 (${stats.totalTerms}条)`, () => { const exportData = MissedTermsManager.exportData(); const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `GitHub_未命中词条_${new Date().toISOString().split('T')[0]}.json`; a.click(); URL.revokeObjectURL(url); } ); // 清空菜单 State.dynamicMenus.clear = GM_registerMenuCommand( "🗑️ 清空未命中词条", () => { if (confirm(`确定要清空所有未命中词条吗?\n共 ${stats.totalPaths} 个页面,${stats.totalTerms} 个词条`)) { MissedTermsManager.clearAll(); GM_notification("未命中词条记录已清空"); refreshMenuStates(); } } ); // 查看统计菜单 State.dynamicMenus.stats = GM_registerMenuCommand( "📊 查看统计", () => { const s = MissedTermsManager.getStats(); GM_notification({ title: "未命中词条统计", text: `页面数: ${s.totalPaths}\n词条数: ${s.totalTerms}`, timeout: 5000 }); } ); } } } /** * 2. 静态菜单创建 * @param {Object} config - 菜单配置 */ function createMenuCommand(config) { const { label, key, callback } = config; let menuId; // 生成菜单标签(根据当前状态) const getMenuLabel = () => `${State.featureSet[key] ? "禁用" : "启用"} ${label}`; // 切换功能状态 const toggle = () => { const newState = !State.featureSet[key]; // 保存到存储 GM_setValue(key, newState); State.featureSet[key] = newState; // 显示通知 GM_notification(`${label}已${newState ? '启用' : '禁用'}`); // 执行回调 callback?.(newState); // 重新注册菜单(更新标签) GM_unregisterMenuCommand(menuId); menuId = GM_registerMenuCommand(getMenuLabel(), toggle); }; // 初始注册菜单 menuId = GM_registerMenuCommand(getMenuLabel(), toggle); } /** * 3. 主菜单设置 */ function setupMenuCommands() { const menuConfigs = [ { label: "正则功能", key: "enable_RegExp", callback: (enabled) => { // 缓存里可能存着「关闭正则时算出的未命中结果」,切换后必须先失效 resetTransCache(); if (enabled && State.pageConfig) traversePage('菜单触发遍历'); } }, { label: "描述翻译", key: "enable_transDesc", callback: (enabled) => { if (enabled) { mountDescButton(); } else { // 禁用描述翻译,移除所有按钮;重新启用时再挂 document.querySelectorAll('.translate-button') .forEach(button => button.remove()); } } } ]; // 为每个配置创建静态菜单 menuConfigs.forEach(config => createMenuCommand(config)); // 初始化动态菜单 refreshMenuStates(); } /* =========================== 启动 =========================== */ init(); })(window, document); /* ================================================================== * 模块二:GitHub 文件下载加速 * ================================================================== */ (function () { "use strict"; /* ================================================================== * 一、节点池 * * 全部是「前缀式」代理:把完整 GitHub URL 拼在前缀后面。 * https://gh-proxy.com/https://github.com/o/r/releases/download/v1/a.zip * * alive:false = 实测不可用(404 / 429 / 5xx / 返回网页而非文件), * 默认不参与测速,可通过「包含失效节点」开关重新尝试。 * ================================================================== */ const NODES = [ // 你指定的三个站点 { host: "https://gh-proxy.com", tag: "gh-proxy.com", note: "美国 Cloudflare" }, { host: "https://gh-proxy.org", tag: "gh-proxy.org", note: "美国 Cloudflare" }, { host: "https://edgeone.gh-proxy.org", tag: "edgeone", note: "EdgeOne CDN,偶发超时" }, { host: "https://github.xxlab.tech", tag: "xxlab.tech", note: "多节点面板" }, // 实测可用 { host: "https://git.tangbai.cc", tag: "git.tangbai.cc" }, { host: "https://github.chenc.dev", tag: "github.chenc.dev" }, { host: "https://github.cnxiaobai.com", tag: "github.cnxiaobai.com" }, { host: "https://github.tianrld.top", tag: "github.tianrld.top" }, { host: "https://ghproxy.mirror.skybyte.me", tag: "skybyte.me" }, { host: "https://ghproxy.sakuramoe.dev", tag: "ghproxy.sakuramoe" }, { host: "https://gh.39.al", tag: "gh.39.al" }, { host: "https://ghp.keleyaa.com", tag: "ghp.keleyaa" }, { host: "https://ggg.clwap.dpdns.org", tag: "ggg.clwap" }, { host: "https://jiashu.1win.eu.org", tag: "jiashu.1win" }, { host: "https://gp.871201.xyz", tag: "gp.871201.xyz" }, { host: "https://github.crdz.eu.org", tag: "github.crdz" }, { host: "https://ghproxy.xzhouqd.com", tag: "ghproxy.xzhouqd" }, { host: "https://ghproxy.net", tag: "ghproxy.net" }, { host: "https://ghfast.top", tag: "ghfast.top" }, { host: "https://tvv.tw", tag: "tvv.tw" }, { host: "https://ghproxy.it", tag: "ghproxy.it" }, { host: "https://github.boki.moe", tag: "github.boki.moe" }, { host: "https://cdn.crashmc.com", tag: "cdn.crashmc" }, { host: "https://gh.monlor.com", tag: "gh.monlor.com" }, { host: "https://ghproxy.imciel.com", tag: "ghproxy.imciel" }, { host: "https://github.1ms.xx.kg", tag: "github.1ms" }, { host: "https://gh.198962.xyz", tag: "gh.198962.xyz" }, { host: "https://hub.ddayh.com", tag: "hub.ddayh" }, { host: "https://gh.chjina.com", tag: "gh.chjina" }, { host: "https://github.ednovas.xyz", tag: "github.ednovas" }, { host: "https://ghfile.geekertao.top", tag: "ghfile.geekertao" }, { host: "https://github.880824.xyz", tag: "github.880824" }, { host: "https://git.820828.xyz", tag: "git.820828" }, { host: "https://gh.996986.xyz", tag: "gh.996986" }, { host: "https://ghproxy.053000.xyz", tag: "ghproxy.053000" }, { host: "https://github.zzrbk.xyz", tag: "github.zzrbk" }, { host: "https://github.mlmle.cn", tag: "github.mlmle" }, { host: "https://proxy.baguoyuyan.com", tag: "proxy.baguoyuyan" }, { host: "https://ghm.078465.xyz", tag: "ghm.078465" }, { host: "https://gh.nxnow.top", tag: "gh.nxnow" }, { host: "https://github.ihnic.com", tag: "github.ihnic" }, { host: "https://github.788787.xyz", tag: "github.788787" }, { host: "https://kenyu.ggff.net", tag: "kenyu.ggff" }, { host: "https://github.lsdfxdk.nyc.mn", tag: "lsdfxdk" }, { host: "https://getgit.love8yun.eu.org", tag: "love8yun" }, { host: "https://ghproxy.monkeyray.net", tag: "monkeyray" }, { host: "https://git.951959483.xyz", tag: "git.951959483" }, { host: "https://gitproxy.127731.xyz", tag: "gitproxy.127731" }, { host: "https://github.boringhex.top", tag: "github.boringhex" }, { host: "https://github-proxy.lixxing.top", tag: "lixxing" }, { host: "https://gh.catmak.name", tag: "gh.catmak" }, { host: "https://gh.idayer.com", tag: "gh.idayer" }, { host: "https://fastgit.cc", tag: "fastgit.cc" }, { host: "https://gh.dpik.top", tag: "gh.dpik.top" }, { host: "https://ghpxy.hwinzniej.top", tag: "ghpxy.hwinzniej" }, { host: "https://wget.la", tag: "wget.la" }, { host: "https://hub.glowp.xyz", tag: "hub.glowp" }, { host: "https://ghproxy.cn", tag: "ghproxy.cn", note: "首页式站点,返回网页", alive: false }, // 已知失效 / 限流 { host: "https://cdn.gh-proxy.org", tag: "cdn.gh-proxy.org", note: "Fastly,常 500", alive: false }, { host: "https://ghproxy.cc", tag: "ghproxy.cc", note: "域名解析失败", alive: false }, { host: "https://github-proxy.com", tag: "github-proxy.com", note: "解析失败", alive: false }, { host: "https://github.zjzzy.cloudns.org", tag: "zjzzy", note: "解析失败", alive: false }, { host: "https://gh.jasonzeng.dev", tag: "jasonzeng", note: "解析失败", alive: false }, { host: "https://raw.ihtw.moe", tag: "raw.ihtw.moe", note: "解析失败", alive: false }, { host: "https://git.yylx.win", tag: "git.yylx.win", note: "解析失败", alive: false }, { host: "https://gh.xxooo.cf", tag: "gh.xxooo.cf", note: "解析失败", alive: false }, { host: "https://gh.zwy.one", tag: "gh.zwy.one", note: "解析失败", alive: false }, { host: "https://gh.noki.icu", tag: "gh.noki.icu", note: "503", alive: false }, { host: "https://gh.aaa.team", tag: "gh.aaa.team", note: "521", alive: false }, { host: "https://xiaomo-station.top", tag: "xiaomo-station", note: "530", alive: false }, { host: "https://git.669966.xyz", tag: "git.669966", note: "502", alive: false }, { host: "https://ghproxy.1888866.xyz", tag: "ghproxy.1888866", note: "525", alive: false }, { host: "https://gitproxy.mrhjx.cn", tag: "gitproxy.mrhjx", note: "429 限流", alive: false }, { host: "https://gh.ddlc.top", tag: "gh.ddlc.top", note: "429 限流", alive: false }, { host: "https://ghproxy.cxkpro.top", tag: "ghproxy.cxkpro", note: "429 限流", alive: false }, { host: "https://github.dpik.top", tag: "github.dpik.top", note: "429 限流", alive: false }, { host: "https://github-proxy.memory-echoes.cn", tag: "memory-echoes", note: "429 限流", alive: false }, { host: "https://github.geekery.cn", tag: "github.geekery", note: "404", alive: false }, { host: "https://free.cn.eu.org", tag: "free.cn.eu.org", note: "403", alive: false }, { host: "https://git.40609891.xyz", tag: "git.40609891", note: "403", alive: false }, { host: "https://gh.h233.eu.org", tag: "gh.h233", note: "403", alive: false }, { host: "https://y.whereisdoge.work", tag: "whereisdoge", note: "404", alive: false }, { host: "https://www.5555.cab", tag: "www.5555.cab", note: "返回网页而非文件", alive: false }, { host: "https://ghproxy.cfd", tag: "ghproxy.cfd", note: "返回网页", alive: false }, { host: "https://gh.con.sh", tag: "gh.con.sh", note: "返回错误文本", alive: false }, { host: "https://tool.mintimate.cn/gh", tag: "mintimate", note: "实测 404", alive: false }, ].filter((n, i, arr) => arr.findIndex((m) => m.host === n.host) === i); /* ================================================================== * 二、配置 * ================================================================== */ const K = { enabled: "加速设置.开关", mode: "加速设置.模式", manualNode: "加速设置.指定节点", autoTest: "加速设置.自动测速", timeout: "加速设置.测速超时", tryDead: "加速设置.包含失效节点", injectBtn: "加速设置.注入按钮", rewrite: "加速设置.改写链接", concurrency: "高级.并发测速数", topN: "高级.保留结果数", results: "state.speedResults", }; const DEF = { enabled: true, mode: "auto", manualNode: "https://gh-proxy.com", autoTest: true, timeout: 8, tryDead: false, injectBtn: true, rewrite: true, concurrency: 8, topN: 20, }; function cfgGet(key, def) { if (typeof GM_getValue !== "function") return def; try { const v = GM_getValue(key, def); return v === undefined || v === null ? def : v; } catch (e) { return def; } } function cfgSet(key, val) { if (typeof GM_setValue !== "function") return; try { GM_setValue(key, val); } catch (e) { /* 写失败不影响使用 */ } } function readConfig() { const num = (k, d, min, max) => { const v = Number(cfgGet(k, d)); return Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : d; }; return { enabled: Boolean(cfgGet(K.enabled, DEF.enabled)), mode: String(cfgGet(K.mode, DEF.mode)) === "manual" ? "manual" : "auto", manualNode: String(cfgGet(K.manualNode, DEF.manualNode) || DEF.manualNode).trim().replace(/\/+$/, ""), autoTest: Boolean(cfgGet(K.autoTest, DEF.autoTest)), timeout: num(K.timeout, DEF.timeout, 3, 30), tryDead: Boolean(cfgGet(K.tryDead, DEF.tryDead)), injectBtn: Boolean(cfgGet(K.injectBtn, DEF.injectBtn)), rewrite: Boolean(cfgGet(K.rewrite, DEF.rewrite)), concurrency: num(K.concurrency, DEF.concurrency, 1, 16), topN: num(K.topN, DEF.topN, 3, 80), }; } /* ================================================================== * 三、链接判定 * * 只有「指向一个真实文件」的链接才套代理。仓库主页、issues、tree、 * releases 列表页套上去只会得到一个网页,必须排除。 * ================================================================== */ const PROXY_VALID_HOSTS = [ "github.com", "www.github.com", "gist.github.com", "raw.githubusercontent.com", "raw.github.com", "gist.githubusercontent.com", "objects.githubusercontent.com", ]; // 仓库内「文件型」路径。每一条都要求末尾有具体内容,不会误吞列表页。 const REPO_FILE_PATHS = [ // release 产物:/o/r/releases/download/tag/file /^\/[^/]+\/[^/]+\/releases\/download\/[^/]+\/[^/]+/i, // latest 直链:/o/r/releases/latest/download/file /^\/[^/]+\/[^/]+\/releases\/latest\/download\/[^/]+/i, // 源码归档:/o/r/archive/refs/tags/v1.zip、/o/r/archive/master.zip /^\/[^/]+\/[^/]+\/archive\/\S+\.(?:zip|tar\.gz|tgz|tar\.bz2|tar)$/i, // 仓库内 raw:/o/r/raw/branch/path /^\/[^/]+\/[^/]+\/raw\/[^/]+\/[^/]+/i, // blob 浏览:/o/r/blob/branch/path /^\/[^/]+\/[^/]+\/blob\/[^/]+\/[^/]+/i, // Actions 产物 /^\/[^/]+\/[^/]+\/actions\/runs\/\d+\/artifacts\/\d+/i, /^\/[^/]+\/[^/]+\/suites\/\d+\/artifacts\/\d+/i, // 补丁 /^\/[^/]+\/[^/]+\/commit\/\S+\.(?:patch|diff)/i, /^\/[^/]+\/[^/]+\/pull\/\d+\.(?:patch|diff)/i, // gist 单文件 raw:/user/gistid/raw/file /^\/[^/]+\/[0-9a-f]{6,}\/raw\/\S+/i, ]; function parseUrl(url) { try { return new URL(url); } catch (e) { return null; } } function isFileUrl(url) { if (!url || typeof url !== "string") return false; const u = parseUrl(url); if (!u) return false; if (u.protocol !== "https:" && u.protocol !== "http:") return false; const host = u.hostname.toLowerCase(); if (!PROXY_VALID_HOSTS.includes(host)) return false; // 独立文件域:路径有内容就是文件 if (host === "raw.githubusercontent.com" || host === "raw.github.com" || host === "gist.githubusercontent.com" || host === "objects.githubusercontent.com") { return u.pathname.length > 1; } // gist.github.com 只有 /user/id/raw/... 是文件 if (host === "gist.github.com") { return /^\/[^/]+\/[0-9a-f]{6,}\/raw\/\S+/i.test(u.pathname); } // github.com 主站:必须命中仓库内文件路径 return REPO_FILE_PATHS.some((r) => r.test(u.pathname)); } function isBlobUrl(url) { const u = parseUrl(url); if (!u) return false; return /^\/[^/]+\/[^/]+\/blob\/\S+/i.test(u.pathname) && /github\.com$/i.test(u.hostname); } // blob 浏览页 → raw 直链,拿到纯文件内容 function blobToRaw(url) { const u = parseUrl(url); if (!u) return url; const m = u.pathname.match(/^\/([^/]+)\/([^/]+)\/blob\/(.+)$/i); if (!m) return url; return `https://raw.githubusercontent.com/${m[1]}/${m[2]}/${m[3]}`; } function fileNameOf(url) { const u = parseUrl(url); if (!u) return ""; const seg = u.pathname.replace(/\/+$/, "").split("/").pop() || ""; try { return decodeURIComponent(seg); } catch (e) { return seg; } } /* ================================================================== * 四、代理拼接 * ================================================================== */ function proxify(host, url) { const base = String(host || "").replace(/\/+$/, ""); if (!base) return url; if (String(url).startsWith(base + "/")) return url; return base + "/" + url; } // 从加速链接反解原始地址(用户粘贴别人的加速链接时也能认) function deproxify(url) { const m = String(url || "").match(/^(https?:\/\/[^/]+(?:\/[^/]+)?)\/(https?:\/\/.+)$/); if (!m) return null; return isFileUrl(m[2]) ? m[2] : null; } /* ================================================================== * 五、测速 * ================================================================== */ // 探针:6KB 的 raw 文件,所有前缀式节点都支持,测速几乎不费流量 const PROBE = "https://raw.githubusercontent.com/torvalds/linux/master/README"; const SPEED_TTL = 6 * 60 * 60 * 1000; // 跨域请求的调用入口。用 typeof 取而不是直接引用 GM, // 因为 GM 在某些环境下可能整个对象都不存在,直接写 GM.xxx 会抛 ReferenceError。 const gmxhr = typeof GM_xmlhttpRequest === "function" ? GM_xmlhttpRequest : typeof GM !== "undefined" && GM && typeof GM.xmlHttpRequest === "function" ? GM.xmlHttpRequest : null; function xhrProbe(url, timeoutMs) { return new Promise((resolve) => { const t0 = Date.now(); let settled = false; let handle = null; const done = (ok, status, size) => { if (settled) return; settled = true; resolve({ ok, ms: Date.now() - t0, status: status || 0, size: size || 0 }); }; // 兜底计时:个别实现不触发 ontimeout const guard = setTimeout(() => { if (handle && typeof handle.abort === "function") { try { handle.abort(); } catch (e) { /* 忽略 */ } } done(false, -4, 0); }, timeoutMs + 1200); try { handle = gmxhr({ method: "GET", url, timeout: timeoutMs, headers: { "Cache-Control": "no-cache" }, onload(res) { clearTimeout(guard); const text = res.responseText || ""; const headers = String(res.responseHeaders || "").toLowerCase(); // 拿到网页说明这节点把 URL 当页面处理了,不算可用 const isHtml = headers.includes("text/html"); const okStatus = res.status >= 200 && res.status < 400; done(okStatus && !isHtml && text.length > 0, res.status, text.length); }, onerror() { clearTimeout(guard); done(false, 0, 0); }, ontimeout() { clearTimeout(guard); done(false, -1, 0); }, onabort() { clearTimeout(guard); done(false, -2, 0); }, }); } catch (e) { clearTimeout(guard); done(false, -3, 0); } }); } async function mapLimit(items, limit, fn) { const out = new Array(items.length); let cursor = 0; const n = Math.max(1, Math.min(limit, items.length)); const workers = Array.from({ length: n }, async () => { while (cursor < items.length) { const i = cursor++; try { out[i] = await fn(items[i], i); } catch (e) { out[i] = null; } } }); await Promise.all(workers); return out; } function poolFor(cfg) { return cfg.tryDead ? NODES : NODES.filter((n) => n.alive !== false); } function loadResults(cfg) { const v = cfgGet(K.results, null); if (!v || typeof v !== "object" || !Array.isArray(v.items)) return null; if (typeof v.at !== "number" || Date.now() - v.at > SPEED_TTL) return null; if (v.poolSize !== poolFor(cfg).length) return null; return v; } async function speedTest(cfg) { const pool = poolFor(cfg); const raw = await mapLimit(pool, cfg.concurrency, async (node) => { const r = await xhrProbe(proxify(node.host, PROBE), cfg.timeout * 1000); return { host: node.host, tag: node.tag, ok: r.ok, ms: r.ms, status: r.status }; }); const items = raw.filter(Boolean); items.sort((a, b) => (a.ok !== b.ok ? (a.ok ? -1 : 1) : a.ms - b.ms)); const okCount = items.filter((i) => i.ok).length; const kept = items.slice(0, Math.max(cfg.topN, okCount)); cfgSet(K.results, { at: Date.now(), poolSize: pool.length, items: kept }); return kept; } function nodeByHost(host) { return NODES.find((n) => n.host === host) || null; } function nodeOf(host, ms) { const hit = nodeByHost(host); return { host, tag: hit ? hit.tag : String(host).replace(/^https?:\/\//, ""), ms: ms === undefined ? null : ms }; } function pickNode(cfg, results) { if (cfg.mode === "manual") return nodeOf(cfg.manualNode, null); const cached = results || loadResults(cfg); if (cached) { const best = cached.items.find((i) => i.ok); if (best) return nodeOf(best.host, best.ms); } // 没有测速结果时用节点池第一个可用项兜底 const first = NODES.find((n) => n.alive !== false) || NODES[0]; return nodeOf(first.host, null); } /* ================================================================== * 六、UI * ================================================================== */ const CSS = ` .gha-btn{display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 9px;margin-left:8px; border-radius:6px;border:1px solid rgba(31,136,61,.45);background:rgba(31,136,61,.10);color:#1a7f37; font:600 12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans",sans-serif; cursor:pointer;vertical-align:middle;white-space:nowrap;transition:background .12s,border-color .12s;} .gha-btn:hover{background:rgba(31,136,61,.20);border-color:rgba(31,136,61,.7);} .gha-btn:active{transform:translateY(1px);} .gha-btn[data-copied="1"]{border-color:rgba(31,136,61,.85);background:rgba(31,136,61,.22);} .gha-btn svg{width:12px;height:12px;flex:none;fill:currentColor;} .gha-float{position:fixed;right:18px;bottom:18px;z-index:2147483000;display:flex;flex-direction:column;gap:8px;} .gha-card{max-width:290px;padding:12px 14px;border-radius:10px;background:#161b22;color:#e6edf3; border:1px solid rgba(255,255,255,.14);box-shadow:0 8px 28px rgba(0,0,0,.45); font:12px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans",sans-serif;} .gha-card h3{margin:0 0 6px;font-size:13px;font-weight:600;} .gha-card p{margin:0;color:#9aa4b2;} .gha-toast{position:fixed;left:50%;bottom:36px;transform:translateX(-50%);z-index:2147483010; padding:9px 16px;border-radius:8px;background:rgba(22,27,34,.95);color:#e6edf3; border:1px solid rgba(255,255,255,.14);box-shadow:0 6px 24px rgba(0,0,0,.4); font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans",sans-serif; pointer-events:none;opacity:0;transition:opacity .16s ease;max-width:80vw;text-align:center;} .gha-toast[data-show="1"]{opacity:1;} `; function addStyle() { if (typeof GM_addStyle === "function") { try { GM_addStyle(CSS); return; } catch (e) { /* 落到原生方式 */ } } const s = document.createElement("style"); s.textContent = CSS; (document.head || document.documentElement).appendChild(s); } let toastTimer = null; function toast(msg, ms) { const old = document.querySelector(".gha-toast"); if (old) old.remove(); const el = document.createElement("div"); el.className = "gha-toast"; el.textContent = msg; document.body.appendChild(el); requestAnimationFrame(() => { el.dataset.show = "1"; }); clearTimeout(toastTimer); toastTimer = setTimeout(() => { delete el.dataset.show; setTimeout(() => el.remove(), 240); }, ms || 2200); } function copyText(text) { if (typeof GM_setClipboard === "function") { try { GM_setClipboard(text, { type: "text", mimetype: "text/plain" }); return true; } catch (e) { /* 落到兜底 */ } } try { const ta = document.createElement("textarea"); ta.value = text; ta.style.cssText = "position:fixed;left:-9999px;top:0;opacity:0;"; document.body.appendChild(ta); ta.select(); const ok = document.execCommand("copy"); ta.remove(); return ok; } catch (e) { return false; } } function notify(title, text) { if (typeof GM_notification !== "function") return; try { GM_notification({ title, text, timeout: 2600 }); } catch (e) { /* 忽略 */ } } const BOLT = ''; /* ================================================================== * 七、运行状态 * ================================================================== */ const S = { cfg: null, node: null, results: null, menu: [], ok: false }; // 给一个原始文件链接算出加速后的地址;blob 页则换成 raw 再加速 function accelerate(url) { if (!S.node) return url; const target = isBlobUrl(url) ? blobToRaw(url) : url; return proxify(S.node.host, target); } /* ================================================================== * 八、注入按钮 * ================================================================== */ const MARK = "ghaDone"; function makeButton(originalUrl, labelText) { const btn = document.createElement("button"); btn.type = "button"; btn.className = "gha-btn"; btn.dataset.ghaUrl = originalUrl; btn.title = `经 ${S.node.tag} 加速\n右键可复制加速链接\n${originalUrl}`; // 图标与文字都直接持有引用,不靠 querySelector 反查, // 这样改文案时不会出现「已复制加速下载」这种叠加错误。 const icon = document.createElement("span"); icon.innerHTML = BOLT; const label = document.createElement("span"); const defaultLabel = labelText || "加速下载"; label.textContent = defaultLabel; btn.appendChild(icon); btn.appendChild(label); btn.addEventListener("click", (ev) => { ev.preventDefault(); ev.stopPropagation(); const target = accelerate(originalUrl); copyText(target); btn.dataset.copied = "1"; label.textContent = "链接已复制"; setTimeout(() => { label.textContent = defaultLabel; delete btn.dataset.copied; }, 1700); window.open(target, "_blank", "noopener,noreferrer"); notify("GitHub 加速", `正在通过 ${S.node.tag} 下载`); }); // 右键直接复制加速链接,方便丢进 IDM / aria2 btn.addEventListener("contextmenu", (ev) => { ev.preventDefault(); ev.stopPropagation(); const target = accelerate(originalUrl); copyText(target); toast("已复制加速链接:" + target, 3200); }); return btn; } // 元素上记录的原始地址(可能已被改写,需要还原) function originalOf(el) { if (el.dataset.ghaOrig) return el.dataset.ghaOrig; const href = el.getAttribute("href") || el.href || ""; return deproxify(href) || href; } // release 资产行 function injectReleaseAssets() { let n = 0; document.querySelectorAll('a[href*="/releases/download/"]').forEach((a) => { if (a.dataset[MARK]) return; const url = originalOf(a); if (!isFileUrl(url)) return; a.dataset[MARK] = "1"; a.insertAdjacentElement("afterend", makeButton(url)); n++; }); return n; } // 「Download ZIP / tar.gz」源码包按钮 function injectArchiveButtons() { let n = 0; document.querySelectorAll('a[href*="/archive/"]').forEach((a) => { if (a.dataset[MARK]) return; const url = originalOf(a); if (!isFileUrl(url)) return; a.dataset[MARK] = "1"; const name = fileNameOf(url); const btn = makeButton(url, name ? `加速 ${name}` : "加速下载"); a.insertAdjacentElement("afterend", btn); n++; }); return n; } // 单文件页(/blob/)在标题旁给一个下载按钮 function injectBlobButton() { if (!isBlobUrl(location.href)) return 0; if (document.querySelector("[data-gha-blob]")) return 0; const anchor = document.querySelector('[data-testid="breadcrumbs"]') || document.querySelector('h1, [data-testid="blob-view-header"]'); if (!anchor || !anchor.parentElement) return 0; const btn = makeButton(location.href, "加速下载此文件"); btn.dataset.ghaBlob = "1"; btn.style.marginLeft = "10px"; anchor.parentElement.insertBefore(btn, anchor.nextSibling); return 1; } /* ================================================================== * 九、改写链接 * ================================================================== */ const REWRITE_SELECTOR = [ 'a[href*="/releases/download/"]', 'a[href*="/archive/"]', 'a[href*="raw.githubusercontent.com"]', 'a[href*="gist.githubusercontent.com"]', 'a[href*="/actions/runs/"]', ].join(","); function rewriteLinks() { let n = 0; document.querySelectorAll(REWRITE_SELECTOR).forEach((a) => { // 先取原始地址:已改写过就用存的,否则用当前 href let abs = a.dataset.ghaOrig; if (!abs) { const href = a.getAttribute("href"); if (!href) return; const u = parseUrl(href); if (!u) return; abs = u.href; if (!isFileUrl(abs)) return; a.dataset.ghaOrig = abs; n++; } if (!isFileUrl(abs)) return; // 值没变就不写:汉化的观察器与本模块共用同一棵 DOM, // 无谓的 setAttribute 会不断产生 mutation 记录,两边都会被拖着空跑。 const want = proxify(S.node.host, abs); if (a.getAttribute("href") !== want) a.setAttribute("href", want); const wantTitle = `已加速(${S.node.tag})\n${abs}`; if (a.getAttribute("title") !== wantTitle) a.title = wantTitle; }); return n; } // 切换节点后刷新所有已改写的链接与按钮提示 function refreshRewrites() { document.querySelectorAll("a[data-gha-orig]").forEach((a) => { const want = proxify(S.node.host, a.dataset.ghaOrig); if (a.getAttribute("href") !== want) a.setAttribute("href", want); a.title = `已加速(${S.node.tag})\n${a.dataset.ghaOrig}`; }); document.querySelectorAll(".gha-btn[data-gha-url]").forEach((b) => { b.title = `经 ${S.node.tag} 加速\n右键可复制加速链接\n${b.dataset.ghaUrl}`; }); } /* ================================================================== * 十、测速结果浮窗 * ================================================================== */ function showSpeedCard(items) { const old = document.querySelector(".gha-float"); if (old) old.remove(); const wrap = document.createElement("div"); wrap.className = "gha-float"; const card = document.createElement("div"); card.className = "gha-card"; const ok = items.filter((i) => i.ok); const rows = ok.slice(0, 7).map((i, idx) => `

${idx === 0 ? "🥇" : "·"} ${i.tag} — ${i.ms}ms

`).join(""); card.innerHTML = `

节点测速(${ok.length}/${items.length} 可用)

` + (rows || "

没有可用节点

") + `

当前:${S.node.tag}

`; const close = document.createElement("button"); close.type = "button"; close.className = "gha-btn"; close.textContent = "关闭"; close.style.margin = "10px 0 0"; close.addEventListener("click", () => wrap.remove()); card.appendChild(close); wrap.appendChild(card); document.body.appendChild(wrap); setTimeout(() => wrap.remove(), 15000); } /* ================================================================== * 十一、菜单 * ================================================================== */ function unregisterMenus() { if (typeof GM_unregisterMenuCommand !== "function") return; S.menu.forEach((id) => { try { GM_unregisterMenuCommand(id); } catch (e) { /* 忽略 */ } }); S.menu = []; } function addMenu(name, fn) { if (typeof GM_registerMenuCommand !== "function") return; try { const id = GM_registerMenuCommand(name, fn); if (id !== undefined) S.menu.push(id); } catch (e) { /* 忽略 */ } } async function doSpeedTest(showCard) { if (!gmxhr) { toast("当前环境不支持跨域请求,无法测速"); return; } toast("正在测速,请稍候…", 1600); const cfg = readConfig(); const items = await speedTest(cfg); S.results = { at: Date.now(), poolSize: poolFor(cfg).length, items }; const best = items.find((i) => i.ok); if (!best) { toast("所有节点都不可用;可尝试在设置里打开「包含失效节点」", 3600); return; } if (cfg.mode === "auto") { S.node = nodeOf(best.host, best.ms); refreshRewrites(); toast(`已切到 ${S.node.tag}(${best.ms}ms)`); } else { toast(`最快是 ${best.tag}(${best.ms}ms),当前手动模式未切换`, 3200); } if (showCard) showSpeedCard(items); } function registerMenus() { if (typeof GM_registerMenuCommand !== "function") return; unregisterMenus(); const cfg = S.cfg; addMenu(cfg.enabled ? "⏸ 关闭加速" : "▶️ 开启加速", () => { cfgSet(K.enabled, !cfg.enabled); location.reload(); }); addMenu(`🌐 当前节点:${S.node.tag}`, () => { toast(`当前:${S.node.host}${S.node.ms ? `(${S.node.ms}ms)` : ""}`, 3000); }); addMenu("⚡ 测速并切换最快节点", () => { doSpeedTest(true); }); addMenu("📊 查看测速结果", () => { const r = loadResults(readConfig()); if (!r) { toast("还没有有效测速结果,先执行一次测速"); return; } showSpeedCard(r.items); }); addMenu("📋 复制本页首个文件的加速链接", () => { const a = document.querySelector("a[data-gha-orig]"); if (!a) { toast("本页没有可加速的文件链接"); return; } const target = accelerate(a.dataset.ghaOrig); copyText(target); toast("已复制:" + target, 3400); }); addMenu("⚙️ 打开设置", () => { if (typeof CAT_userConfig === "function") { try { CAT_userConfig(); return; } catch (e) { /* 落到提示 */ } } toast("请在脚本猫脚本列表里打开本脚本的用户配置"); }); } /* ================================================================== * 十二、启动 * ================================================================== */ // 私有仓库的判断:GitHub 会在仓库页顶部放一个 Private 标记。 // 拿不到标记时按「公开」处理,避免误伤正常仓库。 function isPrivateRepoPage() { const pathname = (location && location.pathname) || ""; const m = pathname.match(/^\/([^/]+)\/([^/]+)/); if (!m) return false; const badge = document.querySelector( 'span[class*="Label"], [data-testid="visibility-label"], .Label--secondary' ); if (!badge) return false; return /^\s*private\s*$/i.test(badge.textContent || ""); } function applyAll() { if (!S.ok || !S.node || !S.cfg) return; // 私有仓库的文件要靠登录态才能下载,套上代理反而会 404/401,直接跳过 if (isPrivateRepoPage()) return 0; let n = 0; if (S.cfg.injectBtn) { n += injectReleaseAssets(); n += injectArchiveButtons(); n += injectBlobButton(); } if (S.cfg.rewrite) n += rewriteLinks(); return n; } let scheduled = null; function scheduleApply() { if (scheduled) return; scheduled = setTimeout(() => { scheduled = null; applyAll(); }, 480); } async function boot() { const cfg = readConfig(); S.cfg = cfg; if (!cfg.enabled) return; addStyle(); // 1) 先定一个节点让页面立刻可用:有缓存用缓存,没有就用首选节点。 // 绝不能在启动阶段阻塞测速 —— 58 个节点全测一轮要 30 秒以上, // 用户等不了,而且期间按钮/改写都不会生效。 let results = cfg.mode === "auto" ? loadResults(cfg) : null; S.results = results; S.node = pickNode(cfg, results); S.ok = true; // 2) 立即应用,用户马上就能看到按钮 applyAll(); // 3) 页面重渲染时补偿(release 切 tag、仓库换分支都会重建列表) const obs = new MutationObserver(scheduleApply); obs.observe(document.body, { childList: true, subtree: true }); // 4) 菜单(此时节点已确定,菜单里能显示正确名字) registerMenus(); // 5) 后台异步测速:没有有效缓存时才做,测完自动切到最快节点 const usable = results && results.items.some((i) => i.ok); if (cfg.mode === "auto" && cfg.autoTest && !usable && gmxhr) { speedTest(cfg) .then((items) => { S.results = { at: Date.now(), poolSize: poolFor(cfg).length, items }; const best = items.find((i) => i.ok); if (!best) return; S.node = nodeOf(best.host, best.ms); refreshRewrites(); registerMenus(); // 菜单里的节点名需要更新 toast(`已自动选择最快节点:${S.node.tag}(${best.ms}ms)`, 2600); }) .catch(() => { /* 测速失败就保持当前节点,不影响使用 */ }); } } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", boot, { once: true }); } else { boot(); }})();