跳到正文

剪贴板

剪贴板 6ek6bya3

__Hel_Y__
原文
剪贴板信息

剪贴板信息

发布
收录
更新

LGSS

JavaScript
// ==UserScript==
// @name         Luogu Seamless Saver (LGSS)
// @namespace    https://www.luogu.com.cn/user/1447705
// @version      1.5.1
// @description  无缝访问文章与剪贴板,可互动,无 iframe,不需要模板文章/剪贴板,对洛谷损失可以忽略为零,用户可以正常使用洛谷
// @author       Hel_Y
// @match        *://www.luogu.com.cn/*
// @run-at       document-start
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @connect      api.luogu.me
// @connect      fecdn.luogu.com.cn
// @connect      www.luogu.com.cn
// @license      MIT
// @require      https://cdn.jsdelivr.net/npm/sweetalert2@latest
// @resource swalJs https://cdn.jsdelivr.net/npm/sweetalert2@latest/dist/sweetalert2.min.js
// @resource swalCss https://cdn.jsdelivr.net/npm/sweetalert2@latest/dist/sweetalert2.min.css
// ==/UserScript==

(function () {
    'use strict';
    const HTML_ESC = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
    function escHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c => HTML_ESC[c]);
    }
    function safeJson(obj) {
        return JSON.stringify(obj)
            .replace(/<\//g, '<\\/')
            .replace(/\u2028/g, '\\u2028')
            .replace(/\u2029/g, '\\u2029');
    }
    function gmRequest({ method = 'GET', url, headers, data, timeout }) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method, url, headers, data, timeout,
                onload: res => resolve(res),
                onerror: () => reject(new Error('网络请求失败')),
                ontimeout: () => reject(new Error('请求超时'))
            });
        });
    }
    async function gmJson(options) {
        const res = await gmRequest(options);
        if (res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res.status}`);
        try {
            return JSON.parse(res.responseText);
        } catch (e) {
            throw new Error('返回数据不是合法 JSON');
        }
    }
    function toSeconds(v) {
        if (v === undefined || v === null) return null;
        if (typeof v === 'number') return v > 1e12 ? Math.floor(v / 1000) : v;
        const t = Date.parse(v);
        return Number.isNaN(t) ? null : Math.floor(t / 1000);
    }
    function showWelcome() {
        if (GM_getValue("welcomelgss1", false)) return;
        const dialog = () => {
            if (typeof Swal === 'undefined') {
                console.warn('[LGSS] SweetAlert2 未加载');
                return;
            }
            fireSwal({
                title: '欢迎使用 LGSS',
                html: `
                    <div style="text-align: left; max-height: 400px; overflow-y: auto; padding: 10px; font-size: 14px; line-height: 1.7;">
                        <p>欢迎使用 Luogu Seamless Saver(LGSS)!</p>
                        <h4>功能</h4>
                        <ul style="padding-left: 20px; margin: 5px 0;">
                            <li>您可以在国内无缝访问只能在国际站查看的文章/剪贴板;</li>
                            <li>可以互动(收藏、点赞、不推荐、评论、删除评论)。</li>
                        </ul>
                        <h4>友情提醒</h4>
                        <p>本插件</p>
                        <ul style="padding-left: 20px; margin: 5px 0;">
                            <li>不会高频访问洛谷 API;</li>
                            <li>只会从洛谷保存站获取数据;</li>
                            <li>只会在加载时调用一次模板新/旧前端界面,并不会对洛谷造成伤害,用户可以正常使用洛谷。</li>
                            <li>加载时会重写文档(Document was reset),属于正常现象。</li>
                        </ul>
                        <p>我们只会收集一些资料构造界面,剩余的时间交给洛谷。</p>
                        <h4>灵感来源</h4>
                        <a href="https://www.luogu.com.cn/article/bq5o089x">在洛谷内无缝访问所有文章。</a>
                    </div>
                `,
                width: '600px',
                confirmButtonText: "我已知晓,开始使用",
                allowOutsideClick: false,
                allowEscapeKey: false,
            }).then(() => GM_setValue("welcomelgss1", true));
        };
        if (document.readyState === 'complete') {
            setTimeout(dialog, 300);
        } else {
            window.addEventListener('load', () => setTimeout(dialog, 300), { once: true });
        }
    }
    function showUpdate() {
        if (GM_getValue("updatelgss150", false)) return;
        const dialog = () => {
            if (typeof Swal === 'undefined') {
                console.warn('[LGSS] SweetAlert2 未加载');
                return;
            }
            fireSwal({
                title: 'LGSS 1.5.0 更新',
                html: `
                    <div style="text-align: left; max-height: 400px; overflow-y: auto; padding: 10px; font-size: 14px; line-height: 1.7;">
                        <h4>bug fix</h4>
                        <ul style="padding-left: 20px; margin: 5px 0;">
                            <li>解决页面私信无红点的 bug;</li>
                            <li>解决因 SPA 导致页面无法渲染;</li>
                            <li>解决 document.write 后 Swal 弹窗失效的 bug(改用 @resource 本地注入);</li>
                            <li>……</li>
                        </ul>
                        <h4>新功能</h4>
                        <ul style="padding-left: 20px; margin: 5px 0;">
                            <li>用户主页新增「个人介绍」卡片,从保存站获取,支持手动更新;</li>
                            <li>文章/剪贴板「更新」按钮移入页面内嵌位置,移除悬浮按钮;</li>
                        </ul>
                    </div>
                `,
                width: '600px',
                confirmButtonText: "我已知晓",
                allowOutsideClick: false,
                allowEscapeKey: false,
            }).then(() => GM_setValue("updatelgss150", true));
        };
        if (document.readyState === 'complete') {
            setTimeout(dialog, 300);
        } else {
            window.addEventListener('load', () => setTimeout(dialog, 300), { once: true });
        }
    }
    showWelcome();
    showUpdate();
    const pathParts = window.location.pathname.split('/').filter(p => p);
    let pageType = pathParts[0] || '';
    let itemId = pathParts[1] || '';
    console.log(`[LGSS] 页面: ${pageType || '(首页)'}${itemId ? ',ID = ' + itemId : ''}`);
    const isArticle = () => pageType === 'article';
    function isUserHome() {
        const parts = location.pathname.split('/').filter(p => p);
        return parts[0] === 'user' && parts.length === 2;
    }
    const typeLabel = () => (isArticle() ? '文章' : '剪贴板');
    const workflowName = () => (isArticle() ? 'article-save-pipeline' : 'paste-save-pipeline');
    const saveStationUrl = id => `https://www.luogu.me/${pageType}/${id}`;
    let loaderVersion = null;
    let vendorVersion = null;
    let csrfToken = null;
    let feConfigVersion = null;
    let luoguTagVersion = null;
    let themeScript = '';
    let customStyle = '';
    let currentUser = null;
    let lgssLoaded = false;
    let lastRenderedContent = null;
    let lastRenderedType = null;
    let lastRenderedId = null;
    async function fetchSaveArticle(id) {
        const json = await gmJson({ url: `https://api.luogu.me/article/query/${id}` });
        if (json.code !== 200 || !json.data) throw new Error('API 数据异常');
        const data = json.data;
        if (!data.time && data.id) {
            try {
                const off = await gmJson({ url: `https://www.luogu.com.cn/api/article/${data.id}` });
                if (off.code === 200 && off.data && off.data.time) {
                    data.time = off.data.time;
                    console.log('[LGSS] 从官方 API 补充 time:', data.time);
                }
            } catch (e) { /* 忽略 */ }
        }
        return data;
    }
    async function fetchSavePaste(id) {
        const json = await gmJson({ url: `https://api.luogu.me/paste/query/${id}` });
        if (json.code !== 200 || !json.data) throw new Error('API 数据异常');
        return json.data;
    }
    function waitForTask(taskId, { maxAttempts = 300, interval = 1000 } = {}) {
        return new Promise((resolve, reject) => {
            let attempts = 0;
            let cancelled = false;
            const tick = async () => {
                if (cancelled) return;
                attempts++;
                try {
                    const json = await gmJson({ url: `https://api.luogu.me/task/query/${taskId}` });
                    if (json.code === 200 && json.data) {
                        if (json.data.status === 2) { cancelled = true; resolve(); return; }
                        if (json.data.status === 3) {
                            cancelled = true;
                            reject(new Error(json.data.info || '任务执行失败'));
                            return;
                        }
                    }
                } catch (e) { /* 网络抖动忽略 */ }
                if (attempts >= maxAttempts) {
                    cancelled = true;
                    reject(new Error('轮询超时'));
                    return;
                }
                setTimeout(tick, interval);
            };
            tick();
        });
    }

    async function triggerSave(id, wfName) {
        const name = wfName || workflowName();
        const res = await gmJson({
            method: 'POST',
            url: `https://api.luogu.me/workflow/create/template/${name}`,
            headers: { 'Content-Type': 'application/json' },
            data: JSON.stringify({ targetId: id }),
            timeout: 10000
        });
        if (res.code !== 200) throw new Error(res.message || '工作流启动失败');
        const saveTaskId = res.data && res.data.taskIds && res.data.taskIds.save;
        if (!saveTaskId) throw new Error('未返回任务ID');
        await waitForTask(saveTaskId);
    }

    async function ensureSavedOnStation(type, id) {
        let fetched;
        try {
            fetched = type === 'article' ? await fetchSaveArticle(id) : await fetchSavePaste(id);
            return { kind: 'data', data: fetched };
        } catch (fetchErr) {
            const msg = fetchErr.message || '';
            // 改:只有"保存站明确无数据"或 4xx 才询问;网络错误/超时/解析失败直接抛
            const isNoData = /API 数据异常/.test(msg) || /HTTP 4\d\d/.test(msg);
            if (!isNoData) throw fetchErr;
            const result = await fireSwal({
                icon: 'warning',
                title: '保存站无数据',
                text: `确定要将${typeLabel()}保存到保存站吗?`,
                showCancelButton: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            });
            if (!result.isConfirmed) throw fetchErr;
            fireSwal({
                title: `正在保存${typeLabel()}`,
                html: '请稍候(最长约 5 分钟)',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => Swal.showLoading(),
            });
            keepSwalAlive(3000);
            await triggerSave(id);
            return { kind: 'saved-need-reload' };
        }
    }
    function showErrorWithOptions(message, type, id) {
        stopSwalKeepAlive();
        Swal.close();
        return Swal.fire({
            icon: 'error',
            title: '加载失败',
            text: message,
            showCancelButton: true,
            confirmButtonText: "刷新",
            cancelButtonText: "跳转到保存站",
        }).then(result => {
            if (result.isConfirmed) {
                location.reload();
            } else if (result.dismiss === Swal.DismissReason.cancel) {
                window.location.href = saveStationUrl(id);
            }
        });
    }
async function lgssManualSave(id) {
    console.log('[LGSS] 手动保存开始,id:', id);
    try {
        await triggerSave(id);

        // 重新拉取保存站数据,判断内容是否真的有变化
        let newData;
        try {
            newData = isArticle()
                ? await fetchSaveArticle(id)
                : await fetchSavePaste(id);
        } catch (fetchErr) {
            console.warn('[LGSS] 更新后获取保存站数据失败,回退刷新:', fetchErr);
            lgssLoaded = false;
            handleBlocked('after-update');
            return;
        }

        const newContent = isArticle()
            ? (newData.content || '')
            : (newData.content || newData.data || '');

        const sameType = lastRenderedType === pageType;
        const sameId   = lastRenderedId === String(id);
        const sameBody = lastRenderedContent !== null
            && newContent === lastRenderedContent;

        if (sameType && sameId && sameBody) {
            console.log('[LGSS] 内容未变化,跳过刷新');
            stopSwalKeepAlive();
            Swal.close();
            setAllActionButtons(false);
            fireSwal({
                icon: 'info',
                title: '无需更新',
                html: `当前${typeLabel()}已是最新版本`,
                confirmButtonText: '确定',
            });
            return;
        }

        console.log('[LGSS] 保存任务完成且内容有变化,即将刷新页面');
        lgssLoaded = false;
        handleBlocked('after-update');
    } catch (err) {
        console.error('[LGSS] 手动保存失败:', err);
        stopSwalKeepAlive();
        Swal.fire({
            icon: 'error',
            title: '更新失败',
            text: err.message,
            confirmButtonText: '确定',
        });
        setAllActionButtons(false);
        throw err;
    }
}
    function isBlocked() {
        if (document.title === '安全访问中心 - 洛谷') return true;
        const h3s = document.querySelectorAll('h3');
        for (const h3 of h3s) {
            if (h3.textContent.trim() === '即将离开洛谷') return true;
        }
        const card = document.querySelector('.card');
        if (card && card.querySelector('h3') && card.querySelector('h3').textContent.includes('即将离开洛谷')) {
            return true;
        }
        return false;
    }
    async function fetchTemplateVersions(mode) {
        try {
            const currentHtml = document.documentElement.innerHTML;
            const csrfMatch = currentHtml.match(/<meta name="csrf-token" content="([^"]+)"/);
            if (csrfMatch) csrfToken = csrfMatch[1];
            let html;
            try {
                const gmRes = await gmRequest({
                    url: 'https://www.luogu.com.cn/ranking',
                    headers: { 'Accept': 'text/html,application/xhtml+xml' }
                });
                if (gmRes.status < 200 || gmRes.status >= 300) throw new Error('HTTP ' + gmRes.status);
                html = gmRes.responseText;
            } catch (gmErr) {
                console.warn('[LGSS] GM 抓排行榜失败,退回 fetch:', gmErr.message);
                const res = await fetch('https://www.luogu.com.cn/ranking');
                if (!res.ok) throw new Error('排行榜加载失败');
                html = await res.text();
            }
            const loaderMatch = html.match(/<script[^>]*src="[^"]*\/loader\.([^"]+)\.js"/);
            if (!loaderMatch) throw new Error('未找到新前端 loader 版本');
            loaderVersion = loaderMatch[1];
            const vendorMatch = html.match(/<script[^>]*src="[^"]*\/vendor\.([^"]+)\.js"/);
            vendorVersion = vendorMatch ? vendorMatch[1] : loaderVersion;
            if (!csrfToken) {
                const csrfRank = html.match(/<meta name="csrf-token" content="([^"]+)"/);
                if (csrfRank) csrfToken = csrfRank[1];
            }
            const configMatch = html.match(/window\.__feConfigVersion\s*=\s*'([^']+)'/);
            if (configMatch) feConfigVersion = configMatch[1];
            const tagMatch = html.match(/window\.__luoguTagVersion\s*=\s*'([^']+)'/);
            if (tagMatch) luoguTagVersion = tagMatch[1];
            const themeMatch = html.match(/<script id="luogu-theme" type="application\/json">(.*?)<\/script>/s);
            if (themeMatch) {
                try {
                    themeScript = `<script id="luogu-theme" type="application/json">${safeJson(JSON.parse(themeMatch[1]))}</script>`;
                } catch (e) {}
            }
            if (!themeScript) {
                const ctxMatch = html.match(/<script id="lentille-context" type="application\/json">(.*?)<\/script>/s);
                if (ctxMatch) {
                    try {
                        const ctx = JSON.parse(ctxMatch[1]);
                        if (ctx.user && ctx.user.theme) {
                            themeScript = `<script id="luogu-theme" type="application/json">${safeJson(ctx.user.theme)}</script>`;
                        }
                    } catch (e) { /* ignore */ }
                }
            }
            if (!themeScript) {
                const defaultTheme = { id: 0, header: {}, sideNav: { color: [0, 0, 0, 1] }, footer: {} };
                themeScript = `<script id="luogu-theme" type="application/json">${safeJson(defaultTheme)}</script>`;
            }
            const styleMatch = html.match(/<style>([\s\S]*?)<\/style>/);
            customStyle = styleMatch ? `<style>${styleMatch[1]}</style>` : '';
            const contextMatch = html.match(/<script id="lentille-context" type="application\/json">(.*?)<\/script>/s);
            if (contextMatch) {
                try {
                    const contextData = JSON.parse(contextMatch[1]);
                    if (contextData.user && contextData.user.uid) {
                        currentUser = contextData.user;
                        console.log('[LGSS] 用户:', currentUser.name, '(UID:', currentUser.uid + ')');
                    }
                } catch (e) {}
            }
            console.log('[LGSS] 模式:', mode, '新前端版本:', loaderVersion);
            return true;
        } catch (e) {
            console.error('[LGSS] 获取版本失败:', e);
            return false;
        }
    }
    function getInlineSwal() {
        try {
            if (typeof GM_getResourceText === 'function') {
                const js = GM_getResourceText('swalJs') || '';
                if (js) {
                    // 防止 Swal 代码里的 </script> 提前结束标签
                    return `<script>${js.replace(/<\/script>/gi, '<\\/script>')}<\/script>`;
                }
            }
        } catch (e) {
            console.warn('[LGSS] 读取本地 Swal 资源失败,退回 CDN:', e);
        }
        return `<script src="https://cdn.jsdelivr.net/npm/sweetalert2@latest"><\/script>`;
    }
    function getInlineSwalCss() {
        const css = savedSwalCss || loadSwalCssFromResource();
        return css ? `<style>${css}</style>` : '';
    }
    let lastSwalOptions = null;
    let savedSwalCss = null;
    let swalStyleObserver = null;
    function loadSwalCssFromResource() {
        if (savedSwalCss) return savedSwalCss;
        try {
            if (typeof GM_getResourceText === 'function') {
                const css = GM_getResourceText('swalCss');
                if (css) {
                    savedSwalCss = css;
                    console.log('[LGSS] 从 @resource 加载 Swal CSS,长度:', css.length);
                }
            }
        } catch (e) {
            console.warn('[LGSS] 读取 Swal CSS 资源失败:', e);
        }
        return savedSwalCss;
    }
    function captureSwalCss() {
        if (savedSwalCss || !document.head) return;
        for (const s of document.head.querySelectorAll('style')) {
            const txt = s.textContent || '';
            if (txt.includes('.swal2-container') && txt.includes('.swal2-popup')) {
                savedSwalCss = txt;
                console.log('[LGSS] 从现有 style 缓存 Swal CSS,长度:', txt.length);
                return;
            }
        }
    }
    function ensureSwalStyleAlive() {
        if (!document.head) return;
        for (const s of document.head.querySelectorAll('style')) {
            if ((s.textContent || '').includes('.swal2-container')) return;
        }
        const css = savedSwalCss || loadSwalCssFromResource() || (captureSwalCss(), savedSwalCss);
        if (!css) {
            console.warn('[LGSS] Swal CSS 不可用,无法注入');
            return;
        }
        const ns = document.createElement('style');
        ns.setAttribute('data-lgss-swal', '1');
        ns.textContent = css;
        document.head.appendChild(ns);
        console.log('[LGSS] Swal 样式已注入');
    }
    function fireSwal(options) {
        lastSwalOptions = options;
        ensureSwalStyleAlive();
        const p = Swal.fire(options);
        setTimeout(captureSwalCss, 0);
        return p.then(r => {
            if (lastSwalOptions === options) lastSwalOptions = null;
            return r;
        });
    }
    function installSwalStyleGuard() {
        if (swalStyleObserver) return;
        if (!document.head) { setTimeout(installSwalStyleGuard, 20); return; }
        ensureSwalStyleAlive();
        swalStyleObserver = new MutationObserver(() => ensureSwalStyleAlive());
        swalStyleObserver.observe(document.head, { childList: true });
    }
    function uninstallSwalStyleGuard() {
        if (swalStyleObserver) { swalStyleObserver.disconnect(); swalStyleObserver = null; }
    }
    function keepSwalAlive() { installSwalStyleGuard(); }
    function stopSwalKeepAlive() { uninstallSwalStyleGuard(); lastSwalOptions = null; }
    loadSwalCssFromResource();
const ACTION_BTN_ICON_PATH = 'M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160H336c-17.7 0-32 14.3-32 32s14.3 32 32 32H463.5c0 0 0 0 0 0h.4c17.7 0 32-14.3 32-32V64c0-17.7-14.3-32-32-32s-32 14.3-32 32v51.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1V448c0 17.7 14.3 32 32 32s32-14.3 32-32V396.9l17.6 17.5c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.7c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352H176c17.7 0 32-14.3 32-32s-14.3-32-32-32H48.4c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z';

let actionsObserver = null;

function injectActionButton() {
    if (!isArticle()) return 'skip';
    const all = document.querySelectorAll('.actions');
    if (!all.length) return 'wait';
    let anyDone = false;
    for (const actions of all) {
        if (actions.querySelector('.lgss-action-btn')) { anyDone = true; continue; }
        const btn = document.createElement('div');
        btn.className = 'button-2line lgss-action-btn';
        btn.setAttribute('data-v-1ddadd0a', '');
        btn.setAttribute('data-v-0928b76c', '');
        btn.innerHTML = `
            <svg data-v-1ddadd0a class="svg-inline--fa fa-arrows-rotate icon" data-prefix="fas" data-icon="arrows-rotate" role="img" viewBox="0 0 512 512" aria-hidden="true">
                <path fill="currentColor" d="${ACTION_BTN_ICON_PATH}"></path>
            </svg>
            <span data-v-1ddadd0a class="text">更新</span>
        `;
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            handleActionButtonClick(btn);
        });
        actions.appendChild(btn);
        anyDone = true;
        console.log('[LGSS] 更新按钮已注入 .actions', actions.className);
    }
    return anyDone ? 'done' : 'wait';
}

function setAllActionButtons(loading) {
    document.querySelectorAll('.lgss-action-btn, .lgss-paste-btn').forEach(btn => {
        btn.dataset.lgssLoading = loading ? '1' : '';
        btn.disabled = loading;
        btn.style.pointerEvents = loading ? 'none' : '';
        btn.style.opacity = loading ? '0.55' : '';
        const label = loading ? '更新中' : '更新';
        const textEl = btn.querySelector('.text');
        if (textEl) textEl.textContent = label;
        else btn.textContent = label;
    });
}

function handleActionButtonClick() {
    if (document.querySelector('[data-lgss-loading="1"]')) return;
    setAllActionButtons(true);
    fireSwal({
        title: `正在更新${typeLabel()}`,
        html: '请稍候',
        allowOutsideClick: false,
        allowEscapeKey: false,
        didOpen: () => Swal.showLoading(),
    });
    keepSwalAlive();
    lgssManualSave(itemId).catch(() => {
        setAllActionButtons(false);
    });
}

function watchActionsForButton() {
    if (!isArticle()) return;
    const status = injectActionButton();
    if (status === 'done' || status === 'skip') return;
    if (actionsObserver) actionsObserver.disconnect();
    actionsObserver = new MutationObserver(() => {
        const s = injectActionButton();
        if (s === 'done' || s === 'skip') {
            actionsObserver.disconnect();
            actionsObserver = null;
        }
    });
    actionsObserver.observe(document.body || document.documentElement, {
        childList: true,
        subtree: true,
    });
    setTimeout(() => {
        if (actionsObserver) {
            actionsObserver.disconnect();
            actionsObserver = null;
        }
    }, 60000);
}
let pasteBtnObserver = null;

function injectPasteButton() {
    if (pageType !== 'paste') return 'skip';
    const headers = document.querySelectorAll('.header-card');
    if (!headers.length) return 'wait';
    let anyDone = false;
    for (const header of headers) {
        const right = header.querySelector('.right');
        if (!right) continue;
        let actionsDiv = right.querySelector('.btn-actions');
        if (!actionsDiv) {
            const innerDiv = right.querySelector(':scope > div');
            if (!innerDiv) continue;
            innerDiv.classList.add('btn-actions');
            actionsDiv = innerDiv;
        }
        if (actionsDiv.querySelector('.lgss-paste-btn')) { anyDone = true; continue; }
        const btn = document.createElement('button');
        btn.className = 'lform-size-middle lcolor-var-cyan-3 lgss-paste-btn';
        btn.type = 'button';
        btn.setAttribute('data-v-505b6a97', '');
        btn.setAttribute('data-v-97240130', '');
        btn.textContent = '更新';
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            handleActionButtonClick(btn);
        });
        const backBtn = actionsDiv.querySelector('a');
        if (backBtn) actionsDiv.insertBefore(btn, backBtn);
        else actionsDiv.appendChild(btn);
        anyDone = true;
        console.log('[LGSS] 更新按钮已注入 header-card');
    }
    return anyDone ? 'done' : 'wait';
}

function watchPasteButton() {
    if (pageType !== 'paste') return;
    const status = injectPasteButton();
    if (status === 'done' || status === 'skip') return;
    if (pasteBtnObserver) pasteBtnObserver.disconnect();
    pasteBtnObserver = new MutationObserver(() => {
        const s = injectPasteButton();
        if (s === 'done' || s === 'skip') {
            pasteBtnObserver.disconnect();
            pasteBtnObserver = null;
        }
    });
    pasteBtnObserver.observe(document.body || document.documentElement, {
        childList: true,
        subtree: true,
    });
    setTimeout(() => {
        if (pasteBtnObserver) {
            pasteBtnObserver.disconnect();
            pasteBtnObserver = null;
        }
    }, 60000);
}
    let introObserver = null;
    let introFetching = false;

    async function fetchSaveUserIntro(uid) {
        const json = await gmJson({ url: `https://api.luogu.me/user/query/${uid}` });
        if (json.code !== 200 || !json.data) throw new Error('API 数据异常');
        const data = json.data;
        return {
            html: data.rendered_introduction || '',
            markdown: data.introduction || '',
        };
    }

    async function renderMarkdown(md) {
        const json = await gmJson({
            method: 'POST',
            url: 'https://api.luogu.me/markdown/render',
            headers: { 'Content-Type': 'application/json' },
            data: JSON.stringify({ content: md }),
            timeout: 15000
        });
        if (json.code !== 200 || !json.data) throw new Error('渲染接口返回异常');
        if (typeof json.data === 'string') return json.data;
        return json.data.html || json.data.content || json.data.rendered || '';
    }

    function buildIntroCard(data) {
        const card = document.createElement('div');
        card.className = 'l-card lgss-intro-card';
        card.setAttribute('data-v-176b97b3', '');
        card.setAttribute('data-v-331a1dc7', '');
        card.setAttribute('data-v-754e1ea4-s', '');
        card.innerHTML = `
            <div data-v-331a1dc7 class="header">
                <h3 data-v-331a1dc7 style="margin: 0px;">个人介绍</h3>
                <span data-v-331a1dc7 class="edit-button">
                    <button data-v-505b6a97 data-v-331a1dc7 class="lform-size-small lgss-intro-btn" type="button">更新</button>
                </span>
            </div>
            <div data-v-41d58f46 data-v-331a1dc7 class="lfe-marked-wrap introduction">
                <div data-v-41d58f46 class="lfe-marked"></div>
            </div>
        `;
        const markedDiv = card.querySelector('.lfe-marked');
        if (data && data.html) {
            markedDiv.innerHTML = data.html;
        } else if (data && data.markdown) {
            markedDiv.innerHTML = `<pre style="white-space:pre-wrap;color:#666;">${escHtml(data.markdown)}</pre>`;
        } else {
            markedDiv.innerHTML = '<p>这个人很懒,什么都没写</p>';
        }
        card.querySelector('.lgss-intro-btn').addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            handleIntroUpdate(e.currentTarget);
        });
        return card;
    }

    async function handleIntroUpdate(btn) {
        if (btn.dataset.lgssLoading === '1') return;
        btn.dataset.lgssLoading = '1';
        btn.disabled = true;
        btn.textContent = '更新中';
        fireSwal({
            title: '正在更新个人介绍',
            html: '请稍候',
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading(),
        });
        keepSwalAlive();
        try {
            await triggerSave(itemId, 'user-introduction-save-pipeline');
            const data = await fetchSaveUserIntro(itemId);
            if (!data.html && data.markdown) {
                try {
                    const html = await renderMarkdown(data.markdown);
                    if (html) data.html = html;
                } catch (e) {
                    console.warn('[LGSS] 实时渲染失败,降级显示 Markdown:', e.message);
                }
            }
            const card = document.querySelector('.lgss-intro-card');
            if (card) {
                const markedDiv = card.querySelector('.lfe-marked');
                if (data.html) {
                    markedDiv.innerHTML = data.html;
                } else if (data.markdown) {
                    markedDiv.innerHTML = `<pre style="white-space:pre-wrap;color:#666;">${escHtml(data.markdown)}</pre>`;
                } else {
                    markedDiv.innerHTML = '<p>这个人很懒,什么都没写</p>';
                }
            }
            btn.textContent = '更新';
            btn.disabled = false;
            btn.dataset.lgssLoading = '';
            stopSwalKeepAlive();
            Swal.close();
        } catch (err) {
            stopSwalKeepAlive();
            Swal.fire({ icon: 'error', title: '更新失败', text: err.message, confirmButtonText: '确定' });
            btn.textContent = '更新';
            btn.disabled = false;
            btn.dataset.lgssLoading = '';
        }
    }

    function findIntroAnchor() {
        const cards = document.querySelectorAll('.main > .l-card');
        let fallback = null;
        for (const card of cards) {
            if (card.classList.contains('lgss-intro-card')) continue;
            const h3 = card.querySelector('h3.lfe-h3');
            if (!h3) continue;
            const text = h3.textContent.trim();
            if (text.includes('比赛等级分趋势图')) return card;
            if (text.includes('做题趋势热度图')) fallback = card;
        }
        return fallback;
    }

    function hasOfficialIntroCard() {
        const cards = document.querySelectorAll('.main .l-card');
        for (const card of cards) {
            if (card.classList.contains('lgss-intro-card')) continue;
            const h3 = card.querySelector('h3');
            if (h3 && h3.textContent.trim().includes('个人介绍')) return true;
        }
        return false;
    }

    function removeInjectedIntroCard() {
        document.querySelectorAll('.lgss-intro-card').forEach(el => el.remove());
    }

    async function injectIntroCard() {
        if (!isUserHome()) return 'skip';

        if (hasOfficialIntroCard()) {
            removeInjectedIntroCard();
            return 'skip';
        }

        if (document.querySelector('.lgss-intro-card')) return 'done';

        if (introFetching) return 'wait';
        const anchor = findIntroAnchor();
        if (!anchor) return 'wait';

        introFetching = true;
        let data;
        try {
            data = await fetchSaveUserIntro(itemId);
        } catch (e) {
            console.warn('[LGSS] 获取个人介绍失败,跳过注入:', e.message);
            introFetching = false;
            return 'skip';
        }
        introFetching = false;

        if (!isUserHome()) return 'skip';
        if (hasOfficialIntroCard()) return 'skip';
        if (document.querySelector('.lgss-intro-card')) return 'done';

        if (!data || (!data.html && !data.markdown)) {
            console.log('[LGSS] 保存站个人介绍为空,不注入');
            return 'skip';
        }

        // 没有 rendered_introduction 时,调 /markdown/render 现场渲染
        if (!data.html && data.markdown) {
            try {
                const html = await renderMarkdown(data.markdown);
                if (html) data.html = html;
            } catch (e) {
                console.warn('[LGSS] 实时渲染个人介绍失败,降级显示原始 Markdown:', e.message);
            }
        }

        if (!isUserHome()) return 'skip';
        if (hasOfficialIntroCard()) return 'skip';
        if (document.querySelector('.lgss-intro-card')) return 'done';

        const anchor2 = findIntroAnchor() || anchor;
        const card = buildIntroCard(data);
        anchor2.parentNode.insertBefore(card, anchor2.nextSibling);
        console.log('[LGSS] 个人介绍卡片已注入');
        return 'done';
    }

    function watchIntroCard() {
        if (!isUserHome()) return;

        removeInjectedIntroCard();
        if (introObserver) { introObserver.disconnect(); introObserver = null; }

        const tick = () => {
            if (!isUserHome()) {
                removeInjectedIntroCard();
                if (introObserver) { introObserver.disconnect(); introObserver = null; }
                return;
            }
            if (hasOfficialIntroCard()) {
                removeInjectedIntroCard();
                return;
            }
            injectIntroCard();
        };

        tick();

        introObserver = new MutationObserver(tick);
        introObserver.observe(document.body || document.documentElement, {
            childList: true,
            subtree: true,
        });

        setTimeout(() => {
            if (introObserver) { introObserver.disconnect(); introObserver = null; }
        }, 30000);
    }
    const DISABLE_ZERO_LINKS_SCRIPT = `
<script>
(function() {
    function disableZeroLinks() {
        document.querySelectorAll('a[href^="/user/0"]').forEach(function(el) {
            el.removeAttribute('href');
            el.style.cursor = 'default';
            el.style.pointerEvents = 'none';
            el.title = '用户信息不可用';
        });
    }
    if (document.body) {
        disableZeroLinks();
        new MutationObserver(disableZeroLinks)
            .observe(document.body, { childList: true, subtree: true });
    }
})();
</script>`;
    const CSP_META = 'default-src \'unsafe-eval\' \'unsafe-inline\' luogu.com *.luogu.com luogu.com.cn *.luogu.com.cn luogu.org *.luogu.org wss: blob: luoguprivate.oss-cn-hangzhou.aliyuncs.com luogu.oss-cn-hangzhou.aliyuncs.com https://challenges.cloudflare.com https://*.dun.163yun.com https://*.dun.163.com https://*.nosdn.126.net https://*.nosdn.127.net https://nos.netease.com https://cstaticdun.126.net https://cstaticdun1.126.net https://cstaticdun-v6.126.net https://acstatic-dun.126.net; img-src * data:; font-src * data:; worker-src data: blob:; frame-src https://fecdn.luogu.com.cn https://player.bilibili.com https://www.bilibili.com https://challenges.cloudflare.com';
    function buildArticleHtml(articleData) {
        const userData = currentUser || {
            uid: 0, avatar: '', name: '', slogan: '', badge: null,
            isAdmin: false, isBanned: false, color: 'Green',
            ccfLevel: 0, xcpcLevel: 0, background: '', verified: false,
            eloValue: 0, followingCount: 0, followerCount: 0, ranking: 0,
            unreadMessageCount: 0, unreadNoticeCount: 0, learnMode: false
        };
        const publishTimestamp = toSeconds(articleData.time)
            ?? toSeconds(articleData.createdAt)
            ?? Math.floor(Date.now() / 1000);
        const publishDate = new Date(publishTimestamp * 1000);
        const isoString = publishDate.toISOString();
        const authorId = (articleData.author && articleData.author.id) || 0;
        const fakeContext = {
            instance: "main",
            template: "article.show",
            data: {
                article: {
                    id: articleData.id || itemId,
                    title: articleData.title || '无标题',
                    category: articleData.category || 3,
                    time: publishTimestamp,
                    author: {
                        uid: authorId,
                        avatar: (articleData.author && articleData.author.avatar) || `https://cdn.luogu.com.cn/upload/usericon/${authorId}.png`,
                        name: (articleData.author && articleData.author.name) || '保存站用户',
                        slogan: (articleData.author && articleData.author.slogan) || '',
                        badge: null,
                        isAdmin: false,
                        isBanned: false,
                        color: (articleData.author && articleData.author.color) || 'Green',
                        ccfLevel: 0,
                        xcpcLevel: 0,
                        background: (articleData.author && articleData.author.background) || ''
                    },
                    upvote: articleData.upvote || 0,
                    replyCount: articleData.replyCount || 0,
                    favorCount: articleData.favorCount || 0,
                    status: 2,
                    solutionFor: null,
                    promoteStatus: 2,
                    collection: null,
                    content: articleData.content || '',
                    contentFull: true,
                    adminNote: null,
                    voted: 0,
                    canReply: true,
                    canEdit: false
                },
                favored: false,
                voted: 0,
                canReply: true,
                canEdit: false
            },
            user: {
                uid: userData.uid || 0,
                avatar: userData.avatar || '',
                name: userData.name || '',
                slogan: userData.slogan || '',
                badge: userData.badge || null,
                isAdmin: !!userData.isAdmin,
                isBanned: !!userData.isBanned,
                color: userData.color || 'Green',
                ccfLevel: userData.ccfLevel || 0,
                xcpcLevel: userData.xcpcLevel || 0,
                background: userData.background || '',
                verified: !!userData.verified,
                eloValue: userData.eloValue || 0,
                followingCount: userData.followingCount || 0,
                followerCount: userData.followerCount || 0,
                ranking: userData.ranking || 0,
                unreadMessageCount: userData.unreadMessageCount || 0,
                unreadNoticeCount: userData.unreadNoticeCount || 0,
                learnMode: false
            },
            time: Date.now() / 1000
        };
        const contextJson = safeJson(fakeContext);
        const rawTitle = articleData.title || '文章';
        const safeTitle = escHtml(rawTitle);
        const desc = escHtml(
            (articleData.content || '').replace(/\s+/g, ' ').substring(0, 200).trim()
        );
        const authorName = escHtml((articleData.author && articleData.author.name) || '保存站用户');
        const ldJson = safeJson({
            "@context": "https://schema.org",
            "@type": "Article",
            "name": rawTitle,
            "description": (articleData.content || '').substring(0, 200),
            "genre": "科技·工程",
            "author": { "@type": "Person", "name": (articleData.author && articleData.author.name) || '保存站用户' },
            "datePublished": isoString
        });
        const loaderVer = loaderVersion;
        const vendorVer = vendorVersion || loaderVer;
        const csrf = csrfToken || '';
        const feConfig = feConfigVersion || '';
        const tagVer = luoguTagVersion || '';
        return `<!DOCTYPE html>
<html lang="zh-CN" class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="csrf-token" content="${escHtml(csrf)}">
    <meta name="renderer" content="webkit">
    <script>
        window.__feInitLocalTime = ${Date.now() / 1000};
        ${feConfig ? `window.__feConfigVersion = '${escHtml(feConfig)}';` : ''}
        window.__feConfigRequest = '\\/_lfe\\/config';
        window.__fePhoneHomeCall = 'https\\u003A\\/\\/moshimoshi\\u003Aagltb3noatpwohhuenb5ag1tc2jsnnl3\\u0040errtrack.luogu.com.cn\\/lotlp1';
        ${tagVer ? `window.__luoguTagVersion = '${escHtml(tagVer)}';` : ''}
        window.__luoguTagRequest = '\\/_lfe\\/tags\\/zh\\u002DCN';
    </script>
    <title>${safeTitle} - 洛谷专栏</title>
    <link rel="icon" href="https://fecdn.luogu.com.cn/favicon.ico">
    <meta http-equiv="Content-Security-Policy" content="${CSP_META}">
    <script id="lentille-context" type="application/json">${contextJson}</script>
    <script src="https://fecdn.luogu.com.cn/columba/vendor.${vendorVer}.js" charset="utf-8" defer></script>
    <script src="https://fecdn.luogu.com.cn/columba/loader.${loaderVer}.js" charset="utf-8" defer></script>
    <link rel="stylesheet" href="https://fecdn.luogu.com.cn/columba/loader.${loaderVer}.css" />
    ${themeScript}
    ${customStyle}
    <link rel="canonical" href="https://www.luogu.com.cn/article/${escHtml(itemId)}" />
    <script type="application/ld+json">${ldJson}</script>
    <meta property="og:type" content="article" />
    <meta property="og:title" content="${safeTitle}" />
    <meta property="og:description" content="${desc}" />
    <meta property="article:section" content="科技·工程" />
    <meta property="article:author" content="${authorName}" />
    <meta property="article:published_time" content="${isoString}" />
    <meta property="og:url" content="https://www.luogu.com.cn/article/${escHtml(itemId)}" />
    <meta property="og:site_name" content="洛谷专栏" />
    ${getInlineSwalCss()}
    ${getInlineSwal()}
</head>
<body>
    <div id="app">
        <noscript><h3>请<b style="color:#f00;">不要禁用</b>脚本,否则网页无法正常加载</h3></noscript>
    </div>
    ${DISABLE_ZERO_LINKS_SCRIPT}
</body>
</html>`;
    }
    function buildPasteHtml(pasteData) {
        const userData = currentUser || {
            uid: 0, avatar: '', name: '', slogan: '', badge: null,
            isAdmin: false, isBanned: false, color: 'Green',
            ccfLevel: 0, xcpcLevel: 0, background: '', verified: false,
            eloValue: 0, followingCount: 0, followerCount: 0, ranking: 0,
            unreadMessageCount: 0, unreadNoticeCount: 0, learnMode: false
        };
        const authorInfo = pasteData.author || pasteData.user || {};
        const pasteTimestamp = toSeconds(pasteData.time)
            ?? toSeconds(pasteData.createdAt)
            ?? Math.floor(Date.now() / 1000);
        const updateTimestamp = toSeconds(pasteData.updateAt) ?? pasteTimestamp;
        const authorId = authorInfo.id || 0;
        const paste = {
            id: pasteData.id || itemId,
            user: {
                uid: authorId,
                avatar: authorInfo.avatar || `https://cdn.luogu.com.cn/upload/usericon/${authorId}.png`,
                name: authorInfo.name || '保存站用户',
                slogan: authorInfo.slogan || '',
                badge: '',
                isAdmin: false,
                isBanned: false,
                color: authorInfo.color || 'Green',
                ccfLevel: 0,
                xcpcLevel: 0,
                background: authorInfo.background || ''
            },
            time: pasteTimestamp,
            public: pasteData.public !== undefined ? pasteData.public : true,
            updateAt: updateTimestamp,
            data: pasteData.content || pasteData.data || ''
        };
        const contextData = {
            instance: "main",
            template: "paste.show",
            status: 200,
            locale: "zh-CN",
            data: {
                paste: paste,
                canEdit: false
            },
            user: {
                uid: userData.uid || 0,
                avatar: userData.avatar || '',
                name: userData.name || '',
                slogan: userData.slogan || '',
                badge: userData.badge || null,
                isAdmin: !!userData.isAdmin,
                isBanned: !!userData.isBanned,
                color: userData.color || 'Green',
                ccfLevel: userData.ccfLevel || 0,
                xcpcLevel: userData.xcpcLevel || 0,
                background: userData.background || '',
                verified: !!userData.verified,
                eloValue: userData.eloValue || 0,
                followingCount: userData.followingCount || 0,
                followerCount: userData.followerCount || 0,
                ranking: userData.ranking || 0,
                unreadMessageCount: userData.unreadMessageCount || 0,
                unreadNoticeCount: userData.unreadNoticeCount || 0,
                learnMode: false
            },
            time: Date.now() / 1000
        };
        const contextJson = safeJson(contextData);
        const loaderVer = loaderVersion;
        const vendorVer = vendorVersion || loaderVer;
        const csrf = csrfToken || '';
        const feConfig = feConfigVersion || '';
        const tagVer = luoguTagVersion || '';
        return `<!DOCTYPE html>
<html lang="zh-CN" class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="csrf-token" content="${escHtml(csrf)}">
    <meta name="renderer" content="webkit">
    <script>
        window.__feInitLocalTime = ${Date.now() / 1000};
        ${feConfig ? `window.__feConfigVersion = '${escHtml(feConfig)}';` : ''}
        window.__feConfigRequest = '\\/_lfe\\/config';
        window.__fePhoneHomeCall = 'https\\u003A\\/\\/moshimoshi\\u003Aagltb3noatpwohhuenb5ag1tc2jsnnl3\\u0040errtrack.luogu.com.cn\\/lotlp1';
        ${tagVer ? `window.__luoguTagVersion = '${escHtml(tagVer)}';` : ''}
        window.__luoguTagRequest = '\\/_lfe\\/tags\\/zh\\u002DCN';
    </script>
    <title>剪贴板 - 洛谷</title>
    <link rel="icon" href="https://fecdn.luogu.com.cn/favicon.ico">
    <meta http-equiv="Content-Security-Policy" content="${CSP_META}">
    <script id="lentille-context" type="application/json">${contextJson}</script>
    <script src="https://fecdn.luogu.com.cn/columba/vendor.${vendorVer}.js" charset="utf-8" defer></script>
    <script src="https://fecdn.luogu.com.cn/columba/loader.${loaderVer}.js" charset="utf-8" defer></script>
    <link rel="stylesheet" href="https://fecdn.luogu.com.cn/columba/loader.${loaderVer}.css" />
    <meta name="robots" content="noindex, nofollow">
    ${themeScript}
    ${customStyle || '<style>body { --lfe-code-font: "Consolas"; }</style>'}
    ${getInlineSwalCss()}
    ${getInlineSwal()}
</head>
<body>
    <div id="app">
        <noscript><h3>请<b style="color:#f00;">不要禁用</b>脚本,否则网页无法正常加载</h3></noscript>
    </div>
    ${DISABLE_ZERO_LINKS_SCRIPT}
</body>
</html>`;
    }
    async function buildAndLoad() {
        if (pageType !== 'article' && pageType !== 'paste') {
            throw new Error(`未知页面类型: ${pageType}`);
        }
        console.log('[LGSS] 劫持界面就绪,开始构造官方环境');
        const card = document.querySelector('.card');
        if (card) card.style.display = 'none';
        const ok = await fetchTemplateVersions(pageType);
        if (!ok || !loaderVersion) {
            console.warn('[LGSS] 无法获取版本信息');
            await showErrorWithOptions('无法获取洛谷前端版本信息', pageType, itemId);
            return;
        }
        let result;
        try {
            result = await ensureSavedOnStation(pageType, itemId);
        } catch (e) {
            console.error(`[LGSS] 获取保存站${pageType}失败:`, e);
            await showErrorWithOptions(`获取保存站${typeLabel()}失败:${e.message || e}`, pageType, itemId);
            return;
        }
        if (result.kind === 'saved-need-reload') {
            lgssLoaded = false;
            handleBlocked('after-save');
            return;
        }
        const data = result.data;
        if (!data) {
            await showErrorWithOptions(`${typeLabel()}数据为空`, pageType, itemId);
            return;
        }
        console.log(`[LGSS] 成功获取${typeLabel()}内容`);
        lastRenderedType = pageType;
        lastRenderedId = String(itemId);
        lastRenderedContent = isArticle()
            ? (data.content || '')
            : (data.content || data.data || '');
        fireSwal({
            icon: 'success',
            title: '获取成功',
            html: '即将自动重写界面',
            allowOutsideClick: false,
            showCancelButton: false,
            showConfirmButton: false,
            didOpen: () => {
                let fired = false;
                const finish = () => {
                    if (fired) return;
                    fired = true;
                    stopSwalKeepAlive();
                    Swal.close();
                    const html = isArticle() ? buildArticleHtml(data) : buildPasteHtml(data);
                    document.open();
                    document.write(html);
                    document.close();
                    installSwalStyleGuard();
                    if (isArticle()) {
                        watchActionsForButton();
                    } else {
                        watchPasteButton();
                    }
                    console.log('[LGSS] 页面已重写,loader.js 将自动渲染');
                };
                const icon = document.querySelector('.swal2-icon');
                if (icon) icon.addEventListener('animationend', finish, { once: true });
                setTimeout(finish, 1500);
            }
        });
        keepSwalAlive(1500);
    }
    function handleBlocked(mode) {
        if (lgssLoaded) {
            console.warn('[LGSS] 已加载,刷新后重试');
            return;
        }
        lgssLoaded = true;
        if (!mode || mode === 'normal') {
            document.title = `LGSS Loading - 洛谷`;
        }
        let swalTitle;
        if (mode === 'after-save') swalTitle = `保存成功,正在再次尝试获取${typeLabel()}内容`;
        else if (mode === 'after-update') swalTitle = `更新成功,正在再次获取${typeLabel()}内容`;
        else swalTitle = `正在获取${typeLabel()}内容`;
        fireSwal({
            title: swalTitle,
            html: '请稍候',
            allowOutsideClick: false,
            allowEscapeKey: false,
            didOpen: () => Swal.showLoading(),
        });
        keepSwalAlive(3000);
        buildAndLoad();
    }
    let done = false;
    let attempts = 0;
    const MAX_ATTEMPTS = 300;
    let detectTimer = null;
    function startDetection() {
        if (detectTimer) clearInterval(detectTimer);
        done = false;
        attempts = 0;
        detectTimer = setInterval(() => {
            attempts++;
            if (isBlocked()) {
                clearInterval(detectTimer);
                detectTimer = null;
                if (!done) {
                    done = true;
                    handleBlocked();
                }
                return;
            }
            if (attempts >= MAX_ATTEMPTS) {
                clearInterval(detectTimer);
                detectTimer = null;
                console.log('[LGSS] 未检测到拦截,不执行替换');
            }
        }, 100);
    }
    let lastPath = location.pathname;
    function onRouteChange() {
        const newPath = location.pathname;
        if (newPath === lastPath) return;
        lastPath = newPath;
        lastRenderedContent = null;
        lastRenderedType = null;
        lastRenderedId = null;

        if (lgssLoaded) {
            lgssLoaded = false;
            console.log('[LGSS] 离开伪造页,重置 lgssLoaded');
        }

        const parts = newPath.split('/').filter(p => p);
        const pt = parts[0], id = parts[1];

        if (pt === 'user') {
            pageType = 'user';
            itemId = id;
            console.log(`[LGSS] SPA 路由跳转到 user/${id}`);
            installSwalStyleGuard();
            if (isUserHome()) {
                watchIntroCard();
            } else {
                if (introObserver) { introObserver.disconnect(); introObserver = null; }
                removeInjectedIntroCard();
            }
            return;
        }

        if (pageType === 'user') {
            if (introObserver) { introObserver.disconnect(); introObserver = null; }
            removeInjectedIntroCard();
        }

        if (pt !== 'article' && pt !== 'paste') return;

        pageType = pt;
        itemId = id;
        console.log(`[LGSS] SPA 路由跳转到 ${pt}/${id}`);
        installSwalStyleGuard();
        startDetection();
    }
    const _pushState = history.pushState;
    history.pushState = function (...a) {
        const r = _pushState.apply(this, a);
        setTimeout(onRouteChange, 0);
        return r;
    };
    const _replaceState = history.replaceState;
    history.replaceState = function (...a) {
        const r = _replaceState.apply(this, a);
        setTimeout(onRouteChange, 0);
        return r;
    };
    window.addEventListener('popstate', () => setTimeout(onRouteChange, 0));
    if (pageType === 'article' || pageType === 'paste') {
        startDetection();
        window.addEventListener('load', () => {
            if (!done && isBlocked()) {
                done = true;
                handleBlocked();
            }
        });
        console.log('[LGSS] 已启动。仅在检测到拦截时自动替换。');
    } else if (pageType === 'user') {
        installSwalStyleGuard();
        if (isUserHome()) {
            watchIntroCard();
            console.log('[LGSS] 用户主页,等待注入个人介绍卡片。');
        } else {
            console.log('[LGSS] 用户子页面,不注入个人介绍。');
        }
    } else {
        console.log('[LGSS] 非目标页面,等待 SPA 路由跳转。');
    }
})();