// ==UserScript== // @name 网站快照存储与恢复助手 // @namespace https://github.com/moyefu/BrowserScript // @version 1.5.0 // @description 针对指定网站实现快照(Cookie、LocalStorage、SessionStorage)的一键存储、命名、加密备份、GitHub Gist云同步、二维码生成/扫码与一键恢复 // @author MOYEFU // @icon https://pic1.imgdb.cn/i/034D4F8VwYLLoU73kkQs3l.gif // @homepage https://scriptcat.org/zh-CN/script-show-page/7633 // @supportURL https://scriptcat.org/zh-CN/script-show-page/7633/issue // @license MIT // @match http*://*/* // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_listValues // @grant GM_registerMenuCommand // @grant GM_cookie // @grant GM_setClipboard // @grant GM_xmlhttpRequest // @connect api.github.com // @require https://cdn.jsdelivr.net/npm/qrcode-generator@1.4.4/qrcode.min.js // @require https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js // @tag MOYEFU // @run-at document-idle // @noframes // ==/UserScript== /* ==UserConfig== Config: filter_mode: title: 域名过滤模式 description: 白名单模式:仅对列表中的网站生效;黑名单模式:对除列表中之外的所有网站生效 type: select values: - [whitelist, 白名单模式 (仅在列表中生效)] - [blacklist, 黑名单模式 (列表中的不生效)] default: whitelist host_list: title: 域名列表 (每行一条) description: 每行一条,支持通配符 * ,例:https://*.example.org* 或 *.baidu.com;白名单模式下仅列表内网站显示,黑名单模式下列表内网站不显示 type: textarea default: "" enable_encryption: title: 本地数据加密 description: 启用 AES-GCM 256 位本地数据加密存储 type: checkbox default: false auto_reload_after_restore: title: 恢复后直接刷新/跳转 description: 恢复快照成功后直接刷新或跳转至来源页面(不再弹窗确认) type: checkbox default: false sync_auto: title: 空闲时自动同步 description: 自动同步至 GitHub Gist(检测空闲且未使用插件时静默同步) type: checkbox default: false sync_idle_minutes: title: 自动同步空闲时长 (分钟) description: 检测无网页操作且无插件操作达到该时长后触发自动同步(默认5分钟) type: number default: 5 min: 1 max: 1440 sync_gist_token: title: GitHub Gist Token description: 用于云同步的 GitHub Personal Access Token(需勾选 gist 权限) type: text default: "" sync_gist_id: title: GitHub Gist ID description: 存储快照数据的 Gist ID(留空可在面板中点击一键自动创建) type: text default: "" ==/UserConfig== */ let appTrustedPolicy=null;function initTrustedTypesPolicy(){if(appTrustedPolicy)return;const e="undefined"!=typeof window&&window.trustedTypes||"undefined"!=typeof unsafeWindow&&unsafeWindow.trustedTypes;if(e&&"function"==typeof e.createPolicy){const t=["default","snapshotPolicy","webSnapshotManager","trusted-types","goog#html","dompurify","angular#unsafe-bypass","nextjs#html","webpack#html","bypass"];for(const n of t){if(appTrustedPolicy)break;try{appTrustedPolicy=e.createPolicy(n,{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e})}catch(e){}}!appTrustedPolicy&&e.defaultPolicy&&(appTrustedPolicy=e.defaultPolicy)}}function safeHTML(e){if(appTrustedPolicy&&"function"==typeof appTrustedPolicy.createHTML)try{return appTrustedPolicy.createHTML(e)}catch(t){return e}return e}function setSafeInnerHTML(e,t){if(!e)return;const n=safeHTML(t);try{return void(e.innerHTML=n)}catch(e){}try{const t=document.createRange();t.selectNode(e);const o=t.createContextualFragment(n);return void e.replaceChildren(o)}catch(e){}try{const t=(new DOMParser).parseFromString(n,"text/html");return void e.replaceChildren(...t.body.childNodes)}catch(e){}}initTrustedTypesPolicy();let innerHTMLPatched=!1;function patchInnerHTMLSetter(){if(!innerHTMLPatched){innerHTMLPatched=!0;try{if("undefined"==typeof Element||!Element.prototype)return;const e=Object.getOwnPropertyDescriptor(Element.prototype,"innerHTML");e&&e.set&&Object.defineProperty(Element.prototype,"innerHTML",{set:function(t){const n=safeHTML(t);try{return e.set.call(this,n)}catch(e){try{const e=document.createRange();e.selectNode(this);const t=e.createContextualFragment(n);return void this.replaceChildren(t)}catch(t){try{const e=(new DOMParser).parseFromString(n,"text/html");return void this.replaceChildren(...e.body.childNodes)}catch(t){throw e}}}},get:function(){return e.get.call(this)},configurable:!0,enumerable:!0})}catch(e){}}}let LSM_UI=null;const ThemeEngine={SCHEMA_TYPE:"LSM_THEME",SCHEMA_VERSION:"1.0.0",DEFAULT_THEME_ID:"yohaku",_shadow:null,_uid:null,BUILTIN_THEMES:[{type:"LSM_THEME",version:"1.0.0",id:"yohaku",name:"Yohaku (余白)",description:"基于 Innei Yohaku 设计体系的米白纸张与梅红质感主题",isBuiltin:!0,tokens:{accent:"#c56473",accentBg:"rgba(197, 100, 115, 0.08)",accentBorder:"rgba(197, 100, 115, 0.3)",accentHoverBg:"rgba(197, 100, 115, 0.14)",accentGlow:"rgba(197, 100, 115, 0.12)",bgPaper:"#faf9f5",bgHeader:"#f0efeb",bgCard:"#ffffff",bgList:"#f9f8f5",bgHover:"#f0efeb",bgActiveCard:"linear-gradient(180deg, rgba(94, 159, 126, 0.06) 0%, #ffffff 60%)",borderLight:"#e3e1db",borderHover:"#d0cec6",textPrimary:"#24231f",textSecondary:"#5c5a55",textMuted:"#787670",textPlaceholder:"#a8a69f",colorSuccess:"#5e9f7e",bgSuccess:"rgba(94, 159, 126, 0.08)",borderSuccess:"rgba(94, 159, 126, 0.25)",colorWarning:"#a87a3d",bgWarning:"rgba(168, 122, 61, 0.08)",borderWarning:"rgba(168, 122, 61, 0.2)",colorInfo:"#3d6896",bgInfo:"rgba(61, 104, 150, 0.08)",borderInfo:"rgba(61, 104, 150, 0.2)",colorDanger:"#a64953",bgDanger:"rgba(166, 73, 83, 0.08)",borderDanger:"rgba(166, 73, 83, 0.25)",fontFamily:"system-ui, -apple-system, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', sans-serif",radiusWindow:"16px",radiusCard:"12px",radiusBtn:"8px"}},{type:"LSM_THEME",version:"1.0.0",id:"classic_blue",name:"Classic Blue (经典科技蓝)",description:"清晰现代的科技蓝调搭配极简冷灰界面",isBuiltin:!0,tokens:{accent:"#2563eb",accentBg:"rgba(37, 99, 235, 0.08)",accentBorder:"rgba(37, 99, 235, 0.3)",accentHoverBg:"rgba(37, 99, 235, 0.14)",accentGlow:"rgba(37, 99, 235, 0.12)",bgPaper:"#f8fafc",bgHeader:"#f1f5f9",bgCard:"#ffffff",bgList:"#f8fafc",bgHover:"#f1f5f9",bgActiveCard:"linear-gradient(180deg, rgba(22, 163, 74, 0.06) 0%, #ffffff 60%)",borderLight:"#e2e8f0",borderHover:"#cbd5e1",textPrimary:"#0f172a",textSecondary:"#334155",textMuted:"#64748b",textPlaceholder:"#94a3b8",colorSuccess:"#16a34a",bgSuccess:"rgba(22, 163, 74, 0.08)",borderSuccess:"rgba(22, 163, 74, 0.25)",colorWarning:"#d97706",bgWarning:"rgba(217, 119, 6, 0.08)",borderWarning:"rgba(217, 119, 6, 0.2)",colorInfo:"#0284c7",bgInfo:"rgba(2, 132, 199, 0.08)",borderInfo:"rgba(2, 132, 199, 0.2)",colorDanger:"#dc2626",bgDanger:"rgba(220, 38, 38, 0.08)",borderDanger:"rgba(220, 38, 38, 0.25)",fontFamily:"system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",radiusWindow:"16px",radiusCard:"12px",radiusBtn:"8px"}},{type:"LSM_THEME",version:"1.0.0",id:"obsidian_dark",name:"Obsidian Dark (曜石暗夜)",description:"深色沉浸护眼主题,曜石黑灰与高亮翡翠绿点缀",isBuiltin:!0,tokens:{accent:"#10b981",accentBg:"rgba(16, 185, 129, 0.12)",accentBorder:"rgba(16, 185, 129, 0.35)",accentHoverBg:"rgba(16, 185, 129, 0.2)",accentGlow:"rgba(16, 185, 129, 0.15)",bgPaper:"#141312",bgHeader:"#1f1e1c",bgCard:"#1f1e1c",bgList:"#141312",bgHover:"#2a2926",bgActiveCard:"linear-gradient(180deg, rgba(16, 185, 129, 0.12) 0%, #1f1e1c 60%)",borderLight:"#2f2d29",borderHover:"#474540",textPrimary:"#f5f4f0",textSecondary:"#d0cec6",textMuted:"#a8a69f",textPlaceholder:"#787670",colorSuccess:"#10b981",bgSuccess:"rgba(16, 185, 129, 0.12)",borderSuccess:"rgba(16, 185, 129, 0.3)",colorWarning:"#f59e0b",bgWarning:"rgba(245, 158, 11, 0.12)",borderWarning:"rgba(245, 158, 11, 0.3)",colorInfo:"#38bdf8",bgInfo:"rgba(56, 189, 248, 0.12)",borderInfo:"rgba(56, 189, 248, 0.3)",colorDanger:"#f43f5e",bgDanger:"rgba(244, 63, 94, 0.12)",borderDanger:"rgba(244, 63, 94, 0.3)",fontFamily:"system-ui, -apple-system, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif",radiusWindow:"16px",radiusCard:"12px",radiusBtn:"8px"}},{type:"LSM_THEME",version:"1.0.0",id:"sakura_pink",name:"Sakura Pink (春櫻粉紫)",description:"温柔优雅的春日樱花色调,粉白相间与柔润光泽",isBuiltin:!0,tokens:{accent:"#e11d48",accentBg:"rgba(225, 29, 72, 0.08)",accentBorder:"rgba(225, 29, 72, 0.28)",accentHoverBg:"rgba(225, 29, 72, 0.14)",accentGlow:"rgba(225, 29, 72, 0.1)",bgPaper:"#fff5f6",bgHeader:"#ffe4e6",bgCard:"#ffffff",bgList:"#fff1f3",bgHover:"#ffe4e6",bgActiveCard:"linear-gradient(180deg, rgba(225, 29, 72, 0.06) 0%, #ffffff 60%)",borderLight:"#fecdd3",borderHover:"#fda4af",textPrimary:"#2b1216",textSecondary:"#612933",textMuted:"#9f4a59",textPlaceholder:"#be7683",colorSuccess:"#059669",bgSuccess:"rgba(5, 150, 105, 0.08)",borderSuccess:"rgba(5, 150, 105, 0.2)",colorWarning:"#d97706",bgWarning:"rgba(217, 119, 6, 0.08)",borderWarning:"rgba(217, 119, 6, 0.2)",colorInfo:"#7c3aed",bgInfo:"rgba(124, 58, 237, 0.08)",borderInfo:"rgba(124, 58, 237, 0.2)",colorDanger:"#e11d48",bgDanger:"rgba(225, 29, 72, 0.08)",borderDanger:"rgba(225, 29, 72, 0.25)",fontFamily:"system-ui, -apple-system, 'PingFang SC', sans-serif",radiusWindow:"18px",radiusCard:"14px",radiusBtn:"10px"}},{type:"LSM_THEME",version:"1.0.0",id:"matcha_green",name:"Matcha Green (宇治抹茶)",description:"清幽宁静的和风抹茶绿,淡雅米绿与墨茶文字",isBuiltin:!0,tokens:{accent:"#15803d",accentBg:"rgba(21, 128, 61, 0.08)",accentBorder:"rgba(21, 128, 61, 0.28)",accentHoverBg:"rgba(21, 128, 61, 0.14)",accentGlow:"rgba(21, 128, 61, 0.1)",bgPaper:"#f9fcf8",bgHeader:"#edf7eb",bgCard:"#ffffff",bgList:"#f4faf2",bgHover:"#e8f5e5",bgActiveCard:"linear-gradient(180deg, rgba(21, 128, 61, 0.06) 0%, #ffffff 60%)",borderLight:"#d6ebd3",borderHover:"#b6deb0",textPrimary:"#19281a",textSecondary:"#3d543f",textMuted:"#678469",textPlaceholder:"#93ac95",colorSuccess:"#15803d",bgSuccess:"rgba(21, 128, 61, 0.08)",borderSuccess:"rgba(21, 128, 61, 0.2)",colorWarning:"#b45309",bgWarning:"rgba(180, 83, 9, 0.08)",borderWarning:"rgba(180, 83, 9, 0.2)",colorInfo:"#0369a1",bgInfo:"rgba(3, 105, 161, 0.08)",borderInfo:"rgba(3, 105, 161, 0.2)",colorDanger:"#b91c1c",bgDanger:"rgba(185, 28, 28, 0.08)",borderDanger:"rgba(185, 28, 28, 0.25)",fontFamily:"system-ui, -apple-system, 'PingFang SC', sans-serif",radiusWindow:"16px",radiusCard:"12px",radiusBtn:"8px"}}],getCustomThemes(){try{const e=GM_getValue("Config.custom_themes",{});return"object"==typeof e&&null!==e?e:{}}catch(e){return{}}},saveCustomThemesMap(e){try{GM_setValue("Config.custom_themes",e||{})}catch(e){}},getAllThemes(){const e=Object.values(this.getCustomThemes());return[...this.BUILTIN_THEMES,...e]},getThemeById(e){return e&&this.getAllThemes().find(t=>t.id===e)||this.BUILTIN_THEMES[0]},getActiveTheme(){const e=GM_getValue("Config.active_theme_id",this.DEFAULT_THEME_ID);return this.getThemeById(e)},setActiveTheme(e){const t=this.getThemeById(e);return GM_setValue("Config.active_theme_id",t.id),this.applyTheme(t),t},resetToDefault(){return this.setActiveTheme(this.DEFAULT_THEME_ID)},bindShadow(e,t){this._shadow=e,this._uid=t,this.applyTheme()},validateAndNormalizeTheme(e){if(!e||"object"!=typeof e)throw new Error("主题数据必须为有效的 JSON 对象");if(e.type&&e.type!==this.SCHEMA_TYPE)throw new Error("非法的主题数据格式类型: "+e.type+",期望为 "+this.SCHEMA_TYPE);const t=this.BUILTIN_THEMES[0].tokens,n=e.tokens||{},o={};for(const[e,s]of Object.entries(t))o[e]="string"==typeof n[e]&&n[e].trim()?n[e].trim():s;const s=String(e.name||"自定义主题").trim(),i=String(e.id||"custom_"+Date.now().toString(36)).trim().replace(/[^a-zA-Z0-9_-]/g,"_"),r=String(e.description||"用户自定义导入的主题样式").trim();return{type:this.SCHEMA_TYPE,version:this.SCHEMA_VERSION,id:i,name:s,description:r,isBuiltin:!1,tokens:o,createdAt:e.createdAt||Date.now(),updatedAt:Date.now()}},getThemeTombstones(){try{const e=GM_getValue("Config.theme_tombstones",{});return"object"==typeof e&&null!==e?e:{}}catch(e){return{}}},saveThemeTombstones(e){try{GM_setValue("Config.theme_tombstones",e||{})}catch(e){}},addThemeTombstone(e){if(!e)return;const t=this.getThemeTombstones();t[e]=Date.now(),this.saveThemeTombstones(t)},removeThemeTombstone(e){if(!e)return;const t=this.getThemeTombstones();t[e]&&(delete t[e],this.saveThemeTombstones(t))},importTheme(e){let t=e;if("string"==typeof e)try{t=JSON.parse(e)}catch(e){throw new Error("JSON 解析失败: "+e.message)}const n=this.validateAndNormalizeTheme(t),o=this.getCustomThemes();return this.BUILTIN_THEMES.some(e=>e.id===n.id)&&(n.id="custom_"+n.id+"_"+Date.now().toString(36).slice(-4)),o[n.id]=n,this.removeThemeTombstone(n.id),this.saveCustomThemesMap(o),this.setActiveTheme(n.id),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync(),n},exportTheme(e){const t=this.getThemeById(e),n={type:this.SCHEMA_TYPE,version:this.SCHEMA_VERSION,id:t.id,name:t.name,description:t.description,tokens:t.tokens,exportedAt:Date.now()};return JSON.stringify(n,null,2)},saveCustomTheme(e){const t=this.validateAndNormalizeTheme(e),n=this.getCustomThemes();return n[t.id]=t,this.removeThemeTombstone(t.id),this.saveCustomThemesMap(n),this.setActiveTheme(t.id),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync(),t},deleteCustomTheme(e){if(this.BUILTIN_THEMES.some(t=>t.id===e))throw new Error("内置官方主题受保护,不可删除");const t=this.getCustomThemes();t[e]&&(delete t[e],this.saveCustomThemesMap(t)),this.addThemeTombstone(e),GM_getValue("Config.active_theme_id","")===e&&this.resetToDefault(),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync()},generateCssVariables:(e,t)=>`\n ${t?`#${t}-root`:':host, [id$="-root"]'} {\n --lsm-accent: ${e.accent};\n --lsm-accent-bg: ${e.accentBg};\n --lsm-accent-border: ${e.accentBorder};\n --lsm-accent-hover-bg: ${e.accentHoverBg};\n --lsm-accent-glow: ${e.accentGlow};\n --lsm-bg-paper: ${e.bgPaper};\n --lsm-bg-header: ${e.bgHeader};\n --lsm-bg-card: ${e.bgCard};\n --lsm-bg-list: ${e.bgList};\n --lsm-bg-hover: ${e.bgHover};\n --lsm-bg-active-card: ${e.bgActiveCard};\n --lsm-border: ${e.borderLight};\n --lsm-border-hover: ${e.borderHover};\n --lsm-text-primary: ${e.textPrimary};\n --lsm-text-secondary: ${e.textSecondary};\n --lsm-text-muted: ${e.textMuted};\n --lsm-text-placeholder: ${e.textPlaceholder};\n --lsm-color-success: ${e.colorSuccess};\n --lsm-bg-success: ${e.bgSuccess};\n --lsm-border-success: ${e.borderSuccess};\n --lsm-color-warning: ${e.colorWarning};\n --lsm-bg-warning: ${e.bgWarning};\n --lsm-border-warning: ${e.borderWarning};\n --lsm-color-info: ${e.colorInfo};\n --lsm-bg-info: ${e.bgInfo};\n --lsm-border-info: ${e.borderInfo};\n --lsm-color-danger: ${e.colorDanger};\n --lsm-bg-danger: ${e.bgDanger};\n --lsm-border-danger: ${e.borderDanger};\n --lsm-font-family: ${e.fontFamily};\n --lsm-radius-window: ${e.radiusWindow||"16px"};\n --lsm-radius-card: ${e.radiusCard||"12px"};\n --lsm-radius-btn: ${e.radiusBtn||"8px"};\n }\n `,applyTheme(e){const t=e||this.getActiveTheme(),n=this.generateCssVariables(t.tokens,this._uid);if(this._shadow){const e=this._uid?`${this._uid}-theme-vars`:"lsm-theme-vars";let t=this._shadow.getElementById(e);t||(t=document.createElement("style"),t.id=e,this._shadow.insertBefore(t,this._shadow.firstChild)),t.textContent=n}if("undefined"!=typeof document&&document){let e=document.getElementById("lsm-host-theme-vars");e||(e=document.createElement("style"),e.id="lsm-host-theme-vars",(document.head||document.documentElement).appendChild(e)),e.textContent=`\n :root {\n --lsm-host-accent: ${t.tokens.accent};\n --lsm-host-accent-bg: ${t.tokens.accentBg};\n --lsm-host-accent-border: ${t.tokens.accentBorder};\n --lsm-host-bg-paper: ${t.tokens.bgPaper};\n --lsm-host-border: ${t.tokens.borderLight};\n --lsm-host-border-hover: ${t.tokens.borderHover||"#d0cec6"};\n --lsm-host-text-primary: ${t.tokens.textPrimary};\n --lsm-host-text-secondary: ${t.tokens.textSecondary};\n --lsm-host-text-muted: ${t.tokens.textMuted};\n --lsm-host-font: ${t.tokens.fontFamily};\n }\n\n /* 宿主环境全部相关弹窗、文本域与列表滚动条美化 */\n div[id*="lsm"] * {\n scrollbar-width: thin;\n scrollbar-color: ${t.tokens.borderHover||"#d0cec6"} transparent;\n }\n div[id*="lsm"] *::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n }\n div[id*="lsm"] *::-webkit-scrollbar-track {\n background: transparent;\n border-radius: 9999px;\n }\n div[id*="lsm"] *::-webkit-scrollbar-thumb {\n background-color: ${t.tokens.borderHover||"#d0cec6"};\n border-radius: 9999px;\n border: 1px solid transparent;\n background-clip: padding-box;\n transition: background-color 0.2s ease;\n }\n div[id*="lsm"] *::-webkit-scrollbar-thumb:hover {\n background-color: ${t.tokens.accent};\n }\n div[id*="lsm"] *::-webkit-scrollbar-corner {\n background: transparent;\n }\n `}}},CompressionEngine={COMPRESSION_PREFIX:"__gz__:",MIN_COMPRESS_SIZE:4096,isSupported:()=>"undefined"!=typeof CompressionStream&&"undefined"!=typeof DecompressionStream&&"undefined"!=typeof Response,isCompressed(e){return"string"==typeof e&&e.startsWith(this.COMPRESSION_PREFIX)},async compressString(e){if(!this.isSupported()||"string"!=typeof e)return e;if(e.lengthBoolean(GM_getValue("Config.enable_encryption",!1)),isAutoReloadEnabled=()=>Boolean(GM_getValue("Config.auto_reload_after_restore",!1)),CryptoEngine={keyCache:new Map,isEncryptionEnabled:()=>isEncryptionEnabled(),async getDerivedKey(e,t,n="v3"){const o=(t||location.hostname||"").trim().toLowerCase(),s=e||"SESSION_MGR_SALT_2026",i=`${o}___${s}___${n}`;if(this.keyCache.has(i))return this.keyCache.get(i);const r=new TextEncoder;let a="";a="v3"===n?"LSM_STABLE_UNIVERSAL_KEY_MATERIAL_2026_SECURE":"v2"===n?`LSM_KEY_V2_SNAPSHOT_${o}`:`LSM_KEY_${navigator.userAgent.slice(0,32)}_${o}`;const c=await crypto.subtle.importKey("raw",r.encode(a),{name:"PBKDF2"},!1,["deriveKey"]),l=await crypto.subtle.deriveKey({name:"PBKDF2",salt:r.encode(s),iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return this.keyCache.set(i,l),l},async encrypt(e,t){if(!this.isEncryptionEnabled()||!crypto.subtle)return{encrypted:!1,payload:JSON.stringify(e)};try{const n=crypto.getRandomValues(new Uint8Array(12)),o=await this.getDerivedKey("SESSION_SALT_GCM",t,"v3"),s=(new TextEncoder).encode(JSON.stringify(e)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},o,s);return{encrypted:!0,v:"3",iv:btoa(String.fromCharCode(...n)),payload:btoa(String.fromCharCode(...new Uint8Array(i)))}}catch(t){return console.warn("[LSM] 加密失败,使用原始格式:",t),{encrypted:!1,payload:JSON.stringify(e)}}},async decrypt(e,t){if(!e)return null;if(!e.encrypted)return"string"==typeof e.payload?JSON.parse(e.payload):e.payload;try{const n=new Uint8Array(atob(e.iv).split("").map(e=>e.charCodeAt(0))),o=new Uint8Array(atob(e.payload).split("").map(e=>e.charCodeAt(0))),s=async(e,t)=>{try{const s=await this.getDerivedKey("SESSION_SALT_GCM",e,t),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},s,o),r=(new TextDecoder).decode(i);return JSON.parse(r)}catch(e){return null}};let i=await s("","v3");if(i)return i;if(t&&(i=await s(t,"v2"),i))return i;if(location.hostname&&location.hostname!==t&&(i=await s(location.hostname,"v2"),i))return i;if(t&&(i=await s(t,"legacy"),i))return i;if(location.hostname&&location.hostname!==t&&(i=await s(location.hostname,"legacy"),i))return i;throw new Error("数据解密失败,快照可能损坏或加密密钥不匹配")}catch(e){throw console.error("[LSM] 解密失败:",e),e instanceof Error?e:new Error("数据解密失败")}},wipeMemory(e){if("object"==typeof e&&null!==e)for(const t of Object.keys(e))"string"==typeof e[t]?e[t]="":"object"==typeof e[t]&&this.wipeMemory(e[t]),delete e[t]}},SessionManager={hasGmCookie:()=>"undefined"!=typeof GM_cookie&&GM_cookie&&"function"==typeof GM_cookie.list&&"function"==typeof GM_cookie.set,async getCookies(){return this.hasGmCookie()?new Promise(e=>{try{GM_cookie.list({url:location.href},(t,n)=>{!n&&t&&Array.isArray(t)?e(t.map(e=>{const t=String(e.domain||"").trim(),n=(t||location.hostname).replace(/^\.+/,""),o=void 0!==e.hostOnly?!!e.hostOnly:!(t.startsWith(".")||n!==location.hostname&&t);return{name:e.name,value:e.value,domain:n,hostOnly:o,path:e.path||"/",secure:!!e.secure,httpOnly:!!e.httpOnly,sameSite:e.sameSite||"unspecified",expirationDate:e.expirationDate,partitionKey:e.partitionKey||null,storeId:e.storeId||null}})):e(this.getDocumentCookies())})}catch(t){e(this.getDocumentCookies())}}):this.getDocumentCookies()},getDocumentCookies(){const e=document.cookie;return e&&e.trim()?e.split(";").map(e=>{const t=e.indexOf("=");if(-1===t)return null;const n=e.slice(0,t).trim(),o=e.slice(t+1).trim();return n?{name:n,value:o,domain:location.hostname,hostOnly:!0,path:"/",secure:"https:"===location.protocol,httpOnly:!1,sameSite:"unspecified",expirationDate:null,partitionKey:null}:null}).filter(Boolean):[]},getWebStorage(){const e={},t={};try{for(let t=0;t{GM_cookie.list({url:location.href},(t,n)=>{!n&&t&&Array.isArray(t)?e(t):e([])})}),i=[o];if(!t)for(let e=1;e{GM_cookie.list({domain:e},(e,n)=>{!n&&e&&Array.isArray(e)?t(e):t([])})});Array.isArray(t)&&r.push(...t)}catch(e){}const a=new Map;for(const n of[...e,...r]){const e=(String(n.domain||"").trim()||o).replace(/^\.+/,"");if(t&&e!==o)continue;const s=n.path||"/",i=`${n.name}___${e}___${s}`;a.has(i)||a.set(i,{...n,cleanDomain:e,path:s})}const c=Array.from(a.values()).map(e=>new Promise(async t=>{const o=!!e.secure,s=o||"https:"===location.protocol?"https:":"http:",i=e.path.startsWith("/")?e.path:"/"+e.path,r={url:`${s}//${e.cleanDomain}${i}`,name:e.name,domain:e.cleanDomain,path:e.path};e.storeId&&(r.storeId=e.storeId),e.partitionKey&&(r.partitionKey=e.partitionKey);let a=!1;try{a=await new Promise(e=>{GM_cookie.delete(r,t=>{e(!t)})})}catch(e){}if(!a){try{await new Promise(t=>{GM_cookie.delete({url:location.href,name:e.name},()=>t())})}catch(e){}if("https:"===location.protocol&&!o)try{const t=`http://${e.cleanDomain}${i}`;await new Promise(n=>{GM_cookie.delete({url:t,name:e.name},()=>n())})}catch(e){}}n++,t()}));await Promise.all(c)}catch(e){console.warn("[LSM Session] GM_cookie 清除异常:",e)}try{const e=this.getDocumentCookies(),i=["/",location.pathname];for(const r of e){const e=encodeURIComponent(r.name),a="=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0";for(const n of Array.from(new Set(i)))if(document.cookie=`${e}${a}; path=${n}`,document.cookie=`${e}${a}; path=${n}; Secure`,document.cookie=`${e}${a}; path=${n}; domain=${o}`,document.cookie=`${e}${a}; path=${n}; domain=.${o}`,!t)for(let t=1;tnew Promise(o=>{try{const s=String(e.domain||"").trim(),i=(s||location.hostname).replace(/^\.+/,""),r=void 0!==e.hostOnly?!!e.hostOnly:!(s.startsWith(".")||i!==location.hostname&&s),a={url:location.href,name:e.name,value:e.value,path:e.path||"/",secure:!!e.secure,httpOnly:!!e.httpOnly};r||(a.domain=i),e.sameSite&&"unspecified"!==e.sameSite&&(a.sameSite=e.sameSite,"none"===String(e.sameSite).toLowerCase()&&(a.secure=!0)),e.expirationDate&&(a.expirationDate=e.expirationDate),e.partitionKey&&(a.partitionKey=e.partitionKey),GM_cookie.set(a,e=>{if(e){if(a.domain)return delete a.domain,void GM_cookie.set(a,e=>{e?n++:t++,o()});n++}else t++;o()})}catch(e){n++,o()}}));await Promise.all(o)}else for(const o of e.cookies)try{const e=String(o.domain||"").trim(),n=(e||location.hostname).replace(/^\.+/,""),s=void 0!==o.hostOnly?!!o.hostOnly:!(e.startsWith(".")||n!==location.hostname&&e);let i=`${encodeURIComponent(o.name)}=${encodeURIComponent(o.value)}; path=${o.path||"/"}`;!s&&n&&(i+=`; domain=${n}`),(o.secure||"https:"===location.protocol)&&(i+="; Secure"),o.sameSite&&"unspecified"!==o.sameSite&&(i+=`; SameSite=${o.sameSite}`),o.expirationDate&&(i+=`; expires=${new Date(1e3*o.expirationDate).toUTCString()}`),document.cookie=i,t++}catch(e){n++}let o=0;if(e.localStorage&&"object"==typeof e.localStorage)try{localStorage.clear();for(const[t,n]of Object.entries(e.localStorage))null!=n&&(localStorage.setItem(t,n),o++)}catch(e){}let s=0;if(e.sessionStorage&&"object"==typeof e.sessionStorage)try{sessionStorage.clear();for(const[t,n]of Object.entries(e.sessionStorage))null!=n&&(sessionStorage.setItem(t,n),s++)}catch(e){}return{cookieSuccessCount:t,cookieFailCount:n,localCount:o,sessionCount:s}}},DB={getStorageKey:e=>`SESSION_DATA_${e||location.hostname}`,getRecords(e){const t=this.getStorageKey(e),n=GM_getValue(t,[]);return Array.isArray(n)?n:[]},saveRecords(e,t){const n=this.getStorageKey(t);GM_setValue(n,e)},getTombstones(e){const t=GM_getValue("LSM_TOMBSTONES",{}),n=t&&"object"==typeof t?t:{},o=Date.now()-2592e6;let s=!1;for(const e of Object.keys(n))if(Array.isArray(n[e])){const t=n[e].filter(e=>e&&e.deletedAt&&e.deletedAt>o);t.length!==n[e].length&&(n[e]=t,s=!0)}return s&&GM_setValue("LSM_TOMBSTONES",n),e?Array.isArray(n[e])?n[e]:[]:n},saveTombstones(e){e&&"object"==typeof e&&GM_setValue("LSM_TOMBSTONES",e)},recordTombstone(e,t){const n=t||location.hostname,o=this.getTombstones();Array.isArray(o[n])||(o[n]=[]);const s=o[n].find(t=>t.id===e);s?s.deletedAt=Date.now():o[n].push({id:e,deletedAt:Date.now()}),this.saveTombstones(o)},clearTombstone(e,t){const n=t||location.hostname,o=this.getTombstones();Array.isArray(o[n])&&(o[n]=o[n].filter(t=>t.id!==e),this.saveTombstones(o))},async addRecord(e,t){const n=location.hostname,o=this.getRecords(n),s=await CryptoEngine.encrypt(t,n),i=Date.now(),r={id:"sess_"+i+"_"+Math.random().toString(36).slice(2,7),name:e.trim(),domain:n,url:location.href,createdAt:i,updatedAt:i,summary:t.summary,cipherData:s};return this.clearTombstone(r.id,n),o.unshift(r),this.saveRecords(o,n),CryptoEngine.wipeMemory(t),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync(),r},updateRecordName(e,t,n){const o=n||location.hostname,s=this.getRecords(o),i=s.find(t=>t.id===e);return!!i&&(i.name=t.trim(),i.updatedAt=Date.now(),this.saveRecords(s,o),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync(),!0)},deleteRecord(e,t){const n=t||location.hostname;let o=this.getRecords(n);const s=o.length;return o=o.filter(t=>t.id!==e),o.length!==s&&(this.saveRecords(o,n),this.recordTombstone(e,n),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync(),!0)},importRecords(e,t){const n=t||location.hostname,o=this.getRecords(n);let s=0,i=0;for(const t of e){if(!t||!t.name||!t.cipherData)continue;const e="string"==typeof t.cipherData?t.cipherData:JSON.stringify(t.cipherData);if(o.some(n=>!(!n||!n.cipherData)&&(("string"==typeof n.cipherData?n.cipherData:JSON.stringify(n.cipherData))===e||n.id&&t.id&&n.id===t.id))){i++;continue}const r={...t,id:t.id&&!o.some(e=>e.id===t.id)?t.id:"sess_"+Date.now()+"_"+Math.random().toString(36).slice(2,7),importedAt:Date.now()};this.clearTombstone(r.id,n),o.unshift(r),s++}return s>0&&(this.saveRecords(o,n),void 0!==GistSyncEngine&&GistSyncEngine.scheduleAutoSync&&GistSyncEngine.scheduleAutoSync()),{count:s,skipped:i}},getAllDomains(){const e=new Set;try{if("function"==typeof GM_listValues){const t=GM_listValues();for(const n of t)if(n.startsWith("SESSION_DATA_")){const t=n.replace("SESSION_DATA_","");t&&e.add(t)}}}catch(e){}e.add(location.hostname);const t=getHostRules();for(const n of t)try{const t=n.replace(/^https?:\/\//i,"").replace(/\/.*$/,"").replace(/^\*\./,"");t&&!t.includes("*")&&e.add(t)}catch(e){}return Array.from(e)},getAllLocalData(){const e=this.getAllDomains(),t={};let n=0;for(const o of e){const e=this.getRecords(o);e&&e.length>0&&(t[o]=e,n+=e.length)}return{format:"LSM_GIST_SYNC",version:"1.5.0",lastSyncTime:GM_getValue("Config.sync_last_time",0),totalSnapshots:n,records:t,tombstones:this.getTombstones(),custom_themes:void 0!==ThemeEngine?ThemeEngine.getCustomThemes():{},theme_tombstones:void 0!==ThemeEngine?ThemeEngine.getThemeTombstones():{}}},applyMergedData(e,t){if(e&&"object"==typeof e)for(const[t,n]of Object.entries(e))this.saveRecords(Array.isArray(n)?n:[],t);t&&"object"==typeof t&&this.saveTombstones(t)},overwriteAllLocalData(e,t){const n=this.getAllDomains();for(const e of n)this.saveRecords([],e);this.applyMergedData(e,t)},async getDecryptedSession(e,t){const n=t||location.hostname,o=this.getRecords(n).find(t=>t.id===e);if(!o)throw new Error("未找到对应快照记录");const s=o.domain||n;return await CryptoEngine.decrypt(o.cipherData,s)}},GistSyncEngine={GIST_FILENAME:"web_snapshot_manager_sync.json",syncLock:!1,hasPendingChanges:!1,idleMonitorTimer:null,lastActivityTime:Date.now(),_activityListenersInitialized:!1,httpRequest:e=>new Promise((t,n)=>{const{method:o="GET",url:s,headers:i={},data:r}=e;"function"==typeof GM_xmlhttpRequest?GM_xmlhttpRequest({method:o,url:s,headers:{Accept:"application/vnd.github.v3+json","User-Agent":"WebSnapshotManager-Tampermonkey-Script",...i},data:r?"string"==typeof r?r:JSON.stringify(r):void 0,timeout:2e4,onload:e=>{try{let o=null;if(e.responseText)try{o=JSON.parse(e.responseText)}catch(t){o=e.responseText}if(e.status>=200&&e.status<300)t({status:e.status,data:o,headers:e.responseHeaders});else{const t=o&&o.message||`HTTP ${e.status}: ${e.statusText||"请求失败"}`;n(new Error(t))}}catch(e){n(e)}},onerror:()=>n(new Error("网络请求失败,请检查网络或代理设置")),ontimeout:()=>n(new Error("网络请求超时 (20秒)"))}):fetch(s,{method:o,headers:{Accept:"application/vnd.github.v3+json",...i},body:r?"string"==typeof r?r:JSON.stringify(r):void 0}).then(async e=>{const o=await e.text();let s=null;try{s=JSON.parse(o)}catch(e){s=o}e.ok?t({status:e.status,data:s}):n(new Error(s&&s.message||`HTTP ${e.status}`))}).catch(e=>n(new Error("Fetch 网络异常: "+e.message)))}),getToken:()=>(GM_getValue("Config.sync_gist_token","")||"").trim(),getGistId:()=>(GM_getValue("Config.sync_gist_id","")||"").trim(),isAutoSyncEnabled:()=>Boolean(GM_getValue("Config.sync_auto",!1)),getIdleMinutes(){const e=Number(GM_getValue("Config.sync_idle_minutes",5));return!isNaN(e)&&e>0?Math.max(1,Math.floor(e)):5},getLastSyncTime:()=>GM_getValue("Config.sync_last_time",0),setSyncConfig(e){"string"==typeof e.token&&GM_setValue("Config.sync_gist_token",e.token.trim()),"string"==typeof e.gistId&&GM_setValue("Config.sync_gist_id",e.gistId.trim()),"boolean"==typeof e.autoSync&&(GM_setValue("Config.sync_auto",e.autoSync),e.autoSync?this.startIdleSyncMonitor():this.stopIdleSyncMonitor()),"number"==typeof e.idleMinutes&&e.idleMinutes>0&&GM_setValue("Config.sync_idle_minutes",Math.max(1,Math.floor(e.idleMinutes))),"number"==typeof e.lastSyncTime&&GM_setValue("Config.sync_last_time",e.lastSyncTime)},async testConnection(e){const t=(void 0!==e?e:this.getToken()).trim();if(!t)throw new Error("请输入 GitHub Personal Access Token");const n=await this.httpRequest({method:"GET",url:"https://api.github.com/user",headers:{Authorization:`Bearer ${t}`}});return{success:!0,login:n.data.login,name:n.data.name||n.data.login,avatar_url:n.data.avatar_url,public_gists:n.data.public_gists,private_gists:n.data.total_private_gists}},async listUserGists(e){const t=(e||this.getToken()).trim();if(!t)throw new Error("请先输入有效的 GitHub Token");const n=await this.httpRequest({method:"GET",url:"https://api.github.com/gists?per_page=100",headers:{Authorization:`Bearer ${t}`}});return(Array.isArray(n.data)?n.data:[]).map(e=>{const t=e.files?Object.keys(e.files):[],n=t.includes(this.GIST_FILENAME);return{id:e.id,description:e.description||"(未命名 Gist)",isPublic:e.public,files:t,isSnapshotGist:n,createdAt:e.created_at,updatedAt:e.updated_at}})},async fetchRemoteGist(e,t){const n=(e||this.getToken()).trim(),o=(t||this.getGistId()).trim();if(!n)throw new Error("未配置 GitHub Token");if(!o)throw new Error("未配置 Gist ID");const s=await this.httpRequest({method:"GET",url:`https://api.github.com/gists/${o}`,headers:{Authorization:`Bearer ${n}`}}),i=(s.data.files||{})[this.GIST_FILENAME];if(!i)return{exists:!0,isEmpty:!0,records:{},tombstones:{},custom_themes:{},theme_tombstones:{},lastSyncTime:0,rawGist:s.data};let r=i.content;if((i.truncated||!r)&&i.raw_url)try{const e=await this.httpRequest({method:"GET",url:i.raw_url,headers:{Authorization:`Bearer ${n}`}});r="string"==typeof e.data?e.data:JSON.stringify(e.data)}catch(e){console.warn("[GistSync] 拉取 raw_url 失败:",e)}let a=null;try{a=this.safeParseRemoteGistData(r)}catch(e){if(i.raw_url&&!i.truncated&&r===i.content)try{const e=await this.httpRequest({method:"GET",url:i.raw_url,headers:{Authorization:`Bearer ${n}`}}),t="string"==typeof e.data?e.data:JSON.stringify(e.data);a=this.safeParseRemoteGistData(t)}catch(e){console.warn("[GistSync] 重试拉取 raw_url 仍失败:",e)}a||(console.warn("[GistSync] Gist 快照数据 JSON 解析失败,尝试容错分块提取:",e),a=this.recoverCorruptedGistJson(r))}if(!a||"object"!=typeof a)throw new Error("Gist 内快照数据格式已损坏且无法提取有效快照");const{cleanMap:c,corruptedCount:l}=this.sanitizeRecordsMap(a.records);return{exists:!0,isEmpty:!1,records:c,tombstones:this.sanitizeTombstonesMap(a.tombstones),custom_themes:this.sanitizeThemesMap(a.custom_themes),theme_tombstones:this.sanitizeThemeTombstonesMap(a.theme_tombstones),corruptedRecordCount:l,lastSyncTime:"number"==typeof a.lastSyncTime?a.lastSyncTime:0,version:a.version||"1.0",rawGist:s.data}},safeParseRemoteGistData(e){if(!e)return null;if("object"==typeof e)return e;const t=String(e).trim();try{return JSON.parse(t)}catch(e){try{const e=t.replace(/^\uFEFF/,"").replace(/,\s*([\]}])/g,"$1");return JSON.parse(e)}catch(e){return this.recoverCorruptedGistJson(t)}}},recoverCorruptedGistJson(e){if(!e||"string"!=typeof e)return{records:{},tombstones:{},custom_themes:{},theme_tombstones:{},lastSyncTime:0};const t={format:"LSM_GIST_SYNC",version:"1.5.0",records:{},tombstones:{},custom_themes:{},theme_tombstones:{},lastSyncTime:0},n=e.match(/"lastSyncTime"\s*:\s*(\d+)/);n&&(t.lastSyncTime=parseInt(n[1],10)||0);let o=0,s=-1,i=!1,r=!1;for(let n=0;nt.id===e.id)||t.records[n].push(e)}else if(e.id&&e.tokens&&("LSM_THEME_CONFIG"===e.type||e.name))t.custom_themes[e.id]=e;else if(e.id&&"number"==typeof e.deletedAt){const n=e.domain||location.hostname||"default";t.tombstones[n]||(t.tombstones[n]=[]),t.tombstones[n].some(t=>t.id===e.id)||t.tombstones[n].push(e)}}catch(e){}s=-1}else o<0&&(o=0,s=-1)}else i=!i;else r=!0}return t},isValidRecord:e=>!(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.id||!e.id.trim()||"string"!=typeof e.name&&!e.name||void 0===e.cipherData&&void 0===e.summary&&void 0===e.url||e.cipherData&&"object"==typeof e.cipherData&&!0===e.cipherData.encrypted&&("string"!=typeof e.cipherData.payload||!e.cipherData.payload)),sanitizeRecordsMap(e){const t={};let n=0,o=0;if(e&&"object"==typeof e)for(const[s,i]of Object.entries(e))if(Array.isArray(i)){const e=[];for(const t of i)this.isValidRecord(t)?(e.push(t),n++):(o++,console.warn(`[GistSync] 过滤忽略损坏的单条快照数据 (域名: ${s}):`,t));e.length>0&&(t[s]=e)}return{cleanMap:t,totalValid:n,corruptedCount:o}},sanitizeTombstonesMap(e){const t={};if(e&&"object"==typeof e)for(const[n,o]of Object.entries(e))if(Array.isArray(o)){const e=o.filter(e=>e&&"object"==typeof e&&"string"==typeof e.id&&"number"==typeof e.deletedAt);e.length>0&&(t[n]=e)}return t},sanitizeThemesMap(e){const t={};if(e&&"object"==typeof e)for(const[n,o]of Object.entries(e))o&&"object"==typeof o&&o.id&&(t[n]=o);return t},sanitizeThemeTombstonesMap(e){const t={};if(e&&"object"==typeof e)for(const[n,o]of Object.entries(e))"string"==typeof n&&"number"==typeof o&&(t[n]=o);return t},async createGist(e,t){const n=(e||this.getToken()).trim();if(!n)throw new Error("请先输入有效的 GitHub Token");const o=t||DB.getAllLocalData();o.lastSyncTime=Date.now(),o.format="LSM_GIST_SYNC",o.version="1.5.0",o.custom_themes||void 0===ThemeEngine||(o.custom_themes=ThemeEngine.getCustomThemes()),o.theme_tombstones||void 0===ThemeEngine||(o.theme_tombstones=ThemeEngine.getThemeTombstones());const s=await this.httpRequest({method:"POST",url:"https://api.github.com/gists",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},data:{description:"网站快照存储与恢复助手 - 云同步备份数据 (WebSnapshotManager)",public:!1,files:{[this.GIST_FILENAME]:{content:JSON.stringify(o,null,2)}}}}),i=s.data.id;if(!i)throw new Error("创建 Gist 失败,GitHub 未返回 Gist ID");return this.setSyncConfig({gistId:i,lastSyncTime:Date.now()}),{gistId:i,htmlUrl:s.data.html_url}},async updateGist(e,t,n){const o=(e||this.getToken()).trim(),s=(t||this.getGistId()).trim();if(!o)throw new Error("未配置 GitHub Token");if(!s)throw new Error("未配置 Gist ID");const i={...n,format:"LSM_GIST_SYNC",version:"1.5.0",lastSyncTime:Date.now()};return await this.httpRequest({method:"PATCH",url:`https://api.github.com/gists/${s}`,headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},data:{description:"网站快照存储与恢复助手 - 云同步备份数据 (WebSnapshotManager)",files:{[this.GIST_FILENAME]:{content:JSON.stringify(i,null,2)}}}}),this.setSyncConfig({lastSyncTime:i.lastSyncTime}),i},mergeThemeData(e={},t={},n={},o={}){const s=e&&"object"==typeof e?e:{},i=t&&"object"==typeof t?t:{},r=n&&"object"==typeof n?n:{},a=o&&"object"==typeof o?o:{},c={},l=Date.now()-2592e6,d=new Set([...Object.keys(r),...Object.keys(a)]);for(const e of d){const t="number"==typeof r[e]?r[e]:0,n="number"==typeof a[e]?a[e]:0,o=Math.max(t,n);o>l&&(c[e]=o)}const p={},g=new Set([...Object.keys(s),...Object.keys(i)]);let m=0,u=0,h=0;for(const e of g){const t=s[e],n=i[e],o=c[e]||0,r=e=>{if(!e)return!0;const t=e.updatedAt||e.createdAt||0;return o>=t};if(t&&r(t))h++;else if(n&&r(n))h++;else if(t&&!n)p[e]=t;else if(!t&&n){if(void 0!==ThemeEngine)try{p[e]=ThemeEngine.validateAndNormalizeTheme(n)}catch(t){p[e]=n}else p[e]=n;m++}else if(t&&n){const o=t.updatedAt||t.createdAt||0;if((n.updatedAt||n.createdAt||0)>o){if(void 0!==ThemeEngine)try{p[e]=ThemeEngine.validateAndNormalizeTheme(n)}catch(t){p[e]=n}else p[e]=n;u++}else p[e]=t}}return{customThemes:p,themeTombstones:c,stats:{totalThemes:Object.keys(p).length,addedFromRemoteThemeCount:m,updatedThemeCount:u,purgedByThemeTombCount:h}}},mergeSnapshotData(e,t){const{cleanMap:n,corruptedCount:o}=this.sanitizeRecordsMap(e.records),{cleanMap:s,corruptedCount:i}=this.sanitizeRecordsMap(t.records),r=this.sanitizeTombstonesMap(e.tombstones),a=this.sanitizeTombstonesMap(t.tombstones),c=new Set([...Object.keys(n),...Object.keys(s),...Object.keys(r),...Object.keys(a)]),l={},d=Date.now()-2592e6;for(const e of c){const t=Array.isArray(r[e])?r[e]:[],n=Array.isArray(a[e])?a[e]:[],o=new Map;for(const e of[...t,...n])e&&e.id&&e.deletedAt&&(e.deletedAt<=d||(!o.has(e.id)||o.get(e.id).deletedAt0&&(l[e]=Array.from(o.values()))}const p={};let g=0,m=0,u=0,h=0;for(const e of c){const t=Array.isArray(n[e])?n[e]:[],o=Array.isArray(s[e])?s[e]:[],i=l[e]||[],r=new Map(i.map(e=>[e.id,e.deletedAt])),a=new Map,c=e=>!e||!e.id||!!(r.has(e.id)&&r.get(e.id)>=(e.updatedAt||e.createdAt||0));for(const e of t)c(e)?m++:a.set(e.id,e);for(const e of o)if(c(e))m++;else if(a.has(e.id)){const t=a.get(e.id),n=t.updatedAt||t.createdAt||0;(e.updatedAt||e.createdAt||0)>n&&(a.set(e.id,e),h++)}else a.set(e.id,e),u++;const d=Array.from(a.values()).sort((e,t)=>(t.createdAt||t.updatedAt||0)-(e.createdAt||e.updatedAt||0));d.length>0&&(p[e]=d,g+=d.length)}return{records:p,tombstones:l,totalSnapshots:g,stats:{totalMergedCount:g,purgedByTombstoneCount:m,addedFromRemoteCount:u,updatedCount:h,corruptedSkippedCount:(o||0)+(i||0)+(t.corruptedRecordCount||0)}}},async twoWaySync(e={}){const{silent:t=!1}=e;if(this.syncLock)return t||"function"!=typeof showToast||showToast("已有同步任务正在进行中,请稍候...","info"),{success:!1,reason:"locked"};const n=this.getToken(),o=this.getGistId();if(!n)return t||"function"!=typeof showToast||showToast("请先在云同步设置中配置 GitHub Token","error"),{success:!1,reason:"no_token"};if(!o)return t||"function"!=typeof showToast||showToast("请先配置 Gist ID 或点击一键自动创建","error"),{success:!1,reason:"no_gist_id"};this.syncLock=!0,this.notifySyncStatus("syncing");try{t||"function"!=typeof showToast||showToast("正在与 GitHub Gist 双向同步...","info");const e=DB.getAllLocalData(),s=await this.fetchRemoteGist(n,o),i=this.mergeSnapshotData(e,s);DB.applyMergedData(i.records,i.tombstones);const r=this.mergeThemeData(e.custom_themes||{},s.custom_themes||{},e.theme_tombstones||{},s.theme_tombstones||{});if(void 0!==ThemeEngine&&(ThemeEngine.saveCustomThemesMap(r.customThemes),ThemeEngine.saveThemeTombstones(r.themeTombstones),ThemeEngine.applyTheme()),await this.updateGist(n,o,{records:i.records,tombstones:i.tombstones,totalSnapshots:i.totalSnapshots,custom_themes:r.customThemes,theme_tombstones:r.themeTombstones}),this.notifySyncStatus("success"),"function"==typeof refreshList&&refreshList(),"function"==typeof renderThemeList&&renderThemeList(),"function"==typeof renderQuickThemeMenu&&renderQuickThemeMenu(),!t&&"function"==typeof showToast){const e=i.stats,t=r.stats;let n=`同步成功!全域共 ${i.totalSnapshots} 条快照,${t.totalThemes} 套自定义主题`;const o=[];e.addedFromRemoteCount>0&&o.push(`快照 +${e.addedFromRemoteCount}`),e.purgedByTombstoneCount>0&&o.push(`快照清理 -${e.purgedByTombstoneCount}`),e.corruptedSkippedCount>0&&o.push(`忽略损坏快照 ${e.corruptedSkippedCount} 条`),t.addedFromRemoteThemeCount>0&&o.push(`主题 +${t.addedFromRemoteThemeCount}`),t.purgedByThemeTombCount>0&&o.push(`主题清理 -${t.purgedByThemeTombCount}`),o.length>0&&(n+=` (${o.join(",")})`),showToast(n,"success")}return{success:!0,result:i,themeResult:r}}catch(e){return this.notifySyncStatus("error",e.message),t||"function"!=typeof showToast||showToast(`同步失败: ${e.message}`,"error"),{success:!1,error:e}}finally{this.syncLock=!1}},recordActivity(){this.lastActivityTime=Date.now()},isPluginInUse(){try{if(void 0!==LSM_UI&&"function"==typeof LSM_UI.isInUse)return LSM_UI.isInUse()}catch(e){}return!1},initActivityListeners(e){if(this._activityListenersInitialized)return void(e&&this._bindShadowActivity(e));this._activityListenersInitialized=!0;const t=()=>{this.recordActivity()};["mousemove","mousedown","mouseup","keydown","keyup","scroll","wheel","touchstart","touchend","touchmove","pointerdown","pointermove","input","change","focus"].forEach(e=>{try{window.addEventListener(e,t,{capture:!0,passive:!0})}catch(e){}}),document.addEventListener("visibilitychange",()=>{document.hidden||this.recordActivity()}),e&&this._bindShadowActivity(e),this.isAutoSyncEnabled()&&this.startIdleSyncMonitor()},_bindShadowActivity(e){if(!e||e._lsmActivityBound)return;e._lsmActivityBound=!0;const t=()=>{this.recordActivity()};["mousedown","mouseup","click","keydown","input","scroll","touchstart"].forEach(n=>{try{e.addEventListener(n,t,{capture:!0,passive:!0})}catch(e){}})},scheduleAutoSync(){if(!this.isAutoSyncEnabled())return;const e=this.getToken(),t=this.getGistId();e&&t&&(this.hasPendingChanges=!0,this.startIdleSyncMonitor())},startIdleSyncMonitor(){this.idleMonitorTimer||(this.idleMonitorTimer=setInterval(()=>{this.checkAndTriggerIdleSync()},1e4))},stopIdleSyncMonitor(){this.idleMonitorTimer&&(clearInterval(this.idleMonitorTimer),this.idleMonitorTimer=null)},async checkAndTriggerIdleSync(){if(!this.isAutoSyncEnabled())return;const e=this.getToken(),t=this.getGistId();if(!e||!t)return;if(this.syncLock)return;if(this.isPluginInUse())return;const n=60*this.getIdleMinutes()*1e3,o=Date.now();if(o-this.lastActivityTime=n)try{const e=await this.twoWaySync({silent:!0,checkConflict:!1});e&&e.success&&(this.hasPendingChanges=!1)}catch(e){console.warn("[GistSync] 空闲自动同步失败:",e)}},checkSyncOnOpen(){"function"==typeof updateCloudStatusUI&&updateCloudStatusUI()},notifySyncStatus(e,t){"function"==typeof updateCloudStatusUI&&updateCloudStatusUI(e,t)}};function initAppUI(){function e(e){if(!e)return"-";const t=new Date(e);if(isNaN(t.getTime()))return"-";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function t(){const e=new Date,t=e=>String(e).padStart(2,"0");return`${location.hostname}_${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}_${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function n(e){return e?String(e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"):""}function o(e,t){try{const n=JSON.stringify(t,null,2),o=new Blob([n],{type:"application/json;charset=utf-8"}),s=URL.createObjectURL(o),i=document.createElement("a");i.href=s,i.download=e,document.body.appendChild(i),i.click(),setTimeout(()=>{document.body.removeChild(i),URL.revokeObjectURL(s)},100)}catch(e){alert("下载文件失败: "+e.message)}}function s(e){return new Promise((t,n)=>{const o=new FileReader;o.onload=e=>{try{const n=JSON.parse(e.target.result);t(n)}catch(e){n(new Error("文件解析失败,请确认选择的是正确的 JSON 格式文件"))}},o.onerror=()=>n(new Error("读取文件出错")),o.readAsText(e)})}const i="lsm-"+Math.random().toString(36).slice(2,8),r=document.createElement("div");r.id="lsm-session-manager-root";const a=r.attachShadow({mode:"open"});ThemeEngine.bindShadow(a,i),document.documentElement.appendChild(r);const c=document.createElement("style");c.textContent=`\n #${i}-root {\n all: initial;\n display: block;\n box-sizing: border-box;\n font-family: var(--lsm-font-family, system-ui, -apple-system, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Noto Sans SC", "Segoe UI", Roboto, Helvetica, Arial, sans-serif);\n color: var(--lsm-text-primary, #24231f);\n font-size: 13px;\n line-height: 1.5;\n text-align: left;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n letter-spacing: 0.01em;\n }\n #${i}-root *, #${i}-root *::before, #${i}-root *::after {\n box-sizing: border-box;\n }\n #${i}-root input, #${i}-root select, #${i}-root textarea, #${i}-root button {\n font-family: inherit;\n }\n\n /* 全局滚动条通用美化 (Shadow DOM 内部全部容器与列表) */\n #${i}-root * {\n scrollbar-width: thin;\n scrollbar-color: var(--lsm-border-hover, #d0cec6) transparent;\n }\n #${i}-root *::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n }\n #${i}-root *::-webkit-scrollbar-track {\n background: transparent;\n border-radius: 9999px;\n }\n #${i}-root *::-webkit-scrollbar-thumb {\n background-color: var(--lsm-border-hover, #d0cec6);\n border-radius: 9999px;\n border: 1px solid transparent;\n background-clip: padding-box;\n transition: background-color 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n }\n #${i}-root *::-webkit-scrollbar-thumb:hover {\n background-color: var(--lsm-accent, #c56473);\n }\n #${i}-root *::-webkit-scrollbar-corner {\n background: transparent;\n }\n\n /* 悬浮球 (动态主题变量驱动) */\n #${i}-ball {\n position: fixed;\n left: auto;\n top: auto;\n right: 25px;\n bottom: 80px;\n z-index: 2147483646;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n background: var(--lsm-bg-paper, #faf9f5);\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.28));\n color: var(--lsm-accent, #c56473);\n font-weight: 600;\n font-size: 13px;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 6px 20px -2px var(--lsm-accent-glow, rgba(197, 100, 115, 0.2)), 0 2px 6px rgba(0, 0, 0, 0.05);\n cursor: grab;\n user-select: none;\n opacity: 0.75;\n transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease, opacity 0.25s ease, left 0.3s cubic-bezier(0.2, 0, 0, 1), top 0.3s cubic-bezier(0.2, 0, 0, 1), border-color 0.2s ease;\n }\n #${i}-ball:hover {\n opacity: 1;\n transform: scale(1.05);\n box-shadow: 0 10px 28px -4px var(--lsm-accent-glow, rgba(197, 100, 115, 0.32)), 0 2px 8px rgba(0, 0, 0, 0.08);\n border-color: var(--lsm-accent, rgba(197, 100, 115, 0.55));\n }\n #${i}-ball.dragging {\n opacity: 1;\n cursor: grabbing;\n transform: scale(0.96);\n transition: none;\n }\n #${i}-ball svg {\n width: 22px;\n height: 22px;\n fill: currentColor;\n pointer-events: none;\n filter: drop-shadow(0 1px 2px var(--lsm-accent-glow, rgba(197, 100, 115, 0.15)));\n }\n\n /* 悬浮球右上角微型关闭/菜单按钮 */\n .${i}-ball-close {\n position: absolute;\n top: -3px;\n right: -3px;\n width: 17px;\n height: 17px;\n border-radius: 50%;\n line-height: 15px;\n background: var(--lsm-text-primary, #24231f);\n color: var(--lsm-bg-paper, #faf9f5);\n font-size: 11px;\n text-align: center;\n cursor: pointer;\n display: none;\n z-index: 3;\n border: 1.5px solid var(--lsm-bg-paper, #faf9f5);\n box-shadow: 0 2px 5px rgba(0,0,0,0.15);\n transition: background 0.15s ease, transform 0.15s ease;\n }\n #${i}-ball:hover .${i}-ball-close {\n display: block;\n }\n .${i}-ball-close:hover {\n background: var(--lsm-color-danger, #a64953);\n transform: scale(1.15);\n }\n\n /* 徽标 */\n .${i}-badge {\n position: absolute;\n top: -3px;\n left: -3px;\n background: var(--lsm-accent, #c56473);\n color: #ffffff;\n font-size: 10px;\n font-weight: 600;\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n font-variant-numeric: tabular-nums;\n min-width: 18px;\n height: 18px;\n border-radius: 9999px;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0 4px;\n border: 1.5px solid var(--lsm-bg-paper, #faf9f5);\n box-shadow: 0 2px 6px var(--lsm-accent-glow, rgba(197, 100, 115, 0.35));\n }\n\n /* 悬浮球快捷菜单遮罩与弹窗 */\n .${i}-menu-mask {\n position: fixed;\n inset: 0;\n z-index: 2147483646;\n background: rgba(20, 19, 18, 0.45);\n backdrop-filter: blur(6px);\n -webkit-backdrop-filter: blur(6px);\n }\n .${i}-menu-mask.hidden { display: none; }\n .${i}-ball-menu {\n position: fixed;\n left: 50%;\n top: 45%;\n transform: translate(-50%, -50%);\n z-index: 2147483647;\n background: var(--lsm-bg-paper, #faf9f5);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-window, 16px);\n box-shadow: 0 20px 45px -10px rgba(0, 0, 0, 0.18), 0 1px 3px rgba(0,0,0,0.04);\n padding: 18px;\n width: 280px;\n animation: lsmFadeIn .2s cubic-bezier(0.16, 1, 0.3, 1);\n }\n .${i}-ball-menu-title {\n font-weight: 600;\n margin: 0 0 12px;\n font-size: 14px;\n color: var(--lsm-text-primary, #24231f);\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .${i}-ball-menu button {\n display: flex;\n align-items: center;\n width: 100%;\n margin-top: 8px;\n padding: 8px 12px;\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-btn, 8px);\n background: var(--lsm-bg-card, #ffffff);\n cursor: pointer;\n font-size: 12px;\n font-weight: 500;\n text-align: left;\n color: var(--lsm-text-primary, #403f3a);\n transition: all 0.15s cubic-bezier(0.22, 1, 0.36, 1);\n }\n .${i}-ball-menu button:hover {\n background: var(--lsm-bg-hover, #f0efeb);\n border-color: var(--lsm-border-hover, #d0cec6);\n color: var(--lsm-text-primary, #24231f);\n }\n .${i}-ball-menu button[data-a="forever"] {\n border-color: var(--lsm-border-danger, rgba(166, 73, 83, 0.2));\n background: var(--lsm-bg-danger, rgba(166, 73, 83, 0.06));\n color: var(--lsm-color-danger, #a64953);\n }\n .${i}-ball-menu button[data-a="forever"]:hover {\n background: var(--lsm-bg-danger, rgba(166, 73, 83, 0.12));\n border-color: var(--lsm-color-danger, rgba(166, 73, 83, 0.35));\n }\n\n /* 主管理窗口 (Paper Card 架构) */\n #${i}-window {\n position: fixed;\n left: auto;\n top: auto;\n right: 30px;\n bottom: 90px;\n z-index: 2147483646;\n width: 500px;\n height: 560px;\n max-width: calc(100vw - 20px);\n max-height: calc(100vh - 30px);\n background: var(--lsm-bg-paper, #faf9f5);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-window, 16px);\n overflow: hidden;\n overflow: clip;\n display: flex;\n flex-direction: column;\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.18), 0 1px 3px rgba(0, 0, 0, 0.04);\n overscroll-behavior: contain;\n touch-action: none;\n }\n #${i}-window.hidden, #${i}-ball.hidden {\n display: none !important;\n }\n\n /* 头部 Header */\n #${i}-header {\n flex: none;\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 18px;\n background: var(--lsm-bg-header, #f0efeb);\n color: var(--lsm-text-primary, #24231f);\n font-size: 13.5px;\n font-weight: 600;\n cursor: grab;\n user-select: none;\n border-bottom: 1px solid var(--lsm-border, #e3e1db);\n position: relative;\n }\n #${i}-header::before {\n content: "";\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n height: 1.5px;\n background: linear-gradient(90deg, transparent 0%, var(--lsm-accent, #c56473) 20%, var(--lsm-accent, #c56473) 80%, transparent 100%);\n opacity: 0.7;\n }\n #${i}-header.dragging {\n cursor: grabbing;\n }\n .${i}-header-left {\n display: flex;\n align-items: center;\n gap: 10px;\n }\n .${i}-header-title {\n display: flex;\n align-items: center;\n gap: 6px;\n letter-spacing: 0.02em;\n }\n .${i}-domain-tag {\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.08));\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.2));\n color: var(--lsm-accent, #c56473);\n font-size: 11px;\n padding: 2px 9px;\n border-radius: 6px;\n font-weight: 500;\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n max-width: 180px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n .${i}-header-actions {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .${i}-header-actions button {\n border: 1px solid rgba(0, 0, 0, 0.08);\n background: transparent;\n color: var(--lsm-text-muted, #787670);\n border-radius: 6px;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n font-size: 13px;\n transition: all 0.15s ease;\n }\n .${i}-header-actions button:hover {\n background: var(--lsm-border, #e3e1db);\n color: var(--lsm-text-primary, #24231f);\n }\n\n /* 状态条 */\n .${i}-status-bar {\n padding: 7px 18px;\n background: var(--lsm-bg-paper, #faf9f5);\n border-bottom: 1px solid var(--lsm-border, #e3e1db);\n display: flex;\n align-items: center;\n justify-content: space-between;\n font-size: 11px;\n color: var(--lsm-text-muted, #787670);\n flex: none;\n }\n .${i}-status-item {\n display: flex;\n align-items: center;\n gap: 6px;\n font-weight: 500;\n }\n .${i}-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n display: inline-block;\n }\n .${i}-dot-green {\n background: var(--lsm-color-success, #5e9f7e);\n box-shadow: 0 0 0 2px var(--lsm-border-success, rgba(94, 159, 126, 0.2));\n }\n .${i}-dot-amber {\n background: var(--lsm-color-warning, #a87a3d);\n box-shadow: 0 0 0 2px var(--lsm-border-warning, rgba(168, 122, 61, 0.2));\n }\n\n /* 操作工具栏 */\n .${i}-toolbar {\n padding: 10px 18px;\n background: var(--lsm-bg-paper, #faf9f5);\n border-bottom: 1px solid var(--lsm-border, #e3e1db);\n display: flex;\n flex-direction: column;\n gap: 8px;\n flex: none;\n }\n .${i}-toolbar-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n flex-wrap: nowrap;\n }\n .${i}-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 5px;\n padding: 6px 12px;\n font-size: 12px;\n font-weight: 500;\n border-radius: var(--lsm-radius-btn, 8px);\n border: 1px solid transparent;\n cursor: pointer;\n user-select: none;\n white-space: nowrap;\n transition: all 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n }\n .${i}-btn:active {\n transform: translateY(1px);\n }\n .${i}-btn-primary {\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.08)) !important;\n color: var(--lsm-accent, #c56473) !important;\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.3)) !important;\n }\n .${i}-btn-primary:hover {\n background: var(--lsm-accent-hover-bg, rgba(197, 100, 115, 0.14)) !important;\n border-color: var(--lsm-accent, #c56473) !important;\n color: var(--lsm-accent, #c56473) !important;\n }\n .${i}-btn-secondary {\n background: transparent;\n color: var(--lsm-text-primary, #403f3a);\n border: 1px solid var(--lsm-border, #e3e1db);\n }\n .${i}-btn-secondary:hover {\n background: var(--lsm-bg-hover, #f0efeb);\n border-color: var(--lsm-border-hover, #d0cec6);\n color: var(--lsm-text-primary, #24231f);\n }\n .${i}-btn-danger {\n background: var(--lsm-bg-danger, rgba(166, 73, 83, 0.08));\n color: var(--lsm-color-danger, #a64953);\n border: 1px solid var(--lsm-border-danger, rgba(166, 73, 83, 0.25));\n }\n .${i}-btn-danger:hover {\n background: var(--lsm-bg-danger, rgba(166, 73, 83, 0.14));\n border-color: var(--lsm-color-danger, rgba(166, 73, 83, 0.4));\n }\n .${i}-btn-restore-pill {\n background: var(--lsm-bg-success, rgba(94, 159, 126, 0.08)) !important;\n color: var(--lsm-color-success, #5e9f7e) !important;\n border: 1px solid var(--lsm-border-success, rgba(94, 159, 126, 0.28)) !important;\n font-weight: 500;\n }\n .${i}-btn-restore-pill:hover {\n background: var(--lsm-bg-success, rgba(94, 159, 126, 0.16)) !important;\n border-color: var(--lsm-color-success, rgba(94, 159, 126, 0.45)) !important;\n }\n .${i}-btn-sm {\n padding: 4px 9px;\n font-size: 11px;\n border-radius: 6px;\n }\n .${i}-btn-icon {\n padding: 6px 8px !important;\n min-width: 28px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n }\n\n /* 更多操作下拉菜单 */\n .${i}-dropdown-wrapper {\n position: relative;\n display: inline-flex;\n flex-shrink: 0;\n }\n .${i}-dropdown-menu {\n position: absolute;\n top: calc(100% + 6px);\n right: 0;\n min-width: 180px;\n background: var(--lsm-bg-paper, #faf9f5);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n padding: 5px;\n box-shadow: 0 12px 30px -4px rgba(0, 0, 0, 0.16), 0 1px 3px rgba(0,0,0,0.04);\n backdrop-filter: blur(12px);\n -webkit-backdrop-filter: blur(12px);\n z-index: 50;\n display: flex;\n flex-direction: column;\n gap: 2px;\n }\n .${i}-dropdown-menu.hidden {\n display: none !important;\n }\n .${i}-dropdown-item {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 7px 10px;\n font-size: 12px;\n font-weight: 500;\n color: var(--lsm-text-primary, #403f3a);\n border-radius: 7px;\n cursor: pointer;\n user-select: none;\n transition: all 0.12s ease;\n white-space: nowrap;\n }\n .${i}-dropdown-item:hover {\n background: var(--lsm-bg-hover, #f0efeb);\n color: var(--lsm-text-primary, #24231f);\n }\n .${i}-dropdown-divider {\n height: 1px;\n background: var(--lsm-border, #e3e1db);\n margin: 3px 0;\n }\n .${i}-item-accent {\n color: var(--lsm-accent, #c56473) !important;\n font-weight: 500;\n }\n .${i}-item-accent:hover {\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.08)) !important;\n color: var(--lsm-accent, #c56473) !important;\n }\n\n /* 移动端与小屏幕自适应响应式布局 */\n @media (max-width: 480px) {\n #${i}-window {\n left: 10px !important;\n right: 10px !important;\n bottom: 15px !important;\n width: auto !important;\n max-width: calc(100vw - 20px) !important;\n height: 82vh !important;\n border-radius: 14px;\n }\n #${i}-header {\n padding: 10px 14px;\n }\n .${i}-domain-tag {\n max-width: 170px;\n font-size: 10px;\n padding: 1px 6px;\n }\n .${i}-toolbar {\n padding: 8px 12px;\n gap: 6px;\n }\n .${i}-toolbar-row {\n gap: 6px;\n }\n .${i}-btn {\n padding: 5px 8px;\n font-size: 11px;\n gap: 4px;\n }\n .${i}-content {\n padding: 10px 12px;\n gap: 8px;\n }\n .${i}-card {\n padding: 10px 12px;\n }\n .${i}-card-chips {\n gap: 4px;\n }\n .${i}-chip {\n font-size: 10px;\n padding: 1px 6px;\n }\n .${i}-card-actions {\n flex-wrap: wrap;\n gap: 4px;\n justify-content: flex-end;\n }\n .${i}-card-actions .${i}-btn {\n padding: 4px 7px;\n font-size: 10px;\n }\n .${i}-search-input {\n height: 30px;\n font-size: 11px;\n padding: 0 26px 0 28px;\n }\n .${i}-theme-grid {\n grid-template-columns: 1fr !important;\n max-height: 280px;\n }\n }\n\n /* 搜索栏 */\n .${i}-search-wrap {\n position: relative;\n display: flex;\n align-items: center;\n width: 100%;\n margin-top: 2px;\n }\n .${i}-search-icon {\n position: absolute;\n left: 10px;\n pointer-events: none;\n color: var(--lsm-text-placeholder, #a8a69f);\n display: flex;\n align-items: center;\n justify-content: center;\n transition: color 0.15s ease;\n }\n .${i}-search-input {\n width: 100%;\n height: 32px;\n padding: 0 28px 0 32px;\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-btn, 8px);\n background: var(--lsm-bg-card, #ffffff);\n background-image: linear-gradient(180deg, var(--lsm-accent-glow, rgba(197, 100, 115, 0.03)) 0%, transparent 26%);\n font-size: 12px;\n color: var(--lsm-text-primary, #24231f);\n outline: none;\n box-sizing: border-box;\n transition: border-color 0.2s, box-shadow 0.2s;\n }\n .${i}-search-input::placeholder {\n color: var(--lsm-text-placeholder, #a8a69f);\n font-size: 11px;\n }\n .${i}-search-input:focus {\n background: var(--lsm-bg-card, #ffffff);\n border-color: var(--lsm-accent-border, rgba(197, 100, 115, 0.35));\n box-shadow: 0 0 0 3px var(--lsm-accent-glow, rgba(197, 100, 115, 0.1));\n }\n .${i}-search-wrap:focus-within .${i}-search-icon {\n color: var(--lsm-accent, #c56473);\n }\n .${i}-search-clear {\n position: absolute;\n right: 7px;\n width: 17px;\n height: 17px;\n border-radius: 50%;\n border: none;\n background: var(--lsm-border, #e3e1db);\n color: var(--lsm-text-muted, #787670);\n font-size: 10px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n transition: all 0.15s ease;\n }\n .${i}-search-clear:hover {\n background: var(--lsm-border-hover, #d0cec6);\n color: var(--lsm-text-primary, #24231f);\n transform: scale(1.08);\n }\n .${i}-search-clear.hidden {\n display: none !important;\n }\n\n /* 记录列表区域 */\n .${i}-content {\n padding: 12px 18px;\n overflow-y: auto;\n flex: 1;\n display: flex;\n flex-direction: column;\n gap: 10px;\n min-height: 0;\n background: var(--lsm-bg-list, #f9f8f5);\n overscroll-behavior: contain;\n -webkit-overflow-scrolling: touch;\n touch-action: pan-y;\n }\n .${i}-card {\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n padding: 12px 14px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);\n transition: all 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n }\n .${i}-card:hover {\n border-color: var(--lsm-border-hover, #d0cec6);\n transform: translateY(-1px);\n box-shadow: 0 6px 20px -2px rgba(0, 0, 0, 0.06);\n }\n .${i}-card.${i}-card-active {\n border-color: var(--lsm-border-success, rgba(94, 159, 126, 0.38));\n background: var(--lsm-bg-active-card, linear-gradient(180deg, rgba(94, 159, 126, 0.05) 0%, #ffffff 60%));\n box-shadow: 0 4px 14px -2px var(--lsm-border-success, rgba(94, 159, 126, 0.12));\n }\n .${i}-badge-active {\n display: inline-flex;\n align-items: center;\n padding: 1px 6px;\n border-radius: 4px;\n font-size: 10px;\n font-weight: 500;\n background: var(--lsm-bg-success, rgba(94, 159, 126, 0.12));\n color: var(--lsm-color-success, #5e9f7e);\n border: 1px solid var(--lsm-border-success, rgba(94, 159, 126, 0.25));\n margin-left: 4px;\n flex-shrink: 0;\n }\n .${i}-card-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n }\n .${i}-card-name {\n font-weight: 600;\n font-size: 13px;\n color: var(--lsm-text-primary, #24231f);\n word-break: break-all;\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .${i}-card-time {\n font-size: 11px;\n color: var(--lsm-text-muted, #787670);\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n font-variant-numeric: tabular-nums;\n flex-shrink: 0;\n }\n \n /* 凭证 Chips 徽章组 */\n .${i}-card-chips {\n display: flex;\n align-items: center;\n gap: 6px;\n flex-wrap: wrap;\n }\n .${i}-chip {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n font-size: 11px;\n font-weight: 500;\n padding: 2px 7px;\n border-radius: 6px;\n line-height: 1.35;\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n font-variant-numeric: tabular-nums;\n }\n .${i}-chip-cookie {\n background: var(--lsm-bg-warning, rgba(168, 122, 61, 0.08));\n color: var(--lsm-color-warning, #a87a3d);\n border: 1px solid var(--lsm-border-warning, rgba(168, 122, 61, 0.2));\n }\n .${i}-chip-local {\n background: var(--lsm-bg-success, rgba(94, 159, 126, 0.08));\n color: var(--lsm-color-success, #5e9f7e);\n border: 1px solid var(--lsm-border-success, rgba(94, 159, 126, 0.2));\n }\n .${i}-chip-session {\n background: var(--lsm-bg-info, rgba(61, 104, 150, 0.08));\n color: var(--lsm-color-info, #3d6896);\n border: 1px solid var(--lsm-border-info, rgba(61, 104, 150, 0.2));\n }\n .${i}-chip-encrypted {\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.08));\n color: var(--lsm-accent, #c56473);\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.2));\n }\n\n /* 来源链接小标签 */\n .${i}-card-origin {\n display: flex;\n align-items: center;\n gap: 6px;\n background: var(--lsm-bg-header, #f0efeb);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: 6px;\n padding: 3px 8px;\n margin-top: 2px;\n font-size: 11px;\n color: var(--lsm-text-muted, #787670);\n }\n .${i}-card-url {\n color: var(--lsm-accent, #c56473);\n text-decoration: none;\n word-break: break-all;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n display: inline-block;\n max-width: calc(100% - 60px);\n }\n .${i}-card-url:hover {\n text-decoration: underline;\n }\n\n /* 卡片操作栏 */\n .${i}-card-actions {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 5px;\n border-top: 1px solid var(--lsm-border, #f0efeb);\n padding-top: 8px;\n margin-top: 2px;\n }\n .${i}-empty {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 50px 0;\n color: var(--lsm-text-placeholder, #a8a69f);\n text-align: center;\n gap: 8px;\n }\n\n /* 抽屉基础样式 (未打开时强制 display: none,彻底杜绝外层窗口滚动穿透或焦点跳转导致的错位) */\n .${i}-save-dialog,\n .${i}-qr-dialog,\n .${i}-scan-dialog,\n .${i}-sync-dialog,\n .${i}-theme-dialog {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--lsm-bg-paper, #faf9f5);\n display: none;\n flex-direction: column;\n padding: 20px;\n gap: 14px;\n transform: translateY(100%);\n transition: transform 0.25s cubic-bezier(0.16, 1, 0.3, 1);\n z-index: 10;\n overscroll-behavior: contain;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n touch-action: pan-y;\n border-top: 1px solid var(--lsm-border, #e3e1db);\n box-sizing: border-box;\n pointer-events: none;\n }\n .${i}-save-dialog.open,\n .${i}-qr-dialog.open,\n .${i}-scan-dialog.open,\n .${i}-sync-dialog.open,\n .${i}-theme-dialog.open {\n display: flex !important;\n transform: translateY(0);\n pointer-events: auto;\n }\n .${i}-dialog-header,\n .${i}-save-dialog-title {\n font-size: 14.5px;\n font-weight: 600;\n color: var(--lsm-text-primary, #24231f);\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 6px;\n border-bottom: 1px solid var(--lsm-border, #e3e1db);\n padding-bottom: 10px;\n }\n .${i}-dialog-title {\n font-size: 14.5px;\n font-weight: 600;\n color: var(--lsm-text-primary, #24231f);\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .${i}-dialog-close {\n background: none;\n border: none;\n font-size: 16px;\n line-height: 1;\n color: var(--lsm-text-muted, #787670);\n cursor: pointer;\n padding: 4px;\n border-radius: 6px;\n transition: color 0.15s ease, background 0.15s ease;\n }\n .${i}-dialog-close:hover {\n color: var(--lsm-text-primary, #24231f);\n background: var(--lsm-bg-hover, #f0efeb);\n }\n\n .${i}-input-group {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .${i}-input-label {\n font-size: 12px;\n font-weight: 500;\n color: var(--lsm-text-secondary, #5c5a55);\n }\n .${i}-input {\n width: 100%;\n padding: 8px 12px;\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-btn, 8px);\n font-size: 12.5px;\n outline: none;\n background: var(--lsm-bg-card, #ffffff);\n background-image: linear-gradient(180deg, var(--lsm-accent-glow, rgba(197, 100, 115, 0.03)) 0%, transparent 26%);\n color: var(--lsm-text-primary, #24231f);\n transition: border-color 0.2s, box-shadow 0.2s;\n }\n .${i}-input:focus {\n border-color: var(--lsm-accent-border, rgba(197, 100, 115, 0.35));\n box-shadow: 0 0 0 3px var(--lsm-accent-glow, rgba(197, 100, 115, 0.1));\n }\n .${i}-grid-preview {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 10px;\n margin-top: 4px;\n }\n .${i}-stat-box {\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 10px);\n padding: 10px;\n text-align: center;\n }\n .${i}-stat-num {\n font-size: 18px;\n font-weight: 600;\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n font-variant-numeric: tabular-nums;\n color: var(--lsm-text-primary, #24231f);\n margin-top: 2px;\n }\n .${i}-stat-label {\n font-size: 11px;\n color: var(--lsm-text-muted, #787670);\n }\n\n /* 快照二维码展示抽屉 */\n .${i}-qr-box {\n background: var(--lsm-bg-header, #f0efeb);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n padding: 16px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 12px;\n }\n .${i}-qr-canvas-wrap {\n background: #ffffff;\n padding: 10px;\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n box-shadow: 0 4px 14px rgba(0, 0, 0, 0.04);\n display: flex;\n align-items: center;\n justify-content: center;\n max-width: 100%;\n }\n .${i}-qr-canvas-wrap canvas {\n max-width: 100%;\n height: auto !important;\n display: block;\n border-radius: 6px;\n }\n .${i}-qr-overflow-box {\n background: var(--lsm-bg-warning, rgba(168, 122, 61, 0.06));\n border: 1px solid var(--lsm-border-warning, rgba(168, 122, 61, 0.25));\n border-radius: var(--lsm-radius-card, 12px);\n padding: 16px 12px;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n text-align: center;\n max-width: 100%;\n }\n .${i}-qr-chunk-player {\n display: none;\n flex-direction: column;\n align-items: center;\n gap: 10px;\n width: 100%;\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n padding: 12px;\n }\n .${i}-qr-chunk-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n width: 100%;\n font-size: 12px;\n color: var(--lsm-text-primary, #403f3a);\n font-weight: 500;\n }\n .${i}-qr-chunk-badge {\n display: inline-flex;\n align-items: center;\n gap: 5px;\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.08));\n color: var(--lsm-accent, #c56473);\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.2));\n padding: 3px 8px;\n border-radius: 9999px;\n font-size: 11px;\n font-weight: 500;\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n }\n .${i}-qr-chunk-bar-wrap {\n width: 100%;\n height: 5px;\n background: var(--lsm-border, #e3e1db);\n border-radius: 9999px;\n overflow: hidden;\n }\n .${i}-qr-chunk-bar-fill {\n height: 100%;\n background: linear-gradient(90deg, var(--lsm-accent, #c56473), var(--lsm-accent-glow, #e08c99));\n border-radius: 9999px;\n transition: width 0.15s ease;\n }\n .${i}-qr-chunk-controls {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 6px;\n width: 100%;\n }\n\n /* 摄像头扫码 */\n .${i}-camera-viewport {\n position: relative;\n width: 100%;\n height: 220px;\n background: #141312;\n border-radius: var(--lsm-radius-card, 12px);\n overflow: hidden;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 4px 16px rgba(0,0,0,0.25) inset;\n }\n .${i}-camera-video {\n width: 100%;\n height: 100%;\n object-fit: cover;\n display: block;\n }\n .${i}-camera-placeholder {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: #a8a69f;\n gap: 8px;\n padding: 20px;\n text-align: center;\n font-size: 12px;\n background: rgba(20, 19, 18, 0.92);\n z-index: 2;\n }\n .${i}-scan-chunk-hud {\n position: absolute;\n top: 8px;\n left: 8px;\n right: 8px;\n background: rgba(20, 19, 18, 0.9);\n backdrop-filter: blur(8px);\n border: 1px solid var(--lsm-accent-border, rgba(197, 100, 115, 0.4));\n border-radius: 10px;\n padding: 8px 10px;\n display: flex;\n flex-direction: column;\n gap: 6px;\n z-index: 6;\n color: #faf9f5;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);\n }\n .${i}-scan-chunk-title {\n font-size: 11px;\n font-weight: 500;\n display: flex;\n align-items: center;\n justify-content: space-between;\n color: #faf9f5;\n }\n .${i}-scan-chunk-chips {\n display: flex;\n flex-wrap: wrap;\n gap: 3px;\n max-height: 48px;\n overflow-y: auto;\n padding: 2px 0;\n }\n .${i}-scan-chunk-dot {\n width: 16px;\n height: 16px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n font-size: 9px;\n font-weight: 600;\n border-radius: 3px;\n background: rgba(255, 255, 255, 0.1);\n color: #a8a69f;\n border: 1px solid rgba(255, 255, 255, 0.1);\n font-family: ui-monospace, "Cascadia Code PL", Consolas, monospace;\n transition: all 0.15s ease;\n }\n .${i}-scan-chunk-dot.received {\n background: var(--lsm-color-success, #5e9f7e);\n color: #ffffff;\n border-color: var(--lsm-border-success, #8cbea3);\n box-shadow: 0 0 5px var(--lsm-color-success, rgba(94, 159, 126, 0.7));\n transform: scale(1.05);\n }\n .${i}-scan-frame {\n position: absolute;\n width: 170px;\n height: 170px;\n border: 2px solid var(--lsm-accent, rgba(197, 100, 115, 0.7));\n border-radius: 12px;\n box-shadow: 0 0 0 9999px rgba(20, 19, 18, 0.5);\n z-index: 3;\n pointer-events: none;\n }\n .${i}-scan-corner {\n position: absolute;\n width: 16px;\n height: 16px;\n border-color: var(--lsm-accent, #c56473);\n border-style: solid;\n }\n .${i}-scan-corner-tl { top: -2px; left: -2px; border-width: 3px 0 0 3px; border-top-left-radius: 8px; }\n .${i}-scan-corner-tr { top: -2px; right: -2px; border-width: 3px 3px 0 0; border-top-right-radius: 8px; }\n .${i}-scan-corner-bl { bottom: -2px; left: -2px; border-width: 0 0 3px 3px; border-bottom-left-radius: 8px; }\n .${i}-scan-corner-br { bottom: -2px; right: -2px; border-width: 0 3px 3px 0; border-bottom-right-radius: 8px; }\n\n .${i}-scan-laser {\n position: absolute;\n left: 6px;\n right: 6px;\n height: 2px;\n background: linear-gradient(90deg, transparent 0%, var(--lsm-accent, #c56473) 50%, transparent 100%);\n box-shadow: 0 0 10px var(--lsm-accent, #c56473), 0 0 4px var(--lsm-color-danger, #a64953);\n animation: ${i}-laser-anim 2s infinite ease-in-out;\n z-index: 4;\n pointer-events: none;\n }\n @keyframes ${i}-laser-anim {\n 0% { top: 8px; opacity: 0.8; }\n 50% { top: calc(100% - 10px); opacity: 1; }\n 100% { top: 8px; opacity: 0.8; }\n }\n\n /* 导入上传选择区 */\n .${i}-import-options {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 10px;\n }\n .${i}-dropzone-btn {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 12px 8px;\n background: var(--lsm-bg-card, #ffffff);\n border: 1px dashed var(--lsm-border-hover, #d0cec6);\n border-radius: var(--lsm-radius-card, 10px);\n cursor: pointer;\n transition: all 0.15s ease;\n color: var(--lsm-text-primary, #403f3a);\n gap: 6px;\n text-align: center;\n }\n .${i}-dropzone-btn:hover {\n background: var(--lsm-bg-hover, #f0efeb);\n border-color: var(--lsm-accent, #c56473);\n color: var(--lsm-accent, #c56473);\n }\n .${i}-dropzone-label {\n font-size: 12px;\n font-weight: 500;\n }\n .${i}-dropzone-hint {\n font-size: 10px;\n color: var(--lsm-text-muted, #787670);\n }\n\n /* 识别成功结果展示卡片 */\n .${i}-result-card {\n background: var(--lsm-bg-success, rgba(94, 159, 126, 0.06));\n border: 1px solid var(--lsm-border-success, rgba(94, 159, 126, 0.25));\n border-radius: var(--lsm-radius-card, 12px);\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n }\n .${i}-result-title {\n font-size: 13px;\n font-weight: 600;\n color: var(--lsm-color-success, #5e9f7e);\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .${i}-result-domain-warn {\n background: var(--lsm-bg-warning, rgba(168, 122, 61, 0.08));\n border: 1px solid var(--lsm-border-warning, rgba(168, 122, 61, 0.25));\n border-radius: 8px;\n padding: 8px 10px;\n font-size: 11px;\n color: var(--lsm-color-warning, #a87a3d);\n line-height: 1.5;\n }\n\n /* 云同步状态指示点与动效 */\n .${i}-dot-cloud {\n background: var(--lsm-text-placeholder, #a8a69f);\n }\n .${i}-dot-cloud.ok {\n background: var(--lsm-color-success, #5e9f7e);\n box-shadow: 0 0 0 2px var(--lsm-border-success, rgba(94, 159, 126, 0.2));\n }\n .${i}-dot-cloud.syncing {\n background: var(--lsm-accent, #c56473);\n box-shadow: 0 0 0 2px var(--lsm-accent-glow, rgba(197, 100, 115, 0.2));\n animation: ${i}Pulse 1.2s infinite;\n }\n .${i}-dot-cloud.warn {\n background: var(--lsm-color-warning, #a87a3d);\n }\n .${i}-dot-cloud.err {\n background: var(--lsm-color-danger, #a64953);\n }\n\n @keyframes ${i}Pulse {\n 0% { opacity: 0.6; }\n 50% { opacity: 1; }\n 100% { opacity: 0.6; }\n }\n\n @keyframes ${i}Spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n\n .${i}-icon-sync.spinning {\n animation: ${i}Spin 0.85s linear infinite;\n }\n\n /* 云同步专属抽屉 */\n .${i}-sync-body,\n .${i}-theme-body {\n display: flex;\n flex-direction: column;\n gap: 14px;\n overflow-y: auto;\n -webkit-overflow-scrolling: touch;\n touch-action: pan-y;\n overscroll-behavior: contain;\n flex: 1;\n min-height: 0;\n padding-right: 0;\n box-sizing: border-box;\n }\n\n .${i}-sync-status-card,\n .${i}-theme-current-card {\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 12px);\n padding: 12px 14px;\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${i}-sync-toggle-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 12px;\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: 10px;\n }\n\n /* Switch 切换开关 */\n .${i}-switch {\n position: relative;\n display: inline-block;\n width: 38px;\n height: 22px;\n flex-shrink: 0;\n }\n .${i}-switch input {\n opacity: 0;\n width: 0;\n height: 0;\n }\n .${i}-slider {\n position: absolute;\n cursor: pointer;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: var(--lsm-border-hover, #d0cec6);\n transition: .2s;\n border-radius: 22px;\n }\n .${i}-slider:before {\n position: absolute;\n content: "";\n height: 16px;\n width: 16px;\n left: 3px;\n bottom: 3px;\n background-color: white;\n transition: .2s cubic-bezier(0.22, 1, 0.36, 1);\n border-radius: 50%;\n box-shadow: 0 1px 3px rgba(0,0,0,0.15);\n }\n .${i}-switch input:checked + .${i}-slider {\n background-color: var(--lsm-accent, #c56473);\n }\n .${i}-switch input:checked + .${i}-slider:before {\n transform: translateX(16px);\n }\n\n /* 主题管理网格 (Theme Grid) */\n .${i}-theme-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n grid-auto-rows: max-content;\n align-content: start;\n gap: 7px;\n max-height: 195px;\n overflow-y: auto;\n padding: 2px;\n box-sizing: border-box;\n }\n .${i}-theme-item {\n background: var(--lsm-bg-card, #ffffff);\n border: 1px solid var(--lsm-border, #e3e1db);\n border-radius: var(--lsm-radius-card, 10px);\n padding: 9px 10px;\n cursor: pointer;\n display: flex;\n flex-direction: column;\n justify-content: center;\n gap: 6px;\n position: relative;\n transition: all 0.2s cubic-bezier(0.22, 1, 0.36, 1);\n min-width: 0;\n min-height: 52px;\n box-sizing: border-box;\n flex-shrink: 0;\n }\n .${i}-theme-item:hover {\n border-color: var(--lsm-accent, #c56473);\n transform: translateY(-1px);\n box-shadow: 0 4px 12px var(--lsm-accent-glow, rgba(0,0,0,0.06));\n }\n .${i}-theme-item.${i}-theme-item-active {\n border-color: var(--lsm-accent, #c56473);\n background: var(--lsm-accent-bg, rgba(197, 100, 115, 0.04));\n box-shadow: 0 0 0 1.5px var(--lsm-accent, #c56473);\n }\n .${i}-theme-item-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 6px;\n min-width: 0;\n width: 100%;\n flex-shrink: 0;\n }\n .${i}-theme-item-title {\n font-weight: 600;\n font-size: 12px;\n color: var(--lsm-text-primary, #24231f);\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: 0;\n flex: 1;\n }\n .${i}-theme-item-badge {\n flex-shrink: 0;\n white-space: nowrap;\n }\n .${i}-theme-item-palette {\n display: flex;\n align-items: center;\n gap: 5px;\n margin-top: 1px;\n flex-shrink: 0;\n min-height: 14px;\n }\n .${i}-theme-swatch-dot {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n border: 1px solid rgba(0,0,0,0.12);\n flex-shrink: 0;\n display: inline-block;\n box-sizing: border-box;\n }\n\n /* Toast 提示 */\n .${i}-toast {\n position: fixed;\n top: 24px;\n left: 50%;\n transform: translateX(-50%) translateY(-10px);\n background: var(--lsm-text-primary, #24231f);\n color: var(--lsm-bg-paper, #faf9f5);\n padding: 8px 16px;\n border-radius: 8px;\n font-size: 12px;\n font-weight: 500;\n box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.25);\n opacity: 0;\n pointer-events: none;\n z-index: 2147483647;\n transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);\n }\n .${i}-toast.show {\n opacity: 1;\n transform: translateX(-50%) translateY(0);\n }\n .${i}-toast.success {\n background: var(--lsm-color-success, #5e9f7e);\n color: #ffffff;\n }\n .${i}-toast.error {\n background: var(--lsm-color-danger, #a64953);\n color: #ffffff;\n }\n .${i}-toast.info {\n background: var(--lsm-text-primary, #24231f);\n color: var(--lsm-bg-paper, #faf9f5);\n }\n\n `,a.appendChild(c);const l=document.createElement("div");l.id=`${i}-root`,l.className=`${i}-root`,setSafeInnerHTML(l,`\n \x3c!-- 悬浮球 --\x3e\n
\n ×\n \n \n \n \n
\n\n \x3c!-- 悬浮球快捷菜单 --\x3e\n \n\n \x3c!-- 主管理窗口 --\x3e\n \n\n \x3c!-- Toast --\x3e\n
\n `),a.appendChild(l);const d=a.getElementById(`${i}-ball`),p=a.getElementById(`${i}-window`),g=a.getElementById(`${i}-header`),m=a.getElementById(`${i}-menu-mask`),u=a.getElementById(`${i}-badge`),h=a.getElementById(`${i}-list`),b=a.getElementById(`${i}-save-dialog`),f=a.getElementById(`${i}-clear-dialog`),y=(a.getElementById(`${i}-btn-cancel-clear`),a.getElementById(`${i}-btn-confirm-clear`),a.getElementById(`${i}-input-name`)),x=a.getElementById(`${i}-preview-box`),v=a.getElementById(`${i}-toast`),$=a.getElementById(`${i}-qr-dialog`),w=a.getElementById(`${i}-qr-rec-name`),k=a.getElementById(`${i}-qr-rec-meta`),E=a.getElementById(`${i}-qr-canvas-wrap`),S=a.getElementById(`${i}-qr-canvas`),T=a.getElementById(`${i}-qr-overflow-box`),C=a.getElementById(`${i}-qr-overflow-desc`),L=a.getElementById(`${i}-btn-start-chunk-qr`),M=a.getElementById(`${i}-qr-chunk-player`),_=(a.getElementById(`${i}-qr-chunk-badge`),a.getElementById(`${i}-qr-chunk-idx-text`)),I=a.getElementById(`${i}-qr-chunk-bar-fill`),A=a.getElementById(`${i}-btn-chunk-prev`),B=a.getElementById(`${i}-btn-chunk-play-toggle`),G=a.getElementById(`${i}-chunk-play-icon`),z=a.getElementById(`${i}-btn-chunk-next`),H=a.getElementById(`${i}-btn-chunk-exit`),D=a.getElementById(`${i}-qr-tip`),P=a.getElementById(`${i}-btn-download-qr`),j=a.getElementById(`${i}-btn-copy-qr-data`),O=a.getElementById(`${i}-btn-close-qr`),N=a.getElementById(`${i}-btn-close-qr-bottom`),R=a.getElementById(`${i}-scan-dialog`),q=a.getElementById(`${i}-scan-view-main`),F=a.getElementById(`${i}-scan-view-result`),V=a.getElementById(`${i}-camera-video`),U=a.getElementById(`${i}-scan-chunk-hud`),W=a.getElementById(`${i}-scan-chunk-progress-text`),J=a.getElementById(`${i}-scan-chunk-bar-fill`),Y=a.getElementById(`${i}-scan-chunk-chips`),K=a.getElementById(`${i}-scan-frame`),X=a.getElementById(`${i}-camera-placeholder`),Q=a.getElementById(`${i}-camera-status-text`),Z=a.getElementById(`${i}-btn-start-camera`),ee=a.getElementById(`${i}-btn-choose-img`),te=a.getElementById(`${i}-btn-choose-json`),ne=a.getElementById(`${i}-file-scan-image`),oe=a.getElementById(`${i}-file-scan-json`),se=a.getElementById(`${i}-scan-hidden-canvas`),ie=a.getElementById(`${i}-btn-close-scan`),re=a.getElementById(`${i}-res-name`),ae=a.getElementById(`${i}-res-chips`),ce=a.getElementById(`${i}-res-meta`),le=a.getElementById(`${i}-res-domain-warning`),de=a.getElementById(`${i}-btn-scan-restore-now`),pe=a.getElementById(`${i}-btn-scan-save-db`),ge=a.getElementById(`${i}-btn-scan-retry`),me=a.getElementById(`${i}-status-cloud`),ue=a.getElementById(`${i}-dot-cloud`),he=a.getElementById(`${i}-status-cloud-text`),be=a.getElementById(`${i}-btn-sync-toolbar`),fe=a.getElementById(`${i}-sync-toolbar-icon`),ye=a.getElementById(`${i}-sync-dialog`),xe=a.getElementById(`${i}-btn-close-sync`),ve=a.getElementById(`${i}-sync-card-status-title`),$e=a.getElementById(`${i}-sync-card-badge`),we=a.getElementById(`${i}-sync-card-desc`),ke=a.getElementById(`${i}-sync-card-meta`),Ee=a.getElementById(`${i}-sync-input-token`),Se=a.getElementById(`${i}-btn-toggle-token-eye`),Te=a.getElementById(`${i}-sync-input-gist-id`),Ce=a.getElementById(`${i}-sync-input-idle`),Le=a.getElementById(`${i}-btn-search-gists`),Me=a.getElementById(`${i}-btn-test-token`),_e=a.getElementById(`${i}-btn-save-sync-config`),Ie=a.getElementById(`${i}-sync-switch-auto`),Ae=a.getElementById(`${i}-btn-sync-now-drawer`),Be=a.getElementById(`${i}-sync-drawer-icon`),Ge=a.getElementById(`${i}-btn-menu-cloud`),ze=a.getElementById(`${i}-btn-menu-sync-now`),He=a.getElementById(`${i}-btn-menu-theme`),De=a.getElementById(`${i}-btn-quick-theme`),Pe=a.getElementById(`${i}-theme-quick-menu`),je=a.getElementById(`${i}-theme-quick-list`),Oe=a.getElementById(`${i}-theme-quick-count`),Ne=a.getElementById(`${i}-btn-open-theme-settings`),Re=a.getElementById(`${i}-theme-dialog`),qe=a.getElementById(`${i}-btn-close-theme`),Fe=a.getElementById(`${i}-cur-theme-name`),Ve=a.getElementById(`${i}-cur-theme-badge`),Ue=a.getElementById(`${i}-cur-theme-desc`),We=a.getElementById(`${i}-cur-theme-swatches`),Je=a.getElementById(`${i}-theme-grid`),Ye=a.getElementById(`${i}-theme-count-text`),Ke=a.getElementById(`${i}-btn-export-theme`),Xe=a.getElementById(`${i}-btn-import-theme`),Qe=a.getElementById(`${i}-btn-edit-theme`),Ze=a.getElementById(`${i}-btn-create-theme`),et=a.getElementById(`${i}-btn-reset-default-theme`),tt=a.getElementById(`${i}-theme-editor-wrap`),nt=a.getElementById(`${i}-theme-editor-title`),ot=a.getElementById(`${i}-btn-cancel-theme-editor`),st=a.getElementById(`${i}-edit-theme-name`),it=a.getElementById(`${i}-edit-color-accent`),rt=a.getElementById(`${i}-edit-color-paper`),at=a.getElementById(`${i}-edit-color-header`),ct=a.getElementById(`${i}-btn-save-custom-theme`),lt=a.getElementById(`${i}-file-theme-json`),dt=a.getElementById(`${i}-btn-more`),pt=a.getElementById(`${i}-dropdown-menu`);function gt(){b&&b.classList.remove("open"),f&&f.classList.remove("open"),$&&$.classList.remove("open"),R&&R.classList.remove("open"),ye&&ye.classList.remove("open"),Re&&Re.classList.remove("open"),on()}let mt=null,ut=null;function ht(e,t="info"){v.textContent=e,v.className=`${i}-toast ${t} show`,ut&&clearTimeout(ut),ut=setTimeout(()=>{v.classList.remove("show")},3e3)}function bt(){return GM_getValue("lsm_ui_positions",{})}function ft(){try{const e=bt(),t=location.hostname,n=e[t]||{},o=document.documentElement.clientWidth||window.innerWidth,s=document.documentElement.clientHeight||window.innerHeight,i=d.getBoundingClientRect();i.width>0&&i.height>0&&(n.ball={fx:Math.round(i.left/o*1e4)/1e4,fy:Math.round(i.top/s*1e4)/1e4});const r=p.getBoundingClientRect();r.width>0&&r.height>0&&(n.win={fx:Math.round(r.left/o*1e4)/1e4,fy:Math.round(r.top/s*1e4)/1e4}),e[t]=n,GM_setValue("lsm_ui_positions",e)}catch{}}function yt(e,t,n){let o,s,r,a,c=!1,l=!1;const p=(n,d,p)=>{const g=p.tagName;if(["BUTTON","SELECT","TEXTAREA","INPUT"].includes(g))return!1;if(p.closest&&p.closest(`.${i}-ball-close`))return!1;c=!0,l=!1;const m=e.getBoundingClientRect();return o=n,s=d,r=m.left,a=m.top,t.classList.add("dragging"),!0},g=(t,n)=>{if(!c)return!1;const i=t-o,d=n-s;if((Math.abs(i)>3||Math.abs(d)>3)&&(l=!0),!l)return!1;let p=Math.max(0,Math.min(r+i,window.innerWidth-e.offsetWidth)),g=Math.max(0,Math.min(a+d,window.innerHeight-e.offsetHeight));return e.style.left=p+"px",e.style.top=g+"px",e.style.right="auto",e.style.bottom="auto",!0},m=()=>{if(c){if(c=!1,t.classList.remove("dragging"),l)if(e===d){const t=e.offsetLeft,n=e.offsetWidth||50,o=window.innerWidth,s=12,i=t+n/2{p(e.clientX,e.clientY,e.target)&&e.preventDefault()}),document.addEventListener("mousemove",e=>{g(e.clientX,e.clientY)}),document.addEventListener("mouseup",()=>{m()}),t.addEventListener("touchstart",e=>{if(1===e.touches.length){const t=e.touches[0];p(t.clientX,t.clientY,e.target)}},{passive:!0}),document.addEventListener("touchmove",e=>{if(c&&1===e.touches.length){const t=e.touches[0];g(t.clientX,t.clientY)&&(e.cancelable&&e.preventDefault(),e.stopPropagation())}},{passive:!1}),document.addEventListener("touchend",()=>{m()}),document.addEventListener("touchcancel",()=>{m()})}function xt(){return GM_getValue("lsm_active_"+location.hostname,"")}function vt(e){GM_setValue("lsm_active_"+location.hostname,e||"")}function $t(t){const s=DB.getRecords(),r=xt();s.length>0?(u.textContent=s.length>99?"99+":s.length,u.style.display="flex"):u.style.display="none";const c=String(void 0!==t?t:a.getElementById(`${i}-search-input`)?a.getElementById(`${i}-search-input`).value:"").trim().toLowerCase();let l=s;if(c&&(l=s.filter(t=>{const n=(t.name||"").toLowerCase().includes(c),o=e(t.createdAt||t.createTime||t.updatedAt).includes(c),s=(t.url||"").toLowerCase().includes(c);return n||o||s})),0===s.length)return void(h.innerHTML=`\n
\n \n \n \n
当前网站暂无已保存的快照信息
\n
点击上方“一键保存”即可快速备份
\n
\n `);if(0===l.length&&c)return void(h.innerHTML=`\n
\n \n \n \n \n
未找到匹配的快照记录
\n
可尝试更换关键词或点击清空搜索
\n
\n `);let d="";l.forEach(t=>{const o=t.summary?t.summary.cookieCount:"?",s=t.summary?t.summary.localCount:"?",a=t.summary?t.summary.sessionCount:"?",c=t.id===r;d+=`\n
\n
\n \n \n \n \n \n ${n(t.name)}\n ${c?`✓ 当前生效`:""}\n \n ${e(t.createdAt||t.createTime||t.updatedAt)}\n
\n
\n 🍪 Cookie: ${o}\n 💾 Local: ${s}\n 📦 Session: ${a}\n 🔒 ${t.cipherData&&t.cipherData.encrypted?"AES-GCM":"明文"}\n
\n ${t.url?``:""}\n
\n \n \n \n \n \n \n
\n
\n `}),h.innerHTML=d,h.querySelectorAll(".btn-restore").forEach(e=>{e.addEventListener("click",async()=>{const t=e.getAttribute("data-id"),n=e.getAttribute("data-url");try{ht("正在解密并恢复快照...","info");const e=await DB.getDecryptedSession(t),o=await SessionManager.restoreSession(e);CryptoEngine.wipeMemory(e),vt(t),$t(),ht(`恢复成功: Cookie ${o.cookieSuccessCount}个, Storage ${o.localCount+o.sessionCount}项`,"success"),setTimeout(()=>{const e=n&&n.startsWith("http")&&n!==location.href,t=e?n:location.href;isAutoReloadEnabled()?e?location.href=t:location.reload():confirm(e?`快照已恢复!\n检测到该记录保存自页面:\n${n}\n\n是否立即跳转/刷新至该页面以应用快照?`:"快照已恢复!是否立即刷新网页以应用快照?")&&(e?location.href=n:location.reload())},300)}catch(e){ht(`恢复失败: ${e.message}`,"error")}})}),h.querySelectorAll(".btn-qrcode").forEach(t=>{t.addEventListener("click",()=>{const o=t.getAttribute("data-id"),s=DB.getRecords().find(e=>e.id===o);s?function(t){if(!t)return;Gt(),Et=t,w.textContent=t.name||"未命名快照";const o=e(t.createdAt||t.createTime||t.updatedAt||Date.now()),s=t.summary?t.summary.cookieCount:0,i=t.summary?t.summary.localCount:0,r=t.summary?t.summary.sessionCount:0,a=t.summary&&t.summary.approxBytes?t.summary.approxBytes:0,c=a?(a/1024).toFixed(1):"-";k.innerHTML=`\n 创建时间: ${o} · \n 域名: ${n(t.domain||location.hostname)}
\n 凭据概览: Cookie ${s} 项, Local ${i} 项, Session ${r} 项 (${c} KB)\n `;const l={type:"LSM_SINGLE_EXPORT",version:"1.2.0",domain:t.domain||location.hostname,exportTime:Date.now(),record:t};St=JSON.stringify(l);const d=new Blob([St]).size,p=(d/1024).toFixed(1);if(d>2200)E&&(E.style.display="none"),T&&(T.style.display="flex"),C&&(C.innerHTML=`当前快照数据体积为 ${p} KB (${d} 字节),已超出标准单张二维码容纳极限(约 2.2 KB)。`),D&&(D.style.display="none"),P&&(P.disabled=!0,P.style.opacity="0.45",P.style.cursor="not-allowed",P.title="快照数据过大,无法生成单张二维码图片");else{let e=!1;try{_t(S,St,{size:220,margin:2,errorCorrectionLevel:"M",colorDark:"#0f172a",colorLight:"#ffffff"}),e=!0}catch(e){console.warn("二维码生成失败:",e)}e?(E&&(E.style.display="flex"),T&&(T.style.display="none"),D&&(D.style.display="block",D.textContent="使用另一台设备或快照助手的「扫码」功能即可一键导入与恢复"),P&&(P.disabled=!1,P.style.opacity="1",P.style.cursor="pointer",P.title="下载二维码 PNG 图片")):(E&&(E.style.display="none"),T&&(T.style.display="flex"),C&&(C.innerHTML=`当前快照数据体积为 ${p} KB,超出二维码容量限制。`),D&&(D.style.display="none"),P&&(P.disabled=!0,P.style.opacity="0.45",P.style.cursor="not-allowed",P.title="快照数据过大,无法生成二维码图片"))}$.classList.add("open")}(s):ht("未找到对应快照记录","error")})}),h.querySelectorAll(".btn-copy-single").forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-id"),n=DB.getRecords().find(e=>e.id===t);if(!n)return void ht("未找到对应快照记录","error");const o={type:"LSM_SINGLE_EXPORT",version:"1.2.0",domain:n.domain||location.hostname,exportTime:Date.now(),record:n};try{GM_setClipboard(JSON.stringify(o,null,2),"text"),ht(`快照「${n.name}」已复制至剪贴板!`,"success")}catch(e){ht(`复制失败: ${e.message}`,"error")}})}),h.querySelectorAll(".btn-export-single").forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-id"),n=DB.getRecords().find(e=>e.id===t);if(!n)return void ht("未找到对应记录","error");const s={type:"LSM_SINGLE_EXPORT",version:"1.2.0",domain:n.domain||location.hostname,exportTime:Date.now(),record:n},i=(n.name||"session").replace(/[\\/:*?"<>|]/g,"_");o(`${location.hostname}_${i}.json`,s),ht("单条记录已导出为 JSON","success")})}),h.querySelectorAll(".btn-rename").forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-id"),n=e.getAttribute("data-name"),o=prompt("请输入新的记录名称:",n);o&&o.trim()&&o.trim()!==n&&(DB.updateRecordName(t,o.trim()),$t(),ht("已重命名","success"))})}),h.querySelectorAll(".btn-delete").forEach(e=>{e.addEventListener("click",()=>{const t=e.getAttribute("data-id"),n=e.getAttribute("data-name");confirm(`确定要删除记录 [${n}] 吗?`)&&(DB.deleteRecord(t),xt()===t&&vt(""),$t(),ht("已删除记录","info"))})})}async function wt(){gt(),p&&(p.scrollTop=0),b&&(b.scrollTop=0),y.value=t(),x.innerHTML='正在扫描当前快照...',b.classList.add("open"),setTimeout(()=>{b&&b.classList.contains("open")&&y&&(y.focus({preventScroll:!0}),y.select())},50);try{const e=await SessionManager.captureCurrentSession();mt=e;const t=e.summary.approxBytes?(e.summary.approxBytes/1024).toFixed(1):"0",n=e.summary.approxBytes&&e.summary.approxBytes>1572864;x.innerHTML=`\n
\n
\n
🍪 Cookie
\n
${e.summary.cookieCount}
\n
\n
\n
💾 Local
\n
${e.summary.localCount}
\n
\n
\n
📦 Session
\n
${e.summary.sessionCount}
\n
\n
\n
\n 预估体积: ${t} KB\n ${n?'⚠️ 快照体积偏大 (>1.5MB)':'✓ 状态良好'}\n
\n `,p&&(p.scrollTop=0),b&&(b.scrollTop=0)}catch(e){x.innerHTML=`扫描异常: ${e.message}`,p&&(p.scrollTop=0)}}function kt(){b.classList.remove("open"),mt&&(CryptoEngine.wipeMemory(mt),mt=null)}let Et=null,St="",Tt=[],Ct=0,Lt=null,Mt=!0;function _t(e,t,n={}){const{margin:o=2,cellSize:s=4,colorDark:i="#0f172a",colorLight:r="#ffffff",errorCorrectionLevel:a="M"}=n,c="undefined"!=typeof qrcode?qrcode:"undefined"!=typeof window&&window.qrcode?window.qrcode:null;if(!c)throw new Error("QR 编码库 (qrcode-generator) 未成功加载,请检查网络或脚本 @require 声明");const l=c(0,a);l.addData(t),l.make();const d=l.getModuleCount(),p=n.size||220,g=Math.max(2,Math.floor(p/(d+2*o))),m=(d+2*o)*g;e.width=m,e.height=m;const u=e.getContext("2d");if(!u)throw new Error("无法初始化 Canvas 2D 绘图上下文");u.fillStyle=r,u.fillRect(0,0,m,m),u.fillStyle=i;for(let e=0;e{!Tt||Tt.length<=1||(Ct=(Ct+1)%Tt.length,At())},500)}function Gt(){Lt&&(clearInterval(Lt),Lt=null),Tt=[],Ct=0,Mt=!1,M&&(M.style.display="none")}function zt(){Gt(),$.classList.remove("open"),Et=null,St="",P&&(P.disabled=!1,P.style.opacity="1",P.style.cursor="pointer")}let Ht=null,Dt=null,Pt=null;const jt=new Map;function Ot(e){const{id:t,idx:n,total:o,data:s,name:r}=e;if(!t||"number"!=typeof n||!o||"string"!=typeof s)return;let a=jt.get(t);if(a||(a={id:t,total:o,name:r||"分片快照",chunks:new Array(o).fill(null),receivedCount:0,createdAt:Date.now()},jt.set(t,a)),U&&(U.style.display="flex"),null===a.chunks[n]&&(a.chunks[n]=s,a.receivedCount++,function(e){if(!W||!J||!Y)return;const t=Math.round(e.receivedCount/e.total*100);W.textContent=`${e.receivedCount} / ${e.total} (${t}%)`,J.style.width=`${t}%`;let n="";for(let t=0;t${t+1}`}Y.innerHTML=n}(a)),a.receivedCount===a.total){Nt(),U&&(U.style.display="none");const e=a.chunks.join("");jt.delete(t),ht(`所有分片 (${o}/${o}) 已完整接收,正在解析快照...`,"success"),Ut(e)}}function Nt(){if(Dt&&(cancelAnimationFrame(Dt),Dt=null),Ht){try{Ht.getTracks().forEach(e=>e.stop())}catch(e){}Ht=null}V&&(V.srcObject=null),K&&(K.style.display="none"),X&&(X.style.display="flex"),Z&&(Z.style.display="inline-flex"),Q&&(Q.textContent="未开启摄像头实时扫码")}function Rt(){if(Ht){if(V.readyState===V.HAVE_ENOUGH_DATA){const e=se||document.createElement("canvas");e.width=V.videoWidth,e.height=V.videoHeight;const t=e.getContext("2d",{willReadFrequently:!0});t.drawImage(V,0,0,e.width,e.height);const n=t.getImageData(0,0,e.width,e.height),o=It();if(o){const e=o(n.data,n.width,n.height,{inversionAttempts:"dontInvert"});if(e&&e.data){let t=null;try{const n=JSON.parse(e.data.trim());n&&"LSM_CHUNK"===n.type&&n.id&&"number"==typeof n.idx&&n.total&&"string"==typeof n.data&&(t=n)}catch(e){}if(!t)return Nt(),void Ut(e.data);Ot(t)}}}Dt=requestAnimationFrame(Rt)}}function qt(){Nt(),jt.clear(),U&&(U.style.display="none"),W&&(W.textContent="0 / 0 (0%)"),J&&(J.style.width="0%"),Y&&(Y.innerHTML=""),Pt=null,q.style.display="flex",F.style.display="none",ne&&(ne.value=""),oe&&(oe.value="")}function Ft(){qt(),R.classList.add("open")}function Vt(){Nt(),jt.clear(),U&&(U.style.display="none"),R.classList.remove("open"),Pt=null}function Ut(e){if(!e||"string"!=typeof e)return void ht("识别到的内容为空","error");let t;try{t=JSON.parse(e.trim())}catch{return void ht("二维码解析成功,但内容不是合法的 JSON 快照数据","error")}if(t&&"LSM_CHUNK"===t.type&&t.id&&"number"==typeof t.idx&&t.total&&"string"==typeof t.data){Ot(t);const e=jt.get(t.id);return void(e&&e.receivedCount{const t=new Image;t.onload=()=>{const e=se||document.createElement("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d",{willReadFrequently:!0});n.drawImage(t,0,0);const o=n.getImageData(0,0,e.width,e.height),s=It();if(!s)return void ht("jsQR 解码库未成功加载,请检查网络或脚本 @require 依赖","error");const i=s(o.data,o.width,o.height,{inversionAttempts:"attemptBoth"});i&&i.data?Ut(i.data):ht("未能从该图片中识别到有效二维码,请确认图片清晰","error")},t.onerror=()=>ht("图片加载失败","error"),t.src=e.target.result},t.onerror=()=>ht("读取文件失败","error"),t.readAsDataURL(e)}function Jt(t,o){let s=null,r=[],a=t.domain||"",c=o||"导入快照";if("LSM_SINGLE_EXPORT"===t.type&&t.record)s=t.record,r=[t.record],a=t.record.domain||a,c=t.record.name||c;else if("LSM_BATCH_EXPORT"===t.type&&Array.isArray(t.records)&&t.records.length>0)s=t.records[0],r=t.records,a=t.domain||s.domain||a,c=s.name?`${s.name} (等共 ${t.records.length} 条)`:c;else if(t.name&&t.cipherData)s=t,r=[t],a=t.domain||a,c=t.name;else if(Array.isArray(t)&&t.length>0&&t[0].cipherData)s=t[0],r=t,a=s.domain||a,c=s.name?`${s.name} (共 ${t.length} 条)`:c;else{if(!t.cookies&&!t.localStorage)return void ht("无法识别的快照数据格式","error");s={id:"rec_"+Date.now(),name:c,domain:t.domain||location.hostname,url:t.url||location.href,createdAt:Date.now(),createTime:Date.now(),summary:t.summary||{cookieCount:Array.isArray(t.cookies)?t.cookies.length:0,localCount:t.localStorage?Object.keys(t.localStorage).length:0,sessionCount:t.sessionStorage?Object.keys(t.sessionStorage).length:0},cipherData:{encrypted:!1,payload:JSON.stringify(t)}},r=[s],a=s.domain}Pt={json:t,targetRecord:s,recordsToImport:r,sourceDomain:a,name:c},re.textContent=c;const l=s.summary||{},d="number"==typeof l.cookieCount?l.cookieCount:"-",p="number"==typeof l.localCount?l.localCount:"-",g="number"==typeof l.sessionCount?l.sessionCount:"-",m=s.cipherData?s.cipherData.encrypted?"AES-GCM":"明文":"未知";ae.innerHTML=`\n 🍪 Cookie: ${d}\n 💾 Local: ${p}\n 📦 Session: ${g}\n 🔒 ${m}\n `;const u=s.createdAt||s.createTime||t&&(t.exportTime||t.createdAt||t.createTime),h=u?e(u):"未知时间";ce.textContent=`来源域名: ${a||location.hostname} · 创建于 ${h}`,a&&a!==location.hostname?(le.style.display="block",le.innerHTML=`⚠️ 域名不匹配提醒:该快照保存自 ${n(a)},而当前所在网页为 ${n(location.hostname)}。直接恢复可能会因域名隔离导致部分 Cookie 无法生效。`):le.style.display="none",q.style.display="none",F.style.display="flex",ht("快照解析成功,请选择操作","success")}function Yt(t,n){const o=GistSyncEngine.getToken(),s=GistSyncEngine.getGistId(),r=GistSyncEngine.getLastSyncTime(),a=r?e(r):"从未同步";return"syncing"===t?(ue&&(ue.className=`${i}-dot ${i}-dot-cloud syncing`),he&&(he.textContent="☁️ 云同步: 同步中..."),fe&&fe.classList.add("spinning"),Be&&Be.classList.add("spinning"),ve&&(ve.textContent="☁️ 正在与 GitHub Gist 同步..."),$e&&($e.textContent="同步中",$e.style.cssText="background:#dbeafe;color:#2563eb;"),we&&(we.textContent="正在双向传输与合并全域快照数据,请稍候..."),void(ke&&(ke.textContent=`上次同步: ${a}`))):(fe&&fe.classList.remove("spinning"),Be&&Be.classList.remove("spinning"),"error"===t?(ue&&(ue.className=`${i}-dot ${i}-dot-cloud err`),he&&(he.textContent="☁️ 云同步: 异常"),ve&&(ve.textContent="☁️ 云同步异常"),$e&&($e.textContent="连接失败",$e.style.cssText="background:#fee2e2;color:#991b1b;"),we&&(we.textContent=`错误原因: ${n||"网络连接超时或 Token 无效"}`),void(ke&&(ke.textContent=`上次同步: ${a}`))):void(o&&s?(ue&&(ue.className=`${i}-dot ${i}-dot-cloud ok`),he&&(he.textContent="☁️ 云同步: 已连接"),ve&&(ve.textContent="☁️ GitHub Gist 云同步就绪"),$e&&($e.textContent="已连接",$e.style.cssText="background:#dcfce7;color:#166534;"),we&&(we.textContent="已与 GitHub Gist 建立连接,支持双向智能增量合并与防抖自动同步。"),ke&&(ke.textContent=`上次同步: ${a}`)):o&&!s?(ue&&(ue.className=`${i}-dot ${i}-dot-cloud warn`),he&&(he.textContent="☁️ 云同步: 待绑定Gist"),ve&&(ve.textContent="☁️ Token 已就绪,请绑定 Gist"),$e&&($e.textContent="待绑定",$e.style.cssText="background:#fef3c7;color:#b45309;"),we&&(we.textContent="已输入 Token,请点击下方「🚀 自动创建 Gist」或手动填入已有 Gist ID。"),ke&&(ke.textContent=`上次同步: ${a}`)):(ue&&(ue.className=`${i}-dot ${i}-dot-cloud`),he&&(he.textContent="☁️ 云同步: 未配置"),ve&&(ve.textContent="☁️ 未配置云同步"),$e&&($e.textContent="未连接",$e.style.cssText="background:#f1f5f9;color:#64748b;"),we&&(we.textContent="配置 GitHub Token 和 Gist ID 后即可实现跨浏览器/多设备快照自动增量同步与安全备份。"),ke&&(ke.textContent=`上次同步: ${a}`))))}function Kt(){ye&&(gt(),p&&(p.scrollTop=0),ye&&(ye.scrollTop=0),Ee&&(Ee.value=GistSyncEngine.getToken()),Te&&(Te.value=GistSyncEngine.getGistId()),Ce&&(Ce.value=GistSyncEngine.getIdleMinutes()),Ie&&(Ie.checked=GistSyncEngine.isAutoSyncEnabled()),Yt(),ye.classList.add("open"))}function Xt(){ye&&ye.classList.remove("open")}function Qt(){if(!je)return;const e=ThemeEngine.getActiveTheme(),t=ThemeEngine.getAllThemes();Oe&&(Oe.textContent=`共 ${t.length} 款`),je.innerHTML=t.map(t=>{const o=t.id===e.id;return`\n
\n
\n \n \n \n \n ${n(t.name)}\n
\n ${o?'':""}\n
\n `}).join(""),je.querySelectorAll("[data-quick-theme-id]").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.getAttribute("data-quick-theme-id");if(n){const e=ThemeEngine.setActiveTheme(n);Qt(),Zt(),Pe&&Pe.classList.add("hidden"),ht(`已切换为主题: ${e.name}`,"success")}})})}function Zt(){const e=ThemeEngine.getActiveTheme(),t=ThemeEngine.getAllThemes();if(Fe&&(Fe.textContent=e.name),Ve&&(Ve.textContent=e.isBuiltin?"官方预设":"自定义",Ve.style.cssText=e.isBuiltin?"background:var(--lsm-accent-bg);color:var(--lsm-accent);border:1px solid var(--lsm-accent-border);":"background:var(--lsm-bg-warning);color:var(--lsm-color-warning);border:1px solid var(--lsm-border-warning);"),Ue&&(Ue.textContent=e.description||"暂无描述"),We){const t=[{label:"Accent",color:e.tokens.accent},{label:"Paper",color:e.tokens.bgPaper},{label:"Header",color:e.tokens.bgHeader},{label:"Success",color:e.tokens.colorSuccess},{label:"Warning",color:e.tokens.colorWarning},{label:"Info",color:e.tokens.colorInfo}];We.innerHTML=t.map(e=>`\n \n ${e.label}\n `).join("")}Ye&&(Ye.textContent=`共 ${t.length} 套`),Je&&(Je.innerHTML=t.map(t=>{const o=t.id===e.id,s=!!t.isBuiltin;return`\n
\n
\n
\n ${o?"✓ ":""}${n(t.name)}\n
\n ${s?`内置`:``}\n
\n
\n \n \n \n \n
\n
\n `}).join(""),Je.querySelectorAll(`.${i}-theme-item`).forEach(e=>{e.addEventListener("click",t=>{if(t.target.closest(".btn-del-theme")||t.target.classList.contains(`${i}-btn-del-theme`))return;const n=e.getAttribute("data-theme-id");if(n){const e=ThemeEngine.setActiveTheme(n);"edit"===nn&&sn("edit"),Zt(),ht(`已切换为主题: ${e.name}`,"success")}})}),Je.querySelectorAll(`.${i}-btn-del-theme`).forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation();const n=e.getAttribute("data-del-id");if(confirm("确定要删除此自定义主题吗?"))try{ThemeEngine.deleteCustomTheme(n),tt&&"none"!==tt.style.display&&on(),Zt(),Qt(),ht("已删除自定义主题","info")}catch(e){ht(e.message,"error")}})}))}function en(){gt(),Zt(),Re&&Re.classList.add("open")}function tn(e){const t=e.target.files&&e.target.files[0];if(!t)return;const n=new FileReader;n.onload=t=>{try{const e=ThemeEngine.importTheme(t.target.result);Zt(),Qt(),ht(`主题「${e.name}」导入成功并已应用!`,"success")}catch(e){ht(`导入失败: ${e.message}`,"error")}e.target&&(e.target.value="")},n.readAsText(t)}qe&&qe.addEventListener("click",function(){on(),Re&&Re.classList.remove("open")}),De&&De.addEventListener("click",e=>{e.stopPropagation(),Qt(),Pe&&Pe.classList.toggle("hidden"),pt&&pt.classList.add("hidden")}),Ne&&Ne.addEventListener("click",e=>{e.stopPropagation(),Pe&&Pe.classList.add("hidden"),en()}),He&&He.addEventListener("click",()=>{pt&&pt.classList.add("hidden"),en()}),Ke&&Ke.addEventListener("click",()=>{const e=ThemeEngine.getActiveTheme(),t=ThemeEngine.exportTheme(e.id);o(`${(e.name||"theme").replace(/[\\/:*?"<>|]/g,"_")}_theme.json`,JSON.parse(t));try{GM_setClipboard(t,"text"),ht(`主题「${e.name}」已导出文件并复制至剪贴板!`,"success")}catch(t){ht(`主题「${e.name}」已导出为 JSON 文件`,"success")}}),Xe&&Xe.addEventListener("click",()=>{let e=lt||a.getElementById(`${i}-file-theme-json`);e||(e=document.createElement("input"),e.type="file",e.id=`${i}-file-theme-json`,e.accept=".json,application/json",e.style.display="none",a.appendChild(e),e.addEventListener("change",tn)),e.value="",e.click()}),lt&<.addEventListener("change",tn),et&&et.addEventListener("click",()=>{on(),ThemeEngine.resetToDefault(),Zt(),Qt(),ht("已恢复为 Yohaku (余白) 默认主题","success")});let nn=null;function on(){nn=null,tt&&(tt.style.display="none"),Qe&&(Qe.classList.remove(`${i}-btn-primary`),Qe.classList.add(`${i}-btn-secondary`)),Ze&&(Ze.classList.remove(`${i}-btn-primary`),Ze.classList.add(`${i}-btn-secondary`))}function sn(e){if(nn===e&&tt&&"none"!==tt.style.display)return void on();nn=e,tt&&(tt.style.display="flex");const t=ThemeEngine.getActiveTheme(),n="edit"===e;Qe&&(n?(Qe.classList.add(`${i}-btn-primary`),Qe.classList.remove(`${i}-btn-secondary`)):(Qe.classList.remove(`${i}-btn-primary`),Qe.classList.add(`${i}-btn-secondary`))),Ze&&(n?(Ze.classList.remove(`${i}-btn-primary`),Ze.classList.add(`${i}-btn-secondary`)):(Ze.classList.add(`${i}-btn-primary`),Ze.classList.remove(`${i}-btn-secondary`))),nt&&(nt.textContent=n?"✏️ 修改当前主题配色":"➕ 新建自定义主题"),ct&&(ct.textContent=n?"💾 保存修改并应用":"💾 创建并立即应用"),n?st&&(st.value=t.name):st&&(st.value=t.isBuiltin?`${t.name} (定制)`:`${t.name} 副本`),it&&(it.value=t.tokens.accent&&t.tokens.accent.startsWith("#")?t.tokens.accent.slice(0,7):"#c56473"),rt&&(rt.value=t.tokens.bgPaper&&t.tokens.bgPaper.startsWith("#")?t.tokens.bgPaper.slice(0,7):"#faf9f5"),at&&(at.value=t.tokens.bgHeader&&t.tokens.bgHeader.startsWith("#")?t.tokens.bgHeader.slice(0,7):"#f0efeb"),setTimeout(()=>{try{tt.scrollIntoView({behavior:"smooth",block:"nearest"})}catch(e){}},40)}function rn(e,t){if(!e||"string"!=typeof e)return`rgba(197, 100, 115, ${t})`;let n=e.replace("#","").trim();if(3===n.length&&(n=n.split("").map(e=>e+e).join("")),n.length>=6){const e=parseInt(n.slice(0,2),16),o=parseInt(n.slice(2,4),16),s=parseInt(n.slice(4,6),16);if(!isNaN(e)&&!isNaN(o)&&!isNaN(s))return`rgba(${e}, ${o}, ${s}, ${t})`}return e}function an(){d&&(d.style.display="none",d.classList.add("hidden")),p&&(p.style.display="flex",p.classList.remove("hidden"),$t(),Yt(),void 0!==GistSyncEngine&&GistSyncEngine.checkSyncOnOpen&&GistSyncEngine.checkSyncOnOpen())}function cn(){p&&(p.style.display="none",p.classList.add("hidden")),d&&(d.style.display="flex",d.classList.remove("hidden")),kt(),zt(),Vt(),Xt()}Qe&&Qe.addEventListener("click",()=>sn("edit")),Ze&&Ze.addEventListener("click",()=>sn("create")),ot&&ot.addEventListener("click",on),ct&&ct.addEventListener("click",()=>{const e="edit"===nn,t=(st&&st.value?st.value.trim():"")||(e?"未命名主题":"自定义主题"),n=it&&it.value||"#c56473",o=rt&&rt.value||"#faf9f5",s=at&&at.value||"#f0efeb",i=ThemeEngine.getActiveTheme(),r=Object.assign({},i.tokens,{accent:n,accentBg:rn(n,.08),accentBorder:rn(n,.3),accentHoverBg:rn(n,.14),accentGlow:rn(n,.12),bgPaper:o,bgHeader:s,bgList:o,bgHover:s});let a;if(e&&!i.isBuiltin)a={type:ThemeEngine.SCHEMA_TYPE,version:ThemeEngine.SCHEMA_VERSION,id:i.id,name:t,description:i.description||`修改于 ${(new Date).toLocaleDateString()}`,isBuiltin:!1,tokens:r,createdAt:i.createdAt||Date.now(),updatedAt:Date.now()};else{const n="custom_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6);a={type:ThemeEngine.SCHEMA_TYPE,version:ThemeEngine.SCHEMA_VERSION,id:n,name:t,description:e?`基于官方预设「${i.name}」定制的主题`:`基于「${i.name}」新建的个性化主题`,isBuiltin:!1,tokens:r,createdAt:Date.now(),updatedAt:Date.now()}}try{const t=ThemeEngine.saveCustomTheme(a);Zt(),Qt(),on(),ht(e?`主题「${t.name}」修改已保存并生效!`:`新主题「${t.name}」已创建并应用!`,"success")}catch(e){ht(`保存失败: ${e.message}`,"error")}}),yt(d,d,()=>an()),yt(p,g),p.addEventListener("scroll",()=>{0!==p.scrollTop&&(p.scrollTop=0),0!==p.scrollLeft&&(p.scrollLeft=0)},{passive:!0}),bindScrollLock(p,`.${i}-content, .${i}-save-dialog, .${i}-clear-dialog, .${i}-qr-dialog, .${i}-scan-dialog, .${i}-sync-dialog, .${i}-sync-body, .${i}-theme-dialog, .${i}-theme-body`),bindScrollLock(m,null);const ln=a.querySelector(`.${i}-ball-close`);ln&&ln.addEventListener("click",e=>{e.stopPropagation(),m.classList.remove("hidden")}),m.addEventListener("click",e=>{e.target===m&&m.classList.add("hidden")}),m.querySelectorAll("button").forEach(e=>{e.addEventListener("click",()=>{m.classList.add("hidden");const t=e.getAttribute("data-a");"open"===t?an():"save"===t?(an(),wt()):"temp"===t?(d.style.display="none",p.style.display="none",p.classList.add("hidden")):"forever"===t&&(removeHostFromShowList(),d.style.display="none",p.style.display="none",p.classList.add("hidden"))})}),a.getElementById(`${i}-btn-close`).addEventListener("click",()=>cn()),a.getElementById(`${i}-btn-save-current`).addEventListener("click",()=>wt()),a.getElementById(`${i}-btn-clear-current`).addEventListener("click",async()=>{if(confirm(`确定要清空当前网站 (${location.hostname}) 的所有快照数据(Cookie、LocalStorage、SessionStorage)吗?\n清空后将处于未快照。`)){ht("正在清空当前网站数据...","info");try{const e=await SessionManager.clearAllData();vt(""),$t(),ht(`已清空 Cookie ${e.cookieCount}个, Storage ${e.storageCount}项`,"success"),setTimeout(()=>{confirm("当前网站快照数据已彻底清空!是否立即刷新网页以生效?")&&location.reload()},300)}catch(e){ht(`清空失败: ${e.message}`,"error")}}}),a.getElementById(`${i}-btn-reload`).addEventListener("click",()=>location.reload()),me&&me.addEventListener("click",()=>{Kt()}),be&&be.addEventListener("click",async()=>{const e=GistSyncEngine.getToken(),t=GistSyncEngine.getGistId();if(!e||!t)return Kt(),void ht("请先配置 GitHub Token 和 Gist ID","info");await GistSyncEngine.twoWaySync({silent:!1})}),xe&&xe.addEventListener("click",()=>Xt()),Se&&Ee&&Se.addEventListener("click",()=>{const e="password"===Ee.type;Ee.type=e?"text":"password",Se.textContent=e?"🙈":"👁️"}),Me&&Me.addEventListener("click",async()=>{const e=Ee?Ee.value.trim():"";if(e)try{ht("正在连接 GitHub API 验证 Token...","info"),Me.disabled=!0;const t=await GistSyncEngine.testConnection(e);ht(`Token 验证成功!账号: @${t.login} (${t.name})`,"success"),GistSyncEngine.setSyncConfig({token:e}),Yt()}catch(e){ht(`连接失败: ${e.message}`,"error"),Yt("error",e.message)}finally{Me.disabled=!1}else ht("请先输入 GitHub Token","error")}),Le&&Le.addEventListener("click",()=>{!async function(){if(document.querySelector(".lsm-gist-picker-mask"))return;ensureHostAnimationStyle();const t=((Ee?Ee.value.trim():"")||GistSyncEngine.getToken()).trim();if(!t)return ht("请先在上方输入有效的 GitHub Token","error"),void(Ee&&Ee.focus());ht("正在从 GitHub 获取 Gist 列表...","info");let o=[];try{o=await GistSyncEngine.listUserGists(t)}catch(e){return void ht(`获取 Gist 列表失败: ${e.message}`,"error")}const s=document.createElement("div");s.className="lsm-dlg-mask lsm-gist-picker-mask",s.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(s,null);const i=document.createElement("div");i.style.cssText="width:520px;max-width:calc(100vw - 32px);max-height:85vh;background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:20px 22px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;display:flex;flex-direction:column;gap:12px;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const r=document.createElement("div");r.style.cssText="display:flex;align-items:center;justify-content:space-between;gap:8px;",r.innerHTML=`\n
\n
\n \n \n \n 选择已有 Gist 进行绑定 (${o.length})\n
\n \n
\n \n `;const a=r.querySelector(".lsm-picker-close-btn");a.addEventListener("mouseenter",()=>a.style.color="#24231f"),a.addEventListener("mouseleave",()=>a.style.color="#787670");const c=r.querySelector(".lsm-picker-auto-create-btn");c.addEventListener("mouseenter",()=>{c.style.background="rgba(197,100,115,0.15)"}),c.addEventListener("mouseleave",()=>{c.style.background="rgba(197,100,115,0.08)"});const l=document.createElement("input");l.type="text",l.placeholder="🔍 实时搜索 Gist 描述、文件名或 ID...",l.style.cssText="width:100%;box-sizing:border-box;padding:8px 12px;font-size:12.5px;border:1px solid #e3e1db;border-radius:8px;outline:none;background:#ffffff;background-image:linear-gradient(180deg,rgba(197,100,115,0.03) 0%,transparent 26%);color:#24231f;transition:border-color .2s,box-shadow .2s;",l.addEventListener("focus",()=>{l.style.borderColor="rgba(197,100,115,0.35)",l.style.boxShadow="0 0 0 3px rgba(197,100,115,0.1)"}),l.addEventListener("blur",()=>{l.style.borderColor="#e3e1db",l.style.boxShadow="none"});const d=document.createElement("div");d.style.cssText="flex:1;overflow-y:auto;max-height:50vh;display:flex;flex-direction:column;gap:8px;padding-right:2px;",bindScrollLock(d,null);const p=()=>s.remove();a.addEventListener("click",p);const g=async()=>{try{ht("正在 GitHub 创建 Secret Gist...","info"),c&&(c.disabled=!0);const e=await GistSyncEngine.createGist(t);Te&&(Te.value=e.gistId),GistSyncEngine.setSyncConfig({token:t,gistId:e.gistId}),ht("Gist 创建并绑定成功!","success"),Yt(),p()}catch(e){ht(`创建 Gist 失败: ${e.message}`,"error")}finally{c&&(c.disabled=!1)}};function m(s=""){d.innerHTML="";const i=s.toLowerCase().trim();if(!o.length){const e=document.createElement("div");e.style.cssText="text-align:center;padding:32px 16px;color:#787670;font-size:12.5px;display:flex;flex-direction:column;align-items:center;gap:12px;",e.innerHTML='\n
当前 GitHub 账号下暂无任何 Gist 记录
\n \n ';const t=e.querySelector(".lsm-empty-create-btn");return t.addEventListener("mouseenter",()=>t.style.background="#b55362"),t.addEventListener("mouseleave",()=>t.style.background="#c56473"),t.addEventListener("click",g),void d.appendChild(e)}const r=o.filter(e=>!i||(e.description||"").toLowerCase().includes(i)||e.id.toLowerCase().includes(i)||e.files.some(e=>e.toLowerCase().includes(i)));if(!r.length){const e=document.createElement("div");e.style.cssText="text-align:center;padding:24px 16px;color:#787670;font-size:12px;display:flex;flex-direction:column;align-items:center;gap:10px;",e.innerHTML='\n
未匹配到符合条件的 Gist
\n \n ';const t=e.querySelector(".lsm-empty-create-btn");return t.addEventListener("mouseenter",()=>t.style.background="rgba(197,100,115,0.15)"),t.addEventListener("mouseleave",()=>t.style.background="rgba(197,100,115,0.08)"),t.addEventListener("click",g),void d.appendChild(e)}r.sort((e,t)=>(t.isSnapshotGist?1:0)-(e.isSnapshotGist?1:0));for(const o of r){const s=document.createElement("div"),i=!!o.isSnapshotGist;s.style.cssText="border:1px solid "+(i?"rgba(197,100,115,0.25)":"#e3e1db")+";background:"+(i?"rgba(197,100,115,0.04)":"#ffffff")+";border-radius:10px;padding:10px 12px;cursor:pointer;transition:all 0.2s cubic-bezier(0.22,1,0.36,1);display:flex;flex-direction:column;gap:4px;",s.addEventListener("mouseenter",()=>{s.style.borderColor="#c56473",s.style.transform="translateY(-1px)",s.style.boxShadow="0 4px 14px rgba(197,100,115,0.12)"}),s.addEventListener("mouseleave",()=>{s.style.borderColor=i?"rgba(197,100,115,0.25)":"#e3e1db",s.style.transform="none",s.style.boxShadow="none"});const r=o.files.slice(0,3).join(", ")+(o.files.length>3?` 等 ${o.files.length} 个文件`:""),a=o.updatedAt?e(new Date(o.updatedAt).getTime()):"-";s.innerHTML=`\n
\n
\n ${i?"🌸 ":""}${n(o.description||"(未命名 Gist)")}\n
\n \n ${o.isPublic?"Public":"Secret"}\n \n
\n ${i?`
✨ 包含快照备份文件 (${GistSyncEngine.GIST_FILENAME})
`:""}\n
\n 包含文件: ${n(r||"无")}\n 更新于: ${a}\n
\n
ID: ${o.id}
\n `,s.addEventListener("click",()=>{Te&&(Te.value=o.id),GistSyncEngine.setSyncConfig({token:t,gistId:o.id}),Yt(),ht(`已选择并绑定 Gist: ${o.description||o.id}`,"success"),p()}),d.appendChild(s)}}c.addEventListener("click",g),l.addEventListener("input",e=>m(e.target.value)),s.addEventListener("click",e=>{e.target===s&&p()}),m(""),i.appendChild(r),i.appendChild(l),i.appendChild(d),s.appendChild(i),document.documentElement.appendChild(s),setTimeout(()=>l.focus(),50)}()}),_e&&_e.addEventListener("click",()=>{const e=Ee?Ee.value.trim():"",t=Te?Te.value.trim():"",n=!!Ie&&Ie.checked,o=Ce?Number(Ce.value.trim()):5;GistSyncEngine.setSyncConfig({token:e,gistId:t,autoSync:n,idleMinutes:!isNaN(o)&&o>0?Math.floor(o):5}),Yt(),ht("云同步配置已保存!","success")}),Ie&&Ie.addEventListener("change",e=>{const t=e.target.checked;GistSyncEngine.setSyncConfig({autoSync:t});const n=GistSyncEngine.getIdleMinutes();ht(t?`已开启自动同步 (空闲 ${n} 分钟触发)`:"已关闭快照自动同步","info")}),Ae&&Ae.addEventListener("click",async()=>{const e=Ee?Ee.value.trim():"",t=Te?Te.value.trim():"";e&&t?(GistSyncEngine.setSyncConfig({token:e,gistId:t}),await GistSyncEngine.twoWaySync({silent:!1})):ht("请先填写并保存 Token 与 Gist ID","error")}),Ge&&Ge.addEventListener("click",()=>{pt.classList.add("hidden"),Kt()}),ze&&ze.addEventListener("click",async()=>{pt.classList.add("hidden"),await GistSyncEngine.twoWaySync({silent:!1})});const dn=a.getElementById(`${i}-search-input`),pn=a.getElementById(`${i}-search-clear`);dn.addEventListener("input",()=>{const e=dn.value;pn.classList.toggle("hidden",!e),$t(e)}),pn.addEventListener("click",()=>{dn.value="",pn.classList.add("hidden"),dn.focus(),$t("")}),dt&&dt.addEventListener("click",e=>{e.stopPropagation(),pt.classList.toggle("hidden")}),l.addEventListener("click",e=>{!Pe||Pe.classList.contains("hidden")||!De||De.contains(e.target)||Pe.contains(e.target)||Pe.classList.add("hidden"),pt.classList.contains("hidden")||dt.contains(e.target)||pt.classList.add("hidden")}),a.getElementById(`${i}-btn-export-all`).addEventListener("click",()=>{pt.classList.add("hidden");const e=DB.getRecords();if(!e.length)return void ht("当前网站暂无可导出的记录","info");const t={type:"LSM_BATCH_EXPORT",version:"1.0",domain:location.hostname,exportTime:Date.now(),count:e.length,records:e};o(`${location.hostname}_all_sessions.json`,t),ht(`成功导出 ${e.length} 条记录`,"success")});const gn=a.getElementById(`${i}-file-import`);async function mn(e,t){let n=null,o="",s=t||"",i=e.domain||"";if("LSM_SINGLE_EXPORT"===e.type&&e.record)n=e.record.cipherData,o=e.record.url||"",s=e.record.name||s,i=e.record.domain||i;else if("LSM_BATCH_EXPORT"===e.type&&Array.isArray(e.records)&&e.records.length>0)n=e.records[0].cipherData,o=e.records[0].url||"",s=e.records[0].name||s,i=e.records[0].domain||i;else if(e.name&&e.cipherData)n=e.cipherData,o=e.url||"",s=e.name||s,i=e.domain||i;else{if(!e.cookies&&!e.localStorage)throw new Error("无法识别的快照数据格式");n={encrypted:!1,payload:JSON.stringify(e)},o=e.url||"",i=e.domain||i}if(!n)throw new Error("快照数据中缺少有效凭据");if(i&&i!==location.hostname&&!confirm(`⚠️ 域名不匹配提示:\n\n该快照来源网站为:[${i}]\n而当前所在网站为:[${location.hostname}]\n\n跨网站恢复可能导致当前网站无法识别该快照。是否仍要继续恢复?`))return void ht("已取消恢复","info");ht("正在解密并恢复快照...","info");const r=i||location.hostname,a=await CryptoEngine.decrypt(n,r),c=await SessionManager.restoreSession(a);CryptoEngine.wipeMemory(a),vt(""),$t(),ht(`恢复成功: Cookie ${c.cookieSuccessCount}个, Storage ${c.localCount+c.sessionCount}项`,"success"),setTimeout(()=>{const e=o&&o.startsWith("http")&&o!==location.href,t=e?o:location.href;isAutoReloadEnabled()?e?location.href=t:location.reload():confirm(e?`快照 [${s||"已选择"}] 已恢复!\n检测到该记录保存自页面:\n${o}\n\n是否立即跳转/刷新至该页面以应用快照?`:`快照 [${s||"已选择"}] 已恢复!是否立即刷新网页以应用快照?`)&&(e?location.href=o:location.reload())},300)}a.getElementById(`${i}-btn-import-all`).addEventListener("click",()=>{pt.classList.add("hidden"),gn.value="",gn.click()}),gn.addEventListener("change",async e=>{const t=e.target.files&&e.target.files[0];if(t)try{ht("正在读取导入文件...","info");const e=await s(t);let n=[],o=e.domain||"";if("LSM_BATCH_EXPORT"===e.type&&Array.isArray(e.records))n=e.records;else if("LSM_SINGLE_EXPORT"===e.type&&e.record)n=[e.record],o=e.record.domain||o;else if(Array.isArray(e))n=e;else{if(!e.name||!e.cipherData)throw new Error("无法识别的备份文件结构");n=[e],o=e.domain||o}if(o&&o!==location.hostname&&!confirm(`⚠️ 域名不匹配提示:\n\n该备份文件来源网站为:[${o}]\n而当前所在网站为:[${location.hostname}]\n\n跨网站导入可能导致快照无法生效或无法直接解密。是否仍要继续导入到当前网站?`))return void ht("已取消导入","info");const{count:i,skipped:r}=DB.importRecords(n);$t(),0===i&&r>0?ht(`检测到 ${r} 条快照数据已存在,已全部自动跳过`,"info"):ht(r>0?`成功导入 ${i} 条快照,已自动跳过 ${r} 条重复记录`:`成功导入 ${i} 条快照记录!`,"success")}catch(e){ht(`导入失败: ${e.message}`,"error")}});const un=a.getElementById(`${i}-file-restore-direct`);a.getElementById(`${i}-btn-restore-file`).addEventListener("click",()=>{pt.classList.add("hidden"),un.value="",un.click()}),un.addEventListener("change",async e=>{const t=e.target.files&&e.target.files[0];if(t)try{ht("正在解析备份文件...","info");const e=await s(t);await mn(e,t.name)}catch(e){ht(`恢复失败: ${e.message}`,"error")}}),a.getElementById(`${i}-btn-restore-clipboard`).addEventListener("click",async()=>{pt.classList.add("hidden");try{let e,t="";try{t=await navigator.clipboard.readText()}catch{t=prompt("请在此粘贴快照 JSON 数据:")||""}if(!t||!t.trim())return void ht("未获取到剪贴板文本,请先复制快照数据","info");try{e=JSON.parse(t.trim())}catch{throw new Error("剪贴板内容不是合法的 JSON 快照数据")}await mn(e,"剪贴板快照")}catch(e){ht(`剪贴板恢复失败: ${e.message}`,"error")}}),window.addEventListener("paste",async e=>{if(p.classList.contains("hidden")||"none"===p.style.display)return;const t=a.activeElement||document.activeElement;t&&t.id;let n="";if(e.clipboardData&&(n=e.clipboardData.getData("text")),!n||"string"!=typeof n)return;const o=n.trim();if(o.startsWith("{")&&o.endsWith("}"))try{const t=JSON.parse(o);if(!("LSM_SINGLE_EXPORT"===t.type&&t.record||"LSM_BATCH_EXPORT"===t.type&&Array.isArray(t.records)&&t.records.length>0||t.name&&t.cipherData||t.cipherData&&t.cipherData.ciphertext||t.summary&&(t.cookies||t.localStorage)))return;e.preventDefault(),e.stopPropagation();const n=t.record&&t.record.name||t.name||t.records&&t.records[0]&&t.records[0].name||"剪贴板快照",s=t.domain||t.record&&t.record.domain||"",i=s&&s!==location.hostname?`\n(⚠️ 来源域名: ${s},当前域名: ${location.hostname})`:"";confirm(`📋 检测到您在管理面板中粘贴了快照数据 [${n}]!${i}\n\n是否立即解密并恢复此快照到当前网站?`)&&await mn(t,n)}catch(e){}},!0);const hn=a.getElementById(`${i}-btn-confirm-save`);a.getElementById(`${i}-btn-cancel-save`).addEventListener("click",()=>kt()),hn.addEventListener("click",async()=>{const e=y.value.trim()||t();if(mt)try{const t=await DB.addRecord(e,mt);mt=null,t&&t.id&&vt(t.id),kt(),$t(),ht("快照信息已安全加密保存!","success")}catch(e){ht(`保存失败: ${e.message}`,"error")}else ht("未检测到有效数据,请重新打开","error")}),window.addEventListener("keydown",e=>{if(!p.classList.contains("hidden")&&"none"!==p.style.display)if("Escape"===e.key){if($&&$.classList.contains("open"))return e.preventDefault(),e.stopPropagation(),void zt();if(R&&R.classList.contains("open"))return e.preventDefault(),e.stopPropagation(),void Vt();if(b&&b.classList.contains("open"))return e.preventDefault(),e.stopPropagation(),void kt()}else if("Enter"===e.key&&b&&b.classList.contains("open"))return e.preventDefault(),e.stopPropagation(),void hn.click()},!0);const bn=a.getElementById(`${i}-btn-open-scan`);bn&&bn.addEventListener("click",()=>Ft());const fn=a.getElementById(`${i}-btn-menu-scan`);fn&&fn.addEventListener("click",()=>{pt.classList.add("hidden"),Ft()}),O&&O.addEventListener("click",()=>zt()),N&&N.addEventListener("click",()=>zt()),L&&L.addEventListener("click",()=>{Et&&St&&(Tt=function(e,t){const n=1200,o=Math.max(1,Math.ceil(t.length/n)),s="chk_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6),i=[];for(let r=0;r{Mt?(Mt=!1,Lt&&(clearInterval(Lt),Lt=null),G&&(G.textContent="▶ 继续")):(Mt=!0,G&&(G.textContent="⏸ 暂停"),Bt())}),A&&A.addEventListener("click",()=>{Tt&&0!==Tt.length&&(Ct=(Ct-1+Tt.length)%Tt.length,At())}),z&&z.addEventListener("click",()=>{Tt&&0!==Tt.length&&(Ct=(Ct+1)%Tt.length,At())}),H&&H.addEventListener("click",()=>(Gt(),E&&(E.style.display="none"),T&&(T.style.display="flex"),void(D&&(D.style.display="none")))),P&&P.addEventListener("click",()=>{if(P.disabled)ht("快照数据过大无法生成二维码图片,请使用「复制数据」或「导出文件」","error");else if(S)try{const e=S.toDataURL("image/png"),t=document.createElement("a"),n=(Et&&Et.name?Et.name:"snapshot").replace(/[\\/:*?"<>|]/g,"_");t.href=e,t.download=`${location.hostname}_${n}_qr.png`,t.click(),ht("二维码图片已开始下载","success")}catch(e){ht(`二维码图片下载失败: ${e.message}`,"error")}}),j&&j.addEventListener("click",()=>{if(St)try{"function"==typeof GM_setClipboard?GM_setClipboard(St,"text"):navigator.clipboard&&navigator.clipboard.writeText&&navigator.clipboard.writeText(St).catch(()=>{}),ht("快照 JSON 数据已复制到剪贴板!","success")}catch(e){ht(`复制失败: ${e.message}`,"error")}else ht("暂无可复制的二维码数据","info")}),ie&&ie.addEventListener("click",()=>Vt()),Z&&Z.addEventListener("click",()=>async function(){if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)try{Q.textContent="正在请求摄像头权限...",Z.style.display="none";const e=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1280},height:{ideal:720}}});Ht=e,V.srcObject=e,V.setAttribute("playsinline","true"),await V.play(),X.style.display="none",K.style.display="block",Q.textContent="正在实时扫码中,请对准二维码...",Rt()}catch(e){console.error("启动摄像头失败:",e),Nt(),Q.textContent="无法访问摄像头: "+(e.message||"用户拒绝或设备不可用"),ht("无法访问摄像头: "+(e.message||"权限被拒绝"),"error")}else ht("当前环境或浏览器不支持访问摄像头","error")}()),ee&&ne&&ee.addEventListener("click",()=>{ne.value="",ne.click()}),ne&&ne.addEventListener("change",e=>{const t=e.target.files&&e.target.files[0];t&&Wt(t)}),te&&oe&&te.addEventListener("click",()=>{oe.value="",oe.click()}),oe&&oe.addEventListener("change",async e=>{const t=e.target.files&&e.target.files[0];if(t)try{ht("正在读取 JSON 快照文件...","info"),Jt(await s(t),t.name)}catch(e){ht(`读取失败: ${e.message}`,"error")}}),q&&(q.addEventListener("dragover",e=>{e.preventDefault(),e.stopPropagation()}),q.addEventListener("drop",async e=>{e.preventDefault(),e.stopPropagation();const t=e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files[0];if(t)if(t.type.startsWith("image/"))Wt(t);else if(t.name.endsWith(".json")||t.type.includes("json"))try{ht("正在读取 JSON 快照文件...","info"),Jt(await s(t),t.name)}catch(e){ht(`读取失败: ${e.message}`,"error")}else ht("请拖入图片二维码截图或 .json 快照文件","error")})),de&&de.addEventListener("click",async()=>{if(!Pt||!Pt.json)return void ht("无可恢复的快照数据","error");const e=Pt.json,t=Pt.name;try{Vt(),await mn(e,t)}catch(e){ht(`恢复失败: ${e.message}`,"error")}}),pe&&pe.addEventListener("click",()=>{if(!Pt||!Pt.recordsToImport)return void ht("无可保存的快照数据","error");const e=Pt.recordsToImport;try{const{count:t,skipped:n}=DB.importRecords(e);$t(),Vt(),0===t&&n>0?ht(`检测到 ${n} 条快照数据已存在,已全部跳过`,"info"):ht(n>0?`成功导入 ${t} 条快照,跳过 ${n} 条重复记录`:`成功导入并保存 ${t} 条快照记录!`,"success")}catch(e){ht(`保存失败: ${e.message}`,"error")}}),ge&&ge.addEventListener("click",()=>{qt()}),function(){try{const e=bt()[location.hostname];if(!e)return;const t=document.documentElement.clientWidth||window.innerWidth,n=document.documentElement.clientHeight||window.innerHeight,o=d.offsetWidth||50,s=d.offsetHeight||50;if(e.ball){let i=e.ball.fx,r=e.ball.fy;"number"==typeof i&&"number"==typeof r||(i=Math.max(0,e.ball.x||0)/t,r=Math.max(0,e.ball.y||0)/n);const a=Math.max(10,Math.min(t-o-10,i*t)),c=Math.max(10,Math.min(n-s-10,r*n));d.style.left=a+"px",d.style.top=c+"px",d.style.right="auto",d.style.bottom="auto"}const i=p.offsetWidth||480,r=p.offsetHeight||520;if(e.win){let o=e.win.fx,s=e.win.fy;"number"==typeof o&&"number"==typeof s||(o=Math.max(0,e.win.x||0)/t,s=Math.max(0,e.win.y||0)/n);const a=Math.max(10,Math.min(Math.max(10,t-i-10),o*t)),c=Math.max(10,Math.min(Math.max(10,n-r-10),s*n));p.style.left=a+"px",p.style.top=c+"px",p.style.right="auto",p.style.bottom="auto"}}catch{}}(),$t(),window.addEventListener("resize",()=>{try{if(d&&"none"!==d.style.display&&!d.classList.contains("hidden")){const e=d.getBoundingClientRect(),t=document.documentElement.clientWidth||window.innerWidth,n=document.documentElement.clientHeight||window.innerHeight,o=bt()[location.hostname],s=o&&"number"==typeof o.ball.fx?o.ball.fx:e.left/t,i=o&&"number"==typeof o.ball.fy?o.ball.fy:e.top/n;d.style.left=Math.max(10,Math.min(t-(d.offsetWidth||50)-10,s*t))+"px",d.style.top=Math.max(10,Math.min(n-(d.offsetHeight||50)-10,i*n))+"px"}if(p&&"none"!==p.style.display&&!p.classList.contains("hidden")){const e=p.getBoundingClientRect(),t=document.documentElement.clientWidth||window.innerWidth,n=document.documentElement.clientHeight||window.innerHeight,o=bt()[location.hostname],s=o&&"number"==typeof o.win.fx?o.win.fx:e.left/t,i=o&&"number"==typeof o.win.fy?o.win.fy:e.top/n;p.style.left=Math.max(10,Math.min(Math.max(10,t-(p.offsetWidth||480)-10),s*t))+"px",p.style.top=Math.max(10,Math.min(Math.max(10,n-(p.offsetHeight||520)-10),i*n))+"px"}}catch{}});const yn=()=>{if(b&&b.classList.contains("open")&&y){const e=y.value;!e.startsWith("快照_")&&e||(y.value=t())}};if(window.addEventListener("popstate",yn),window.addEventListener("hashchange",yn),!window.__LSM_HISTORY_HOOKED__){window.__LSM_HISTORY_HOOKED__=!0;const e=history.pushState;"function"==typeof e&&(history.pushState=function(...t){const n=e.apply(this,t);return yn(),n});const t=history.replaceState;"function"==typeof t&&(history.replaceState=function(...e){const n=t.apply(this,e);return yn(),n})}LSM_UI={ball:d,win:p,openWindow:an,openThemeDialog:en,closeWindow:cn,openCloudSyncDialog:Kt,closeCloudSyncDialog:Xt,isInUse:()=>{try{if(p&&"none"!==p.style.display&&!p.classList.contains("hidden"))return!0;if(document.querySelector(".lsm-dlg-mask, .lsm-gist-picker-mask, .lsm-conflict-mask, .lsm-diff-mask, .lsm-qrcode-preview-mask"))return!0;if(a&&a.querySelector(".open"))return!0}catch{}return!1}},void 0!==GistSyncEngine&&(GistSyncEngine.initActivityListeners(a),GistSyncEngine.isAutoSyncEnabled()&&GistSyncEngine.startIdleSyncMonitor())}function getFilterMode(){let e=GM_getValue("Config.filter_mode","whitelist");Array.isArray(e)&&(e=e[0]);const t=String(e||"").match(/[a-zA-Z]+/);return"blacklist"===(t?t[0].toLowerCase():"whitelist")?"blacklist":"whitelist"}function getHostRules(){let e=GM_getValue("Config.host_list",null);return null==e&&(e=GM_getValue("Config.show_host","")),String(e||"").split("\n").map(e=>e.trim()).filter(Boolean)}function isHostMatched(){const e=getHostRules();if(!e.length)return!1;const t=[location.href,location.origin,location.protocol+"//"+location.host,location.host,location.hostname];return e.some(e=>{const n=new RegExp(e?"^"+e.replace(/[.+?^${}()|[\\]\\]/g,"\\$&").replace(/\\*/g,".*")+"$":"^$","i");return t.some(e=>n.test(e))})}function hostBlocked(){try{const e=getFilterMode(),t=isHostMatched(),n=getHostRules();return"blacklist"===e?t:!n.length||!t}catch(e){return!0}}function enableCurrentHost(){try{const e=getFilterMode();let t=GM_getValue("Config.host_list",null);null==t&&(t=GM_getValue("Config.show_host",""));let n=String(t||"").split("\n").map(e=>e.trim()).filter(Boolean);const o=[location.href,location.origin,location.protocol+"//"+location.host,location.host,location.hostname];if("blacklist"===e)n=n.filter(e=>{const t=new RegExp("^"+e.replace(/[.+?^${}()|[\\]\\]/g,"\\$&").replace(/\\*/g,".*")+"$","i");return!o.some(e=>t.test(e))});else{const e=location.origin;n.some(t=>t===e)||n.push(e)}GM_setValue("Config.host_list",n.join("\n"))}catch(e){console.error("[LSM] 写入配置失败:",e)}}const addHostToShowList=enableCurrentHost;function disableCurrentHost(){try{const e=getFilterMode();let t=GM_getValue("Config.host_list",null);null==t&&(t=GM_getValue("Config.show_host",""));let n=String(t||"").split("\n").map(e=>e.trim()).filter(Boolean);const o=[location.href,location.origin,location.protocol+"//"+location.host,location.host,location.hostname];if("blacklist"===e){const e=location.origin;n.some(t=>t===e)||n.push(e)}else n=n.filter(e=>{const t=new RegExp("^"+e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$","i");return!o.some(e=>t.test(e))});GM_setValue("Config.host_list",n.join("\n"))}catch(e){console.error("[LSM] 移除配置失败:",e)}}const removeHostFromShowList=disableCurrentHost;function bindScrollLock(e,t){let n=0;function o(n){let o=n;for(;o&&o!==e&&o!==document.documentElement&&o!==document.body;){if(o.scrollHeight>o.clientHeight){const e=window.getComputedStyle?window.getComputedStyle(o):null;if(e){const t=e.overflowY;if("auto"===t||"scroll"===t||"overlay"===t)return o}}if(t&&o.matches&&o.matches(t)&&o.scrollHeight>o.clientHeight)return o;o=o.parentElement||(o.getRootNode?o.getRootNode().host:null)}return t&&n.closest?n.closest(t):null}e.addEventListener("wheel",e=>{e.stopPropagation();const t=o(e.target);if(!t)return void e.preventDefault();const{scrollTop:n,scrollHeight:s,clientHeight:i}=t,r=e.deltaY;(s<=i||r<0&&n<=0||r>0&&n+i>=s-1)&&e.preventDefault()},{passive:!1}),e.addEventListener("touchstart",e=>{1===e.touches.length&&(n=e.touches[0].clientY)},{passive:!0}),e.addEventListener("touchmove",e=>{if(1!==e.touches.length)return;const t=o(e.target);if(!t)return e.cancelable&&e.preventDefault(),void e.stopPropagation();const s=e.touches[0].clientY-n,{scrollTop:i,scrollHeight:r,clientHeight:a}=t;if(r<=a)return e.cancelable&&e.preventDefault(),void e.stopPropagation();s>0&&i<=0||s<0&&i+a>=r-1?(e.cancelable&&e.preventDefault(),e.stopPropagation()):e.stopPropagation()},{passive:!1})}function ensureHostAnimationStyle(){if(!document.getElementById("lsm-host-animations")){const e=document.createElement("style");e.id="lsm-host-animations",e.textContent="@keyframes lsmFadeIn{from{opacity:0;transform:scale(0.96)}to{opacity:1;transform:scale(1)}}",(document.head||document.documentElement).appendChild(e)}}function showBlockedDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();const e=document.createElement("div");e.className="lsm-dlg-mask",e.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(e,null);const t=document.createElement("div");t.style.cssText="width:360px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const n=document.createElement("div");n.innerHTML="🔑 快照管理助手未激活",n.style.cssText="margin-bottom:10px;display:flex;align-items:center;gap:6px;";const o=getFilterMode(),s=document.createElement("div");s.textContent="blacklist"===o?"当前网站已被加入「黑名单」列表中,快照助手未在此站点激活。你可以选择:":"当前网站不在「白名单」列表中,快照助手未在此站点激活。你可以选择:",s.style.cssText="font-size:13px;color:#5c5a55;line-height:1.6;margin-bottom:18px;";const i=document.createElement("button");i.textContent="临时显示(仅本次生效)",i.style.cssText="display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid rgba(197,100,115,0.3);border-radius:10px;background:rgba(197,100,115,0.08);color:#c56473;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",i.addEventListener("mouseenter",()=>{i.style.background="rgba(197,100,115,0.14)",i.style.borderColor="rgba(197,100,115,0.45)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(197,100,115,0.08)",i.style.borderColor="rgba(197,100,115,0.3)"});const r=document.createElement("button");r.textContent="blacklist"===o?"永久开启(移出黑名单)":"永久开启(加入白名单)",r.style.cssText="display:block;width:100%;padding:9px 0;border:1px solid #e3e1db;border-radius:10px;background:transparent;color:#403f3a;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",r.addEventListener("mouseenter",()=>{r.style.background="#f0efeb",r.style.borderColor="#d0cec6"}),r.addEventListener("mouseleave",()=>{r.style.background="transparent",r.style.borderColor="#e3e1db"});const a=document.createElement("button");a.textContent="取消",a.style.cssText="display:block;width:100%;padding:8px 0;margin-top:6px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",a.addEventListener("mouseenter",()=>a.style.color="#24231f"),a.addEventListener("mouseleave",()=>a.style.color="#787670");const c=()=>e.remove();i.addEventListener("click",()=>{c(),initApp()}),r.addEventListener("click",()=>{c(),addHostToShowList(),initApp()}),a.addEventListener("click",c),e.addEventListener("click",t=>{t.target===e&&c()}),t.append(n,s,i,r,a),e.appendChild(t),document.documentElement.appendChild(e)}function showMainDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();const e=document.createElement("div");e.className="lsm-dlg-mask",e.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(e,null);const t=document.createElement("div");t.style.cssText="width:360px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const n=document.createElement("div");n.innerHTML="🔑 快照管理助手",n.style.cssText="margin-bottom:10px;display:flex;align-items:center;gap:6px;";const o=getFilterMode(),s=document.createElement("div");s.textContent="blacklist"===o?"当前网站处于黑名单排除范围之外,功能就绪。你可以选择:":"当前网站已在白名单允许列表中,功能就绪。你可以选择:",s.style.cssText="font-size:13px;color:#5c5a55;line-height:1.6;margin-bottom:18px;";const i=document.createElement("button");i.textContent="打开管理窗口",i.style.cssText="display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid rgba(197,100,115,0.3);border-radius:10px;background:rgba(197,100,115,0.08);color:#c56473;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",i.addEventListener("mouseenter",()=>{i.style.background="rgba(197,100,115,0.14)",i.style.borderColor="rgba(197,100,115,0.45)"}),i.addEventListener("mouseleave",()=>{i.style.background="rgba(197,100,115,0.08)",i.style.borderColor="rgba(197,100,115,0.3)"});const r=document.createElement("button");r.textContent="临时隐藏悬浮球(刷新后恢复)",r.style.cssText="display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid #e3e1db;border-radius:10px;background:transparent;color:#403f3a;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",r.addEventListener("mouseenter",()=>{r.style.background="#f0efeb",r.style.borderColor="#d0cec6"}),r.addEventListener("mouseleave",()=>{r.style.background="transparent",r.style.borderColor="#e3e1db"});const a=document.createElement("button");a.textContent="blacklist"===o?"永久关闭(加入黑名单)":"永久关闭(从白名单移除)",a.style.cssText="display:block;width:100%;padding:9px 0;border:1px solid rgba(166,73,83,0.25);border-radius:10px;background:rgba(166,73,83,0.06);color:#a64953;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",a.addEventListener("mouseenter",()=>{a.style.background="rgba(166,73,83,0.12)",a.style.borderColor="rgba(166,73,83,0.4)"}),a.addEventListener("mouseleave",()=>{a.style.background="rgba(166,73,83,0.06)",a.style.borderColor="rgba(166,73,83,0.25)"});const c=document.createElement("button");c.textContent="取消",c.style.cssText="display:block;width:100%;padding:8px 0;margin-top:6px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",c.addEventListener("mouseenter",()=>c.style.color="#24231f"),c.addEventListener("mouseleave",()=>c.style.color="#787670");const l=()=>e.remove(),d=()=>{LSM_UI&&(LSM_UI.ball&&(LSM_UI.ball.style.display="none"),LSM_UI.win&&(LSM_UI.win.style.display="none",LSM_UI.win.classList.add("hidden")))};i.addEventListener("click",async()=>{l(),LSM_UI||await initApp(),LSM_UI&&"function"==typeof LSM_UI.openWindow&&LSM_UI.openWindow()}),r.addEventListener("click",()=>{l(),d()}),a.addEventListener("click",()=>{l(),removeHostFromShowList(),d()}),c.addEventListener("click",l),e.addEventListener("click",t=>{t.target===e&&l()}),t.append(n,s,i,r,a,c),e.appendChild(t),document.documentElement.appendChild(e)}function showSwitchFilterModeDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();const e=getFilterMode(),t="blacklist"===e?"whitelist":"blacklist",n="blacklist"===t?"黑名单模式":"白名单模式",o=document.createElement("div");o.className="lsm-dlg-mask",o.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(o,null);const s=document.createElement("div");s.style.cssText="width:380px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const i=document.createElement("div");i.innerHTML="🛡️ 切换域名过滤模式",i.style.cssText="margin-bottom:10px;display:flex;align-items:center;gap:6px;";const r=document.createElement("div");r.innerHTML=`当前模式:${"blacklist"===e?"黑名单模式 (列表中的网站不生效)":"白名单模式 (仅在列表中生效)"}
点击下方按钮将切换为:${n}
切换后将立即生效并刷新当前页面。`,r.style.cssText="font-size:13px;color:#5c5a55;line-height:1.6;margin-bottom:18px;";const a=document.createElement("button");a.textContent=`确认切换为「${n}」`,a.style.cssText="display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid rgba(197,100,115,0.3);border-radius:10px;background:rgba(197,100,115,0.08);color:#c56473;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",a.addEventListener("mouseenter",()=>{a.style.background="rgba(197,100,115,0.14)",a.style.borderColor="rgba(197,100,115,0.45)"}),a.addEventListener("mouseleave",()=>{a.style.background="rgba(197,100,115,0.08)",a.style.borderColor="rgba(197,100,115,0.3)"});const c=document.createElement("button");c.textContent="取消",c.style.cssText="display:block;width:100%;padding:8px 0;margin-top:4px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",c.addEventListener("mouseenter",()=>c.style.color="#24231f"),c.addEventListener("mouseleave",()=>c.style.color="#787670");const l=()=>o.remove();a.addEventListener("click",()=>{GM_setValue("Config.filter_mode",t),l(),location.reload()}),c.addEventListener("click",l),o.addEventListener("click",e=>{e.target===o&&l()}),s.append(i,r,a,c),o.appendChild(s),document.documentElement.appendChild(o)}function showEditHostListDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();let e=GM_getValue("Config.host_list",null);null==e&&(e=GM_getValue("Config.show_host",""));const t=getFilterMode(),n=document.createElement("div");n.className="lsm-dlg-mask",n.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(n,"textarea");const o=document.createElement("div");o.style.cssText="width:460px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const s=document.createElement("div");s.innerHTML="📝 编辑域名规则列表",s.style.cssText="margin-bottom:8px;display:flex;align-items:center;gap:6px;";const i=document.createElement("div");i.innerHTML=`当前生效模式:${"blacklist"===t?"黑名单模式 (列表中不生效)":"白名单模式 (仅在列表中生效)"}
每行一条规则,支持通配符 *(例:https://*.example.com**.baidu.com):`,i.style.cssText="font-size:12.5px;color:#5c5a55;line-height:1.5;margin-bottom:12px;";const r=document.createElement("textarea");r.value=String(e||""),r.placeholder="*.google.com\nhttps://github.com/*\n*.example.org",r.style.cssText="width:100%;height:160px;box-sizing:border-box;border:1px solid #e3e1db;border-radius:10px;padding:10px 12px;font-size:13px;line-height:1.5;font-family:ui-monospace,Consolas,Monaco,monospace;color:#24231f;resize:vertical;outline:none;background:#ffffff;background-image:linear-gradient(180deg,rgba(197,100,115,0.03) 0%,transparent 26%);transition:border-color .2s,box-shadow .2s;margin-bottom:16px;",r.addEventListener("focus",()=>{r.style.borderColor="rgba(197,100,115,0.35)",r.style.boxShadow="0 0 0 3px rgba(197,100,115,0.1)"}),r.addEventListener("blur",()=>{r.style.borderColor="#e3e1db",r.style.boxShadow="none"});const a=document.createElement("div");a.style.cssText="display:flex;gap:10px;justify-content:flex-end;align-items:center;";const c=document.createElement("button");c.textContent="+ 添加当前网站",c.style.cssText="padding:7px 12px;border:1px solid #e3e1db;border-radius:8px;background:transparent;color:#403f3a;font-size:12px;cursor:pointer;font-weight:500;transition:all .15s;",c.addEventListener("mouseenter",()=>{c.style.background="#f0efeb",c.style.borderColor="#d0cec6"}),c.addEventListener("mouseleave",()=>{c.style.background="transparent",c.style.borderColor="#e3e1db"}),c.addEventListener("click",()=>{const e=location.origin,t=r.value.split("\n").map(e=>e.trim()).filter(Boolean);t.includes(e)||(t.push(e),r.value=t.join("\n"))});const l=document.createElement("button");l.textContent="保存并应用",l.style.cssText="padding:7px 16px;border:1px solid rgba(197,100,115,0.3);border-radius:8px;background:rgba(197,100,115,0.08);color:#c56473;font-size:12.5px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",l.addEventListener("mouseenter",()=>{l.style.background="rgba(197,100,115,0.14)",l.style.borderColor="rgba(197,100,115,0.45)"}),l.addEventListener("mouseleave",()=>{l.style.background="rgba(197,100,115,0.08)",l.style.borderColor="rgba(197,100,115,0.3)"});const d=document.createElement("button");d.textContent="取消",d.style.cssText="padding:7px 12px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",d.addEventListener("mouseenter",()=>d.style.color="#24231f"),d.addEventListener("mouseleave",()=>d.style.color="#787670");const p=()=>n.remove();l.addEventListener("click",()=>{const e=r.value.split("\n").map(e=>e.trim()).filter(Boolean).join("\n");GM_setValue("Config.host_list",e),p(),location.reload()}),d.addEventListener("click",p),n.addEventListener("click",e=>{e.target===n&&p()}),a.append(c,d,l),o.append(s,i,r,a),n.appendChild(o),document.documentElement.appendChild(n)}function showToggleEncryptionDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();const e=GM_getValue("Config.enable_encryption",!1),t=!e,n=document.createElement("div");n.className="lsm-dlg-mask",n.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(n,null);const o=document.createElement("div");o.style.cssText="width:380px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const s=document.createElement("div");s.innerHTML="🔒 本地数据加密设置",s.style.cssText="margin-bottom:10px;display:flex;align-items:center;gap:6px;";const i=document.createElement("div");i.innerHTML=`当前状态:${e?"已开启 AES-GCM 256 位加密":"未开启(明文存储)"}
点击确认将切换为:${t?"开启本地数据加密":"关闭本地数据加密"}
(新保存的快照将按新设置执行,已保存的旧快照依然支持正常读取)`,i.style.cssText="font-size:13px;color:#5c5a55;line-height:1.6;margin-bottom:18px;";const r=document.createElement("button");r.textContent=t?"确认开启加密":"确认关闭加密",r.style.cssText=`display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid ${t?"rgba(197,100,115,0.3)":"rgba(166,73,83,0.25)"};border-radius:10px;background:${t?"rgba(197,100,115,0.08)":"rgba(166,73,83,0.06)"};color:${t?"#c56473":"#a64953"};font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);`,r.addEventListener("mouseenter",()=>{r.style.background=t?"rgba(197,100,115,0.14)":"rgba(166,73,83,0.12)"}),r.addEventListener("mouseleave",()=>{r.style.background=t?"rgba(197,100,115,0.08)":"rgba(166,73,83,0.06)"});const a=document.createElement("button");a.textContent="取消",a.style.cssText="display:block;width:100%;padding:8px 0;margin-top:4px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",a.addEventListener("mouseenter",()=>a.style.color="#24231f"),a.addEventListener("mouseleave",()=>a.style.color="#787670");const c=()=>n.remove();r.addEventListener("click",()=>{GM_setValue("Config.enable_encryption",t),c(),location.reload()}),a.addEventListener("click",c),n.addEventListener("click",e=>{e.target===n&&c()}),o.append(s,i,r,a),n.appendChild(o),document.documentElement.appendChild(n)}function showToggleAutoReloadDialog(){if(document.querySelector(".lsm-dlg-mask"))return;ensureHostAnimationStyle();const e=GM_getValue("Config.auto_reload_after_restore",!1),t=!e,n=document.createElement("div");n.className="lsm-dlg-mask",n.style.cssText="position:fixed;inset:0;z-index:2147483647;background:rgba(20,19,18,0.45);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;overscroll-behavior:contain;font-family:system-ui,-apple-system,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans SC',sans-serif;",bindScrollLock(n,null);const o=document.createElement("div");o.style.cssText="width:380px;max-width:calc(100vw - 32px);background:#faf9f5;border:1px solid #e3e1db;border-radius:16px;padding:24px;box-shadow:0 20px 45px -10px rgba(36,35,31,0.18),0 1px 3px rgba(0,0,0,0.04);box-sizing:border-box;animation:lsmFadeIn .2s cubic-bezier(0.16,1,0.3,1);";const s=document.createElement("div");s.innerHTML="🔄 恢复后自动刷新设置",s.style.cssText="margin-bottom:10px;display:flex;align-items:center;gap:6px;";const i=document.createElement("div");i.innerHTML=`当前状态:${e?"已开启自动刷新/跳转(无需二次弹窗确认)":"不默认刷新(恢复后弹窗提示是否刷新)"}
点击确认将切换为:${t?"恢复后直接自动刷新/跳转":"恢复后二次弹窗确认刷新"}。`,i.style.cssText="font-size:13px;color:#5c5a55;line-height:1.6;margin-bottom:18px;";const r=document.createElement("button");r.textContent=t?"确认切换为「自动刷新/跳转」":"确认切换为「不默认刷新」",r.style.cssText="display:block;width:100%;padding:9px 0;margin-bottom:9px;border:1px solid rgba(197,100,115,0.3);border-radius:10px;background:rgba(197,100,115,0.08);color:#c56473;font-size:13px;cursor:pointer;font-weight:500;transition:all .2s cubic-bezier(0.22,1,0.36,1);",r.addEventListener("mouseenter",()=>{r.style.background="rgba(197,100,115,0.14)",r.style.borderColor="rgba(197,100,115,0.45)"}),r.addEventListener("mouseleave",()=>{r.style.background="rgba(197,100,115,0.08)",r.style.borderColor="rgba(197,100,115,0.3)"});const a=document.createElement("button");a.textContent="取消",a.style.cssText="display:block;width:100%;padding:8px 0;margin-top:4px;border:none;background:none;color:#787670;font-size:12px;cursor:pointer;transition:color .15s;",a.addEventListener("mouseenter",()=>a.style.color="#24231f"),a.addEventListener("mouseleave",()=>a.style.color="#787670");const c=()=>n.remove();r.addEventListener("click",()=>{GM_setValue("Config.auto_reload_after_restore",t),c(),location.reload()}),a.addEventListener("click",c),n.addEventListener("click",e=>{e.target===n&&c()}),o.append(s,i,r,a),n.appendChild(o),document.documentElement.appendChild(n)}function registerAllMenuCommands(){GM_registerMenuCommand("🎨 主题设置 (切换/导出/导入)",async()=>{LSM_UI||await initApp(),LSM_UI&&("function"==typeof LSM_UI.openWindow&&LSM_UI.openWindow(),"function"==typeof LSM_UI.openThemeDialog&&LSM_UI.openThemeDialog())}),GM_registerMenuCommand("🔑 快照管理助手",()=>{hostBlocked()?showBlockedDialog():showMainDialog()});const e=getFilterMode();GM_registerMenuCommand("blacklist"===e?"🛡️ 当前为【黑名单】模式 (点击切换为白名单)":"🛡️ 当前为【白名单】模式 (点击切换为黑名单)",()=>{showSwitchFilterModeDialog()}),GM_registerMenuCommand("📝 编辑域名规则列表 (黑/白名单)",()=>{showEditHostListDialog()});const t=GM_getValue("Config.enable_encryption",!1);GM_registerMenuCommand(t?"🔒 本地数据【已加密】 (点击切换/关闭)":"🔓 本地数据【未加密】 (点击切换/开启)",()=>{showToggleEncryptionDialog()});const n=GM_getValue("Config.auto_reload_after_restore",!1);GM_registerMenuCommand(n?"🔄 恢复后【自动刷新/跳转】 (点击切换为不刷新)":"⏸️ 恢复后【不默认刷新】 (点击切换为自动刷新)",()=>{showToggleAutoReloadDialog()}),GM_registerMenuCommand("☁️ 云同步设置与状态 (GitHub Gist)",async()=>{hostBlocked()?showBlockedDialog():(LSM_UI||await initApp(),LSM_UI&&"function"==typeof LSM_UI.openWindow&&(LSM_UI.openWindow(),"function"==typeof LSM_UI.openCloudSyncDialog&&LSM_UI.openCloudSyncDialog()))})}async function initApp(){document.getElementById("lsm-session-manager-root")?LSM_UI&&LSM_UI.ball&&(LSM_UI.ball.style.display="",LSM_UI.ball.classList.remove("hidden")):(patchInnerHTMLSetter(),initAppUI())}(async()=>{"use strict";registerAllMenuCommands(),hostBlocked()||initApp()})();