// ==UserScript== // @name Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-CN Ophel Atlas - AI 对话结构化与导航工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:zh-TW Ophel Atlas - AI 對話結構化與導覽工具, 全能AI助手 (支持 Gemini, ChatGPT, Claude, Grok, AI Studio, 豆包) // @name:en Ophel Atlas - AI Chat Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:de Ophel Atlas - KI-Chat-Organizer & Navigator (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:es Ophel Atlas - Organizador de Chats de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:fr Ophel Atlas - Organisateur de Chat IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ja Ophel Atlas - AI対話の構造化とナビゲーションツール (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ko Ophel Atlas - AI 채팅 정리 및 탐색 도구 (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:pt-BR Ophel Atlas - Organizador de Chat de IA (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @name:ru Ophel Atlas - Органайзер AI-чатов (Support Gemini, ChatGPT, Claude, Grok, AI Studio) // @namespace https://github.com/urzeye/ophel // @version 1.0.58 // @author urzeye // @description 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:en AI chat navigator and organizer for Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM, and Z.ai. Adds real-time outlines, Search Everywhere, conversation folders, pinning, prompt queue, prompt library, Markdown/JSON export, WebDAV sync, Zen Mode, wide/full-screen reading, scroll lock, LaTeX/table copy, tab renaming, privacy mode, notifications, reading history restore, shortcuts, prompt variables, and theme tweaks. Sound presets. Batch import. // @description:zh-CN 适用于 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 对话导航与整理工具,提供实时大纲、Search Everywhere 全局搜索、会话文件夹、置顶、提示词队列与提示词库、提示词变量、Markdown/JSON 导出、思维链导出控制、WebDAV 同步、禅模式、宽屏/全屏阅读、滚动锁定、主题切换、LaTeX/表格复制、标签页重命名、隐私模式、完成通知音、阅读历史恢复、快捷键与批量导入提示词队列,让长 AI 对话更易搜索、更易导航、更易沉淀、更易复用。 // @description:zh-TW 適用於 Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai 的 AI 對話導覽與整理工具,提供即時大綱、Search Everywhere 全域搜尋、對話資料夾、置頂、提示詞佇列與提示詞庫、提示詞變數、Markdown/JSON 匯出、思維鏈匯出控制、WebDAV 同步、禪模式、寬螢幕/全螢幕閱讀、捲動鎖定、主題切換、LaTeX/表格複製、分頁重新命名、隱私模式、完成通知音、閱讀歷史恢復、快捷鍵與批量匯入提示詞佇列,讓長 AI 對話更易搜尋、更易導覽、更易沉澱、更易複用。 // @description:de KI-Chat-Navigator für Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM und Z.ai. Mit Echtzeit-Gliederung, Search Everywhere, Ordnern, Pinning, Prompt-Queue, Markdown/JSON-Export, WebDAV-Sync, Zen Mode, Scroll Lock, Tab-Umbenennung, Benachrichtigungen und Verlauf für lange, durchsuchbare AI-Chats. // @description:es Navegador y organizador de chats con IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM y Z.ai. Incluye esquemas en tiempo real, Search Everywhere, carpetas, fijado, cola y biblioteca de prompts, variables, exportación Markdown/JSON, sincronización WebDAV, Zen Mode, lectura amplia, bloqueo de desplazamiento, copia de LaTeX/tablas, renombrado de pestañas, privacidad, notificaciones e historial para chats largos y reutilizables. // @description:fr Navigateur et organisateur de chats IA pour Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM et Z.ai. Ajoute un plan en temps réel, Search Everywhere, dossiers, épinglage, file et bibliothèque de prompts, variables, export Markdown/JSON, sync WebDAV, Zen Mode, lecture large, verrouillage du défilement, copie LaTeX/tableaux, renommage des onglets, confidentialité, notifications et reprise de lecture pour des chats IA longs et réutilisables. // @description:ja Gemini、Gemini Enterprise、AI Studio、ChatGPT、Claude、Grok、DeepSeek、QwenAI、豆包、Kimi、ChatGLM、Z.ai に対応する AI対話ナビゲーション整理ツール。リアルタイム目次、Search Everywhere、会話フォルダ、ピン留め、プロンプトキューとプロンプトライブラリ、プロンプト変数、Markdown/JSON エクスポート、WebDAV 同期、禅モード、ワイド/全画面読書、スクロールロック、LaTeX/表コピー、タブ名変更、プライバシーモード、完了通知、閲覧履歴復元を提供し、長い AI 対話を検索しやすく再利用しやすくします。 // @description:ko Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, QwenAI, 豆包, Kimi, ChatGLM, Z.ai를 지원하는 AI 대화 탐색·정리 도구입니다. 실시간 개요, Search Everywhere, 대화 폴더, 고정, 프롬프트 큐와 프롬프트 라이브러리, 프롬프트 변수, Markdown/JSON 내보내기, WebDAV 동기화, Zen Mode, 와이드/전체 화면 읽기, 스크롤 잠금, LaTeX/표 복사, 탭 이름 변경, 프라이버시 모드, 완료 알림, 읽기 기록 복원을 제공해 긴 AI 대화를 더 쉽게 검색하고 재사용할 수 있게 합니다. // @description:pt-BR Navegador e organizador de chats com IA para Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM e Z.ai. Inclui outlines em tempo real, Search Everywhere, pastas, fixação, fila e biblioteca de prompts, variáveis, exportação Markdown/JSON, sincronização WebDAV, Zen Mode, leitura ampla, scroll lock, cópia de LaTeX/tabelas, renomeação de abas, privacidade, notificações e histórico para chats longos, pesquisáveis e reutilizáveis. // @description:ru Навигатор и органайзер AI-чатов для Gemini, Gemini Enterprise, AI Studio, ChatGPT, Claude, Grok, DeepSeek, Kimi, QwenAI, Doubao, ChatGLM и Z.ai. Добавляет структуру в реальном времени, Search Everywhere, папки, закрепление, очередь и библиотеку промптов, переменные, экспорт Markdown/JSON, синхронизацию WebDAV, Zen Mode, широкий режим, Scroll Lock, копирование LaTeX/таблиц, переименование вкладок, приватный режим, уведомления и историю чтения для длинных и переиспользуемых AI-чатов. // @license GPL-3.0-only // @icon https://raw.githubusercontent.com/urzeye/ophel/main/assets/icon.png // @homepageURL https://github.com/urzeye/ophel // @source https://github.com/urzeye/ophel.git // @supportURL https://github.com/urzeye/ophel/issues // @match https://gemini.google.com/* // @match https://business.gemini.google/* // @match https://aistudio.google.com/* // @match https://grok.com/* // @match https://chat.openai.com/* // @match https://chatgpt.com/* // @match https://claude.ai/* // @match https://www.doubao.com/* // @match https://ima.qq.com/* // @match https://chat.deepseek.com/* // @match https://www.kimi.com/* // @match https://chatglm.cn/* // @match https://chat.qwen.ai/* // @match https://www.qianwen.com/* // @match https://yuanbao.tencent.com/* // @match https://chat.z.ai/* // @require https://cdn.jsdelivr.net/npm/react@18.3.1/umd/react.production.min.js // @require https://cdn.jsdelivr.net/npm/react-dom@18.3.1/umd/react-dom.production.min.js // @require https://cdn.jsdelivr.net/npm/fuzzysort@3.1.0/fuzzysort.min.js // @require https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.js // @resource ophelAssistantMermaidRunner https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js // @resource ophelAssistantMermaidVendor https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js // @resource ophelIcon https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-icon.193ed41c2441.png // @resource ophelKatexCss https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css // @resource ophelLocaleDe https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.de.26d16336f700.json // @resource ophelLocaleEn https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.en.7d2a8132be67.json // @resource ophelLocaleEs https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.es.003f1ad24fe3.json // @resource ophelLocaleFr https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.fr.24888b6fd25a.json // @resource ophelLocaleJa https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ja.964d00272f7a.json // @resource ophelLocaleKo https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ko.b55002860c1c.json // @resource ophelLocalePt https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.pt.1e6352e6ab1f.json // @resource ophelLocaleRu https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.ru.bb8552eaae2a.json // @resource ophelLocaleZhCN https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.zh-CN.3ec20378883c.json // @resource ophelLocaleZhTW https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.locale.zh-TW.5e00c6cf7f52.json // @resource ophelNotificationBrightAlert https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-bright-alert.568967a3d9f8.ogg // @resource ophelNotificationDefault https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-default.15d3cda1ee80.mp3 // @resource ophelNotificationGlassPing https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-glass-ping.2379b58f953e.ogg // @resource ophelNotificationSoftChime https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-sound-soft-chime.063564703b60.ogg // @resource ophelStyles https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel.user.6f3f3e0dbc00.css // @resource ophelWatermarkBg48 https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-watermark-bg-48.4afc99afe0ef.png // @resource ophelWatermarkBg96 https://cdn.jsdelivr.net/gh/urzeye/ophel@userscript-assets/userscript-assets/ophel-watermark-bg-96.3e26f2233a12.png // @connect * // @grant GM_addStyle // @grant GM_addValueChangeListener // @grant GM_cookie // @grant GM_deleteValue // @grant GM_getResourceText // @grant GM_getResourceURL // @grant GM_getValue // @grant GM_info // @grant GM_notification // @grant GM_removeValueChangeListener // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @grant window.focus // @run-at document-start // @noframes // @tag ai // @tag chat // @tag productivity // @tag navigation // @tag outline // @tag conversation // @tag prompt // @tag export // @tag chinese // @tag multilingual // @tag cross-platform // @tag ai-assistant // @tag all-in-one // @tag 全能AI助手 // ==/UserScript== (function () { 'use strict'; const d$1=new Set;const e = async e=>{d$1.has(e)||(d$1.add(e),(t=>{typeof GM_addStyle=="function"?GM_addStyle(t):(document.head||document.documentElement).appendChild(document.createElement("style")).append(t);})(e));}; const t=function(){const e="undefined"!=typeof document&&document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"}(),n={},r=function(e,r,o){let i=Promise.resolve();if(r&&r.length>0){let e=function(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),a=o?.nonce||o?.getAttribute("nonce");i=e(r.map(e=>{if((e=function(e){return "/"+e}(e))in n)return;n[e]=true;const r=e.endsWith(".css"),o=r?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${e}"]${o}`))return;const i=document.createElement("link");return i.rel=r?"stylesheet":t,r||(i.as="script"),i.crossOrigin="",i.href=e,a&&i.setAttribute("nonce",a),document.head.appendChild(i),r?new Promise((t,n)=>{i.addEventListener("load",t),i.addEventListener("error",()=>n(new Error(`Unable to preload CSS for ${e}`)));}):void 0}));}function a(e){const t=new Event("vite:preloadError",{cancelable:true});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return i.then(t=>{for(const e of t||[])"rejected"===e.status&&a(e.reason);return e().catch(a)})};const o=function(){const e=globalThis.React;if(!e||"function"!=typeof e.createElement)throw new Error("[Ophel] React CDN runtime is missing");return e}(),i=o.Children,a=o.Component,s=o.Fragment,l=o.Profiler,c=o.PureComponent,d=o.StrictMode,u=o.Suspense,h=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,g=o.act,p=o.cloneElement,m=o.createContext,f=o.createElement,b=o.createFactory,y=o.createRef,v=o.forwardRef,w=o.isValidElement,x=o.lazy,k=o.memo,S=o.startTransition,C=o.unstable_act,A=o.useCallback,E=o.useContext,T=o.useDebugValue,M=o.useDeferredValue,_=o.useEffect,I=o.useId,L=o.useImperativeHandle,N=o.useInsertionEffect,D=o.useLayoutEffect,q=o.useMemo,R=o.useReducer,P=o.useRef,z=o.useState,B=o.useSyncExternalStore,O=o.useTransition,F=o.version,$=Object.freeze(Object.defineProperty({__proto__:null,Children:i,Component:a,Fragment:s,Profiler:l,PureComponent:c,StrictMode:d,Suspense:u,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:h,act:g,cloneElement:p,createContext:m,createElement:f,createFactory:b,createRef:y,default:o,forwardRef:v,isValidElement:w,lazy:x,memo:k,startTransition:S,unstable_act:C,useCallback:A,useContext:E,useDebugValue:T,useDeferredValue:M,useEffect:_,useId:I,useImperativeHandle:L,useInsertionEffect:N,useLayoutEffect:D,useMemo:q,useReducer:R,useRef:P,useState:z,useSyncExternalStore:B,useTransition:O,version:F},Symbol.toStringTag,{value:"Module"}));const U=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createRoot)throw new Error("[Ophel] ReactDOM client CDN runtime is missing");return e}();U.createRoot,U.hydrateRoot;const j=["zh-CN","zh-TW","en","ja","ko","fr","de","ru","es","pt"],H={styles:{metaName:"ophelStyles",fileName:"ophel.user.css"},icon:{metaName:"ophelIcon",fileName:"ophel-icon.png"},notificationDefault:{metaName:"ophelNotificationDefault",fileName:"ophel-sound-default.mp3"},notificationSoftChime:{metaName:"ophelNotificationSoftChime",fileName:"ophel-sound-soft-chime.ogg"},notificationGlassPing:{metaName:"ophelNotificationGlassPing",fileName:"ophel-sound-glass-ping.ogg"},notificationBrightAlert:{metaName:"ophelNotificationBrightAlert",fileName:"ophel-sound-bright-alert.ogg"},watermarkBg48:{metaName:"ophelWatermarkBg48",fileName:"ophel-watermark-bg-48.png"},watermarkBg96:{metaName:"ophelWatermarkBg96",fileName:"ophel-watermark-bg-96.png"},assistantMermaidRunner:{metaName:"ophelAssistantMermaidRunner",fileName:"ophel-assistant-mermaid-runner.js",externalUrl:"https://cdn.jsdelivr.net/gh/urzeye/ophel@main/assets/assistant-mermaid-runner.js"},assistantMermaidVendor:{metaName:"ophelAssistantMermaidVendor",fileName:"ophel-assistant-mermaid-vendor.js",externalUrl:"https://cdn.jsdelivr.net/npm/@mermaid-js/tiny@11.13.0/dist/mermaid.tiny.js"}},W={"zh-CN":{metaName:"ophelLocaleZhCN",fileName:"ophel.locale.zh-CN.json"},"zh-TW":{metaName:"ophelLocaleZhTW",fileName:"ophel.locale.zh-TW.json"},en:{metaName:"ophelLocaleEn",fileName:"ophel.locale.en.json"},ja:{metaName:"ophelLocaleJa",fileName:"ophel.locale.ja.json"},ko:{metaName:"ophelLocaleKo",fileName:"ophel.locale.ko.json"},fr:{metaName:"ophelLocaleFr",fileName:"ophel.locale.fr.json"},de:{metaName:"ophelLocaleDe",fileName:"ophel.locale.de.json"},ru:{metaName:"ophelLocaleRu",fileName:"ophel.locale.ru.json"},es:{metaName:"ophelLocaleEs",fileName:"ophel.locale.es.json"},pt:{metaName:"ophelLocalePt",fileName:"ophel.locale.pt.json"}};const G="OPHEL_GEMINI_CANVAS_CODE_REQUEST",Q="OPHEL_GEMINI_CANVAS_CODE_RESPONSE";function V(e){if(e.__ophelGeminiCanvasMainInitialized)return;e.__ophelGeminiCanvasMainInitialized=true,e.document.documentElement.setAttribute("data-ophel-gemini-canvas-main","1");e.addEventListener("message",t=>{if(t.origin&&t.origin!==e.location.origin)return;const n=t.data;if(n?.type!==G)return;const r="string"==typeof n.requestId?n.requestId:"";if(!r)return;const o=(t=>{const n=e.monaco?.editor?.getModels?.();if(!Array.isArray(n)||0===n.length)return "";const r=n.find(e=>{const n=e;return t&&n.uri?.toString?.()===t})||(1===n.length?n[0]:null);return "function"!=typeof r?.getValue?"":r.getValue()})("string"==typeof n.editorUri?n.editorUri:"");e.postMessage({type:Q,requestId:r,code:o},"*");});}const K="en",Z={},Y=new Set,J=()=>{if("undefined"==typeof navigator)return K;const e=navigator.language;return e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":K};let X=J();function ee(e){return e&&"auto"!==e?(t=e,Object.prototype.hasOwnProperty.call(W,t)?e:e.startsWith("zh-TW")||e.startsWith("zh-HK")?"zh-TW":e.startsWith("zh")?"zh-CN":e.startsWith("ja")?"ja":e.startsWith("ko")?"ko":e.startsWith("fr")?"fr":e.startsWith("de")?"de":e.startsWith("ru")?"ru":e.startsWith("es")?"es":e.startsWith("pt")?"pt":K):J();var t;}function te(e){const t=Z[e];if(t)return t;const n=W[e].metaName;try{const t=GM_getResourceText(n);if(!t)return Z[e]={},Z[e];const r=JSON.parse(t);return Z[e]=r,r}catch(r){return console.warn(`[Ophel] Failed to load userscript locale resource: ${e}`,r),Z[e]={},Z[e]}}function ne(e){const t=ee(e);return X=t,te(K),t!==K&&te(t),t}function re(){return function(e){if(e)try{const t="string"==typeof e?JSON.parse(e):e,n="object"==typeof t&&null!==t?t.state?.settings?.language:void 0;return "string"==typeof n?n:void 0}catch(t){return void console.warn("[Ophel] Failed to parse persisted settings language:",t)}}(GM_getValue("settings"))||"auto"}function oe(e){return Y.add(e),()=>{Y.delete(e);}}function ie(e){const t=ee(e),n=X;X=t,te(K),te(t),n!==t&&Y.forEach(e=>{try{e();}catch(t){console.warn("[Ophel] Userscript i18n listener failed:",t);}});}function ae(e){return ee(e)}function se(e,t){const n=te(X),r=X===K?n:te(K);let o=n[e]||r[e]||e;return t&&Object.keys(t).forEach(e=>{o=o.replace(new RegExp(`{${e}}`,"g"),t[e]);}),o}function le(e){return Array.from(new Set(j.map(t=>te(t)[e]).filter(e=>"string"==typeof e&&e.trim().length>0)))}function ce(){return X}const de=Object.freeze(Object.defineProperty({__proto__:null,getAllLocalizedTexts:le,getCurrentLang:ce,getEffectiveLanguage:ae,getInitialUserscriptLanguage:re,primeUserscriptLocales:ne,setLanguage:ie,subscribeI18nChanges:oe,t:se},Symbol.toStringTag,{value:"Module"}));const ue='@font-face {\n font-family: "Inter";\n src: local("Inter"), local("InterVariable");\n font-style: normal;\n font-weight: 100 900;\n unicode-range:\n U+0000-02FF, U+0304, U+0308, U+0329, U+0370-03FF, U+1D00-1DBF, U+1E00-1EFF,\n U+1F00-1FFF, U+0400-052F, U+1C80-1C88, U+2116, U+2DE0-2DFF, U+A640-A69F,\n U+1EA0-1EF9, U+20AB, U+2000-206F, U+20A0-20C0, U+20AC, U+2113, U+2122,\n U+2191, U+2193, U+2212, U+2215, U+2C60-2C7F, U+A720-A7FF, U+FEFF, U+FFFD;\n}',he=["gh-platform-macos","gh-platform-windows","gh-platform-other"],ge='"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif',pe=`var(--gh-font-family, ${ge})`;function me(){if("undefined"==typeof navigator)return "other";const e=navigator.userAgentData?.platform,t=[navigator.platform,e,navigator.userAgent].filter(Boolean).join(" ").toLowerCase();return /mac|iphone|ipad|ipod/.test(t)?"macos":/win/.test(t)?"windows":"other"}function fe(e=me()){return "macos"===e?'"Inter", "Hiragino Sans SC", "PingFang SC", "Apple SD Gothic Neo", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Microsoft YaHei", "Malgun Gothic", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif':ge}function be(e){e.classList.remove(...he),e.classList.add(function(e=me()){return `gh-platform-${e}`}());}fe();const ye=new Set,ve=new Set(Object.values(H).filter(({fileName:e})=>/\.(mp3|ogg)$/i.test(e)).map(({metaName:e})=>e)),we=Object.fromEntries(Object.values(H).map(({metaName:e,fileName:t})=>{const n=t.split(".").pop()?.toLowerCase();return [e,"css"===n?"text/css":"png"===n?"image/png":"mp3"===n?"audio/mpeg":"ogg"===n?"audio/ogg":"application/octet-stream"]}));function xe(e,t){if(!t.startsWith("data:")||!ve.has(e))return t;try{const n=t.indexOf(",");if(-1===n)return t;const r=t.slice(5,n),o=t.slice(n+1),i=r.split(";").filter(Boolean),a=i[0]||"",s=we[e]||a||"application/octet-stream",l=i.includes("base64")?function(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r"string"==typeof e&&e.length>0)),window.__OPHEL_USERSCRIPT_ASSET_URLS__={icon:Se(H.icon.metaName)||"",watermarkBg48:Se(H.watermarkBg48.metaName)||"",watermarkBg96:Se(H.watermarkBg96.metaName)||"",assistantMermaidRunner:Se(H.assistantMermaidRunner.metaName)||"",assistantMermaidVendor:Se(H.assistantMermaidVendor.metaName)||""},ne(re()),"undefined"==typeof chrome||!chrome.storage){const e=["settings","prompts","folders","tags","readingHistory","claudeSessionKeys","conversations"];window.chrome={storage:{local:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},sync:{get:(t,n)=>{if(null===t){const t={};for(const n of e){const e=GM_getValue(n);null!=e&&(t[n]=e);}n(t);}else if("string"==typeof t){const e=GM_getValue(t);n({[t]:e});}else {const e={};for(const n of t)e[n]=GM_getValue(n);n(e);}},set:(e,t)=>{for(const[n,r]of Object.entries(e))GM_setValue(n,r);t?.();},remove:(e,t)=>{const n="string"==typeof e?[e]:e;for(const r of n)GM_deleteValue(r);t?.();},clear:t=>{for(const n of e)GM_deleteValue(n);t?.();}},onChanged:{addListener:()=>{},removeListener:()=>{}}},runtime:{getManifest:()=>({version:"1.0.0"}),getURL:e=>e,sendMessage:()=>Promise.resolve({})}};}const Ee=window.chrome?.storage;Ee&&!Ee.onChanged&&(Ee.onChanged={addListener:()=>{},removeListener:()=>{}});const Te=window.chrome?.runtime;if(Te&&!Te.onMessage&&(Te.onMessage={addListener:()=>{},removeListener:()=>{}}),window.top!==window.self)throw new Error("Ophel: Running in iframe, skipping initialization");if(window.ophelUserscriptInitialized)throw new Error("Ophel: Already initialized");async function Me(){const[{getAdapter:e},{App:t},{initNetworkMonitor:n}]=await Promise.all([r(()=>Promise.resolve().then(()=>nv),void 0),r(()=>Promise.resolve().then(()=>KS),void 0),r(()=>Promise.resolve().then(()=>CC),void 0)]),i=e();if(!i)return;i.afterPropertiesSet({});let a=null,s=null;const l=()=>{a?.disconnect(),a=null,null!==s&&(window.clearInterval(s),s=null);};await(async()=>{try{const e=document.createElement("div");e.id="ophel-userscript-root",be(e),e.style.cssText="all: initial; display: block; position: fixed; inset: 0; width: 0; height: 0; overflow: visible; pointer-events: none; z-index: 2147483647;";const n=()=>document.body||document.documentElement,r=async()=>{n()||await new Promise(e=>{const t=new MutationObserver(()=>{n()&&(t.disconnect(),e());});t.observe(document.documentElement,{childList:!0,subtree:!0});});},i=()=>{const t=n();t&&e.parentElement!==t&&t.appendChild(e);};await r(),i(),[250,600,1200,2e3,3500,5e3].forEach(e=>setTimeout(i,e)),a=new MutationObserver(()=>{e.isConnected||i();}),a.observe(document.documentElement,{childList:!0,subtree:!0}),s=window.setInterval(()=>{e.isConnected||i();},2e3),window.location.hostname.includes("chatglm.cn")&&e.classList.add("gh-site-chatglm");const l=e.attachShadow({mode:"open"}),c=document.createElement("style");let d="";try{d=localStorage.getItem("ophel_us_theme_cache")||"";}catch{}c.textContent=(Ce||"")+(d?"\n"+d:""),l.appendChild(c);const u=document.createElement("div");u.id="ophel-app-container",l.appendChild(u);const h=()=>{const[,e]=o.useState(0);return o.useEffect(()=>oe(()=>{e(e=>e+1);}),[]),o.createElement(t)};U.createRoot(u).render(o.createElement(h));}catch(e){throw l(),e}})();const{useSettingsStore:c,getSettingsState:d}=await r(async()=>{const{useSettingsStore:e,getSettingsState:t}=await Promise.resolve().then(()=>_i);return {useSettingsStore:e,getSettingsState:t}},void 0),{useConversationsStore:u}=await r(async()=>{const{useConversationsStore:e}=await Promise.resolve().then(()=>av);return {useConversationsStore:e}},void 0),{useFoldersStore:h}=await r(async()=>{const{useFoldersStore:e}=await Promise.resolve().then(()=>hv);return {useFoldersStore:e}},void 0),{useTagsStore:g}=await r(async()=>{const{useTagsStore:e}=await Promise.resolve().then(()=>fv);return {useTagsStore:e}},void 0),{usePromptsStore:p}=await r(async()=>{const{usePromptsStore:e}=await Promise.resolve().then(()=>Nv);return {usePromptsStore:e}},void 0),{useClaudeSessionKeysStore:m}=await r(async()=>{const{useClaudeSessionKeysStore:e}=await Promise.resolve().then(()=>Jk);return {useClaudeSessionKeysStore:e}},void 0),{useReadingHistoryStore:f}=await r(async()=>{const{useReadingHistoryStore:e}=await Promise.resolve().then(()=>mk);return {useReadingHistoryStore:e}},void 0),b=e=>{if(e.getState()._hasHydrated)return Promise.resolve(true);return new Promise(t=>{let n,r=false;const o=e=>{r||(r=true,window.clearTimeout(n),t(e));},i=e.subscribe(e=>{e._hasHydrated&&(i(),o(true));});n=window.setTimeout(()=>{i(),e.setState({_hasHydrated:true}),o(false);},5e3);})};await Promise.all([b(c),b(u),b(h),b(g),b(p),b(m),b(f)]);const y=d(),v=i.getSiteId(),{initCoreModules:w,subscribeModuleUpdates:x,initUrlChangeObserver:k}=await r(async()=>{const{initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}=await Promise.resolve().then(()=>YA);return {initCoreModules:e,subscribeModuleUpdates:t,initUrlChangeObserver:n}},void 0),S={adapter:i,settings:y,siteId:v};await w(S),n(),x(S),k(S),window.addEventListener("unload",l),window.addEventListener("unload",ke);}window.ophelUserscriptInitialized=true,function(){const e="undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window;if(e.__ophelScrollLockInitialized)return;e.__ophelScrollLockInitialized=true;const t=e.Element,n=e.HTMLElement,r={scrollIntoView:t.prototype.scrollIntoView,scrollTo:e.scrollTo.bind(e),scrollTopDescriptor:Object.getOwnPropertyDescriptor(t.prototype,"scrollTop")||Object.getOwnPropertyDescriptor(n.prototype,"scrollTop")};function o(){const e=document.documentElement.dataset.ophelPositionLock;if(void 0!==e){const t=Number(e);if(!isNaN(t))return t}return null}function i(){document.documentElement.dataset.ophelPositionLockLastBlock=String(Date.now());}if(e.__ophelOriginalApis=r,e.__ophelScrollLockEnabled=false,t.prototype.scrollIntoView=function(t){const n=t&&"object"==typeof t&&t.__bypassLock;if(null!==o()){if(n)return r.scrollIntoView.call(this,t);let e=this.parentElement;for(;e;){if(e.scrollWidth>e.clientWidth&&e.scrollHeight<=e.clientHeight+10)return r.scrollIntoView.call(this,t);e=e.parentElement;}return void i()}if(!e.__ophelScrollLockEnabled)return r.scrollIntoView.call(this,t);let a=this.parentElement;for(;a;){if(a.scrollWidth>a.clientWidth&&a.scrollHeight<=a.clientHeight+10)return r.scrollIntoView.call(this,t);a=a.parentElement;}return n?r.scrollIntoView.call(this,t):void 0},e.scrollTo=function(t,n){if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return r.scrollTo.apply(e,arguments);let a;return a="object"==typeof t&&null!==t?t.top:n,"number"==typeof a&&a>e.scrollY+50?void 0:r.scrollTo.apply(e,arguments)},r.scrollTopDescriptor){const n=r.scrollTopDescriptor;Object.defineProperty(t.prototype,"scrollTop",{get:function(){return n.get?n.get.call(this):0},set:function(t){if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return void(n.set&&n.set.call(this,t));const r=o();if(null!==r)return Math.abs(t-r)>10?(i(),void(n.set&&n.set.call(this,r))):void(n.set&&n.set.call(this,t));if(!e.__ophelScrollLockEnabled)return void(n.set&&n.set.call(this,t));t>(n.get?n.get.call(this):0)+50||n.set&&n.set.call(this,t);},configurable:true});}const a=t.prototype.scrollTo;t.prototype.scrollTo=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return a.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return a.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return a.apply(this,arguments);let r;"object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n);const s=this.scrollTop||0;return "number"==typeof r&&r>s+50?void 0:a.apply(this,arguments)};const s=t.prototype.scroll;t.prototype.scroll=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return s.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return s.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return s.apply(this,arguments);let r;"object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n);const a=this.scrollTop||0;return "number"==typeof r&&r>a+50?void 0:s.apply(this,arguments)};const l=t.prototype.scrollBy;if(t.prototype.scrollBy=function(t,n){if("object"==typeof t&&null!==t&&void 0!==t.left&&void 0===t.top)return l.apply(this,arguments);if(this.scrollWidth>this.clientWidth&&this.scrollHeight<=this.clientHeight+10)return l.apply(this,arguments);if(null!==o())return void i();if(!e.__ophelScrollLockEnabled)return l.apply(this,arguments);let r;return "object"==typeof t&&null!==t?r=t.top:"number"==typeof n&&(r=n),"number"==typeof r&&r>50?void 0:l.apply(this,arguments)},e.addEventListener("message",t=>{"OPHEL_SCROLL_LOCK_TOGGLE"===t.data?.type&&(e.__ophelScrollLockEnabled=t.data.enabled);}),"function"==typeof t.prototype.scrollIntoViewIfNeeded){const e=t.prototype.scrollIntoViewIfNeeded;t.prototype.scrollIntoViewIfNeeded=function(t){if(null===o())return e.call(this,t);i();};}}(),"gemini.google.com"===location.hostname&&V("undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Me();},{once:true}):Me();const _e=o.Fragment,Ie=(e,t,n)=>o.createElement(e,function(e,t){return void 0===t?e??{}:{...e??{},key:t}}(t,n)),Le=Ie,Ne=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Ie("circle",{cx:"12",cy:"12",r:"4"}), Ie("line",{x1:"12",y1:"2",x2:"12",y2:"4"}), Ie("line",{x1:"12",y1:"20",x2:"12",y2:"22"}), Ie("line",{x1:"4.93",y1:"4.93",x2:"6.34",y2:"6.34"}), Ie("line",{x1:"17.66",y1:"17.66",x2:"19.07",y2:"19.07"}), Ie("line",{x1:"2",y1:"12",x2:"4",y2:"12"}), Ie("line",{x1:"20",y1:"12",x2:"22",y2:"12"}), Ie("line",{x1:"4.93",y1:"19.07",x2:"6.34",y2:"17.66"}), Ie("line",{x1:"17.66",y1:"6.34",x2:"19.07",y2:"4.93"})]}),De=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:Ie("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})}),qe=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:Ie("path",{fill:t,fillRule:"evenodd",clipRule:"evenodd",d:"M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"})}),Re=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Ie("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),Pe=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("circle",{cx:"12",cy:"5",r:"2.5"}), Ie("line",{x1:"12",y1:"7.5",x2:"12",y2:"22"}), Ie("line",{x1:"7",y1:"10",x2:"17",y2:"10"}), Ie("path",{d:"M4 14C4 19 8 22 12 22C16 22 20 19 20 14"}), Ie("path",{d:"M1.5 16.5L4 14L6.5 16.5"}), Ie("path",{d:"M17.5 16.5L20 14L22.5 16.5"})]}),ze=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 1024 1024",fill:"none",className:n,children:[ Ie("path",{d:"M768 208H595.349a223.478 223.478 0 0 1-147.964-56 223.473 223.473 0 0 0-147.964-56H256C149.961 96 64 181.961 64 288v448c0 106.038 85.961 192 192 192h512c106.039 0 192-85.962 192-192V400c0-106.039-85.961-192-192-192z m112 528c0 61.757-50.243 112-112 112H256c-61.757 0-112-50.243-112-112V288c0-61.758 50.243-112 112-112h43.421a143.372 143.372 0 0 1 94.995 35.953A303.263 303.263 0 0 0 595.349 288H768c61.757 0 112 50.242 112 112v336z",fill:t}), Ie("path",{d:"M690.783 471.577l-82.681-91.826c-7.899-8.772-18.796-13.236-29.739-13.235a39.868 39.868 0 0 0-26.752 10.274c-16.417 14.782-17.743 40.074-2.961 56.491L576.31 464H360c-22.092 0-40 17.908-40 40 0 22.091 17.908 40 40 40h304c22.092 0 40-17.909 40-40 0-8.139-2.461-15.688-6.636-22.005-1.66-3.69-3.728-7.25-6.581-10.418zM664 606.516H360c-22.092 0-40 17.908-40 40 0 8.139 2.461 15.688 6.636 22.005 1.66 3.69 3.729 7.25 6.581 10.418l82.681 91.826c7.899 8.772 18.796 13.235 29.739 13.235a39.863 39.863 0 0 0 26.752-10.274c16.417-14.782 17.743-40.074 2.961-56.491l-27.659-30.719H664c22.092 0 40-17.908 40-40s-17.908-40-40-40z",fill:t})]}),Be=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Ie("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), Ie("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),Oe=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Ie("circle",{cx:"12",cy:"12",r:"3"}), Ie("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),Fe=({size:e=18,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:[ Ie("path",{d:"M512 960c-234.394624 0-425.10336-190.708736-425.10336-425.10336S277.605376 109.79328 512 109.79328c116.878336 0 225.772544 46.432256 306.69312 130.737152 9.644032 10.027008 44.068864 47.517696 52.627456 58.438656 11.113472 14.242816 8.558592 34.807808-5.684224 45.92128-14.306304 11.113472-34.87232 8.49408-45.92128-5.684224-7.791616-10.027008-39.406592-44.196864-48.156672-53.32992C703.028224 214.472704 610.8672 175.194112 512 175.194112c-198.308864 0-359.702528 161.393664-359.702528 359.702528S313.691136 894.599168 512 894.599168 871.702528 733.205504 871.702528 534.89664c0-18.074624 14.625792-32.700416 32.700416-32.700416s32.700416 14.625792 32.700416 32.700416c0 234.394624-190.708736 425.10336-425.10336 425.10336z"}), Ie("path",{d:"M838.683648 371.395584H623.194112c-18.074624 0-32.700416-14.625792-32.700416-32.700416s14.625792-32.700416 32.700416-32.700416h209.294336V96.700416c0-18.074624 14.625792-32.700416 32.700416-32.700416s32.700416 14.625792 32.700416 32.700416v215.489536c-0.001024 32.635904-26.569728 59.205632-59.205632 59.205632z"})]}),$e=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:Ie("line",{x1:"5",y1:"12",x2:"19",y2:"12"})}),Ue=({size:e=18,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:[ Ie("path",{d:"M192 192m32 0l0 0q32 0 32 32l0 640q0 32-32 32l0 0q-32 0-32-32l0-640q0-32 32-32Z",fill:t}), Ie("path",{d:"M192 832m32 0l256 0q32 0 32 32l0 0q0 32-32 32l-256 0q-32 0-32-32l0 0q0-32 32-32Z",fill:t}), Ie("path",{d:"M192 512m32 0l256 0q32 0 32 32l0 0q0 32-32 32l-256 0q-32 0-32-32l0 0q0-32 32-32Z",fill:t}), Ie("path",{d:"M448 192m64 0l320 0q64 0 64 64l0 0q0 64-64 64l-320 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Ie("path",{d:"M640 480m64 0l128 0q64 0 64 64l0 0q0 64-64 64l-128 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Ie("path",{d:"M640 768m64 0l128 0q64 0 64 64l0 0q0 64-64 64l-128 0q-64 0-64-64l0 0q0-64 64-64Z",fill:t}), Ie("path",{d:"M224 224m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0Z",fill:t})]}),je=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}), Ie("polyline",{points:"14 2 14 8 20 8"}), Ie("line",{x1:"16",y1:"13",x2:"8",y2:"13"}), Ie("line",{x1:"16",y1:"17",x2:"8",y2:"17"}), Ie("line",{x1:"10",y1:"9",x2:"8",y2:"9"})]}),He=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block"},children:Ie("path",{fill:t,stroke:t,strokeWidth:"0.3",d:"M19.75 6.5a.75.75 0 0 1-.75-.75V5h-.75a.75.75 0 0 1 0-1.5H19v-.75a.75.75 0 0 1 1.5 0v.75h.75a.75.75 0 0 1 0 1.5h-.75v.75a.75.75 0 0 1-.75.75M8.799 3.728a.34.34 0 0 1 .1-.18c.046-.04.082-.048.102-.048s.056.007.102.049a.34.34 0 0 1 .1.178a6.57 6.57 0 0 0 1.767 3.304a6.55 6.55 0 0 0 3.303 1.767c.07.014.135.053.178.1c.042.046.049.082.049.102s-.007.056-.049.102a.34.34 0 0 1-.178.1a6.56 6.56 0 0 0-3.303 1.768a6.56 6.56 0 0 0-1.766 3.302a.34.34 0 0 1-.101.18c-.046.04-.082.048-.102.048s-.056-.007-.102-.049a.34.34 0 0 1-.1-.178a6.57 6.57 0 0 0-1.767-3.304a6.55 6.55 0 0 0-3.303-1.767a.34.34 0 0 1-.179-.1c-.04-.047-.048-.082-.049-.102c0-.02.008-.056.049-.101a.34.34 0 0 1 .18-.102a6.56 6.56 0 0 0 3.302-1.766a6.56 6.56 0 0 0 1.767-3.303M9 2c-.883 0-1.52.695-1.67 1.422A5.06 5.06 0 0 1 5.97 5.97a5.06 5.06 0 0 1-2.546 1.36c-.728.15-1.424.788-1.423 1.673c.002.882.697 1.517 1.423 1.668a5.05 5.05 0 0 1 2.547 1.358c.87.871 1.22 1.88 1.359 2.549C7.48 15.305 8.118 16 9 16c.885 0 1.521-.695 1.672-1.423a5.06 5.06 0 0 1 1.358-2.546a5.06 5.06 0 0 1 2.548-1.36c.727-.15 1.422-.787 1.422-1.67c0-.885-.695-1.521-1.423-1.672a5.05 5.05 0 0 1-2.546-1.359a5.06 5.06 0 0 1-1.359-2.548C10.521 2.695 9.885 2 9.002 2M9.5 16.954v1.796c0 .966.784 1.75 1.75 1.75h7.5a1.75 1.75 0 0 0 1.75-1.75v-7.5a1.75 1.75 0 0 0-1.75-1.75h-1.796a2.7 2.7 0 0 0-.15-1.5h1.946A3.25 3.25 0 0 1 22 11.25v7.5A3.25 3.25 0 0 1 18.75 22h-7.5A3.25 3.25 0 0 1 8 18.75v-1.946a2.7 2.7 0 0 0 1.5.15M12 13.75a.75.75 0 0 1 .75-.75h5.5a.75.75 0 0 1 0 1.5h-5.5a.75.75 0 0 1-.75-.75m.75 2.25a.75.75 0 0 0 0 1.5h3.5a.75.75 0 0 0 0-1.5zm-10 3a.75.75 0 0 0 0 1.5h.75v.75a.75.75 0 0 0 1.5 0v-.75h.75a.75.75 0 0 0 0-1.5H5v-.75a.75.75 0 0 0-1.5 0V19z"})}),We=({size:e=16,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ Ie("path",{fill:t,d:"M128 256m42.666667 0l682.666666 0q42.666667 0 42.666667 42.666667l0 0q0 42.666667-42.666667 42.666666l-682.666666 0q-42.666667 0-42.666667-42.666666l0 0q0-42.666667 42.666667-42.666667Z"}), Ie("path",{fill:t,d:"M599.168 757.248a42.666667 42.666667 0 0 1-6.656-22.869333V461.653333a42.666667 42.666667 0 0 1 64.981333-36.352l218.154667 134.058667a42.666667 42.666667 0 0 1 0.554667 72.362667l-218.154667 138.666666a42.666667 42.666667 0 0 1-58.88-13.141333z m78.677333-100.522667l95.018667-60.373333-95.018667-58.368v118.741333z"}), Ie("path",{fill:t,d:"M128 469.333333m42.666667 0l256 0q42.666667 0 42.666666 42.666667l0 0q0 42.666667-42.666666 42.666667l-256 0q-42.666667 0-42.666667-42.666667l0 0q0-42.666667 42.666667-42.666667Z"}), Ie("path",{fill:t,d:"M128 682.666667m42.666667 0l256 0q42.666667 0 42.666666 42.666666l0 0q0 42.666667-42.666666 42.666667l-256 0q-42.666667 0-42.666667-42.666667l0 0q0-42.666667 42.666667-42.666666Z"})]}),Ge=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}), Ie("circle",{cx:"9",cy:"11",r:"1",fill:t,stroke:"none"}), Ie("circle",{cx:"12",cy:"11",r:"1",fill:t,stroke:"none"}), Ie("circle",{cx:"15",cy:"11",r:"1",fill:t,stroke:"none"})]}),Qe=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), Ie("polyline",{points:"7 10 12 15 17 10"}), Ie("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),Ve=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}), Ie("polyline",{points:"17 8 12 3 7 8"}), Ie("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),Ke="M12 3v12",Ze="m7 10 5 5 5-5",Ye="M5 21h14",Je=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("circle",{cx:"12",cy:"12",r:"10"}), Ie("line",{x1:"12",y1:"8",x2:"12",y2:"16"}), Ie("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),Xe=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("circle",{cx:"12",cy:"12",r:"10"}), Ie("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),et=({size:e=18,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"})}),tt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Ie("polyline",{points:"5 12 12 5 19 12"})]}),nt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("line",{x1:"12",y1:"5",x2:"12",y2:"19"}), Ie("polyline",{points:"19 12 12 19 5 12"})]}),rt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73v.18a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.38a2 2 0 0 0-.73-2.73l-.15-.1a2 2 0 0 1-1-1.72v-.51a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"})}),ot=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M13.5 10.5L21 3 M16 3h5v5 M2 21h5 M12 21a9 9 0 0 0 9-9 9 9 0 0 0-9-9 9 9 0 0 0-9 9c0 4.97 4.03 9 9 9z"})}),it=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:Ie("path",{d:"M553.79358 660.032655v-121.03257a19.643494 19.643494 0 0 1 9.872902-17.085748l370.924415-213.827617a40.054312 40.054312 0 0 0 0-69.468399L553.844735 19.521745 529.597297 5.402984a40.105467 40.105467 0 0 0-60.158201 34.734199v600.916992a19.796959 19.796959 0 0 1-18.97848 19.745804c-217.561928 8.952113-430.673377 66.501412-430.673377 180.832687 0 125.227275 254.649254 181.80463 491.752367 181.80463s491.956986-56.577355 491.956986-181.90694c0-117.656345-225.900182-175.103334-449.805322-181.446546z m30.38603-525.412312l211.014096 121.3395a19.745804 19.745804 0 0 1 0 34.22265l-211.014096 121.953359a19.745804 19.745804 0 0 1-29.669861-17.085747V151.706091a19.745804 19.745804 0 0 1 29.669861-17.085748z m232.601478 765.226636a1211.655731 1211.655731 0 0 1-610.12488 0c-83.68947-25.986706-101.95178-53.149975-101.951781-58.316623s18.313466-32.278762 101.951781-58.418933a992.405691 992.405691 0 0 1 242.320915-37.598876 19.745804 19.745804 0 0 1 20.461973 19.694649v79.187836a19.745804 19.745804 0 0 0 19.796959 19.745804h44.658256a19.796959 19.796959 0 0 0 19.796959-19.745804v-79.187836a19.745804 19.745804 0 0 1 20.461973-19.745803 992.405691 992.405691 0 0 1 242.37207 37.65003c83.638315 26.037861 101.696006 52.99651 101.696006 58.316623s-18.057691 32.381072-101.696006 58.418933z",fill:t})}),at=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z M3.27 6.96L12 12.01l8.73-5.05 M12 22.08V12"})}),st=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},children:[ Ie("path",{d:"M511.5 119.3l366.8 168.8c-0.4 14.7-1.6 35-4.5 60.2-5.9 52.4-20.6 137.5-56.7 245.4-23 68.8-86.3 145.9-183.1 222.9-48.8 38.9-95.1 68.8-122.2 85.3-26.6-16.9-71.8-47.1-119.7-86.2-95.6-78-159-155.6-183.5-224.5-38.5-108.6-53.1-192.1-58.5-243.1-2.6-24.8-3.4-44.5-3.5-58.7l364.9-170.1m-0.2-55.1L98 257s-16 126.8 63.6 351c67.6 190.3 349.8 352.3 349.8 352.3s289.2-159 353.2-350.6C938.3 388.8 928 256 928 256L511.3 64.2z",fill:t}), Ie("path",{d:"M511.3 273.3c25.4 0 46.1 20.7 46.1 46.1s-20.7 46.1-46.1 46.1c-25.4 0-46.1-20.7-46.1-46.1s20.7-46.1 46.1-46.1m0-50c-53.1 0-96.1 43-96.1 96.1s43 96.1 96.1 96.1 96.1-43 96.1-96.1-43-96.1-96.1-96.1z",fill:t}), Ie("path",{d:"M486.3 383.8h50v384h-50z",fill:t}), Ie("path",{d:"M513 599h94.5v50H513zM513 717h94.5v50H513z",fill:t})]}),lt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z M12 16v-4 M12 8h.01"})}),ct=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"})}),dt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2z M2 12h20 M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})}),ut=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"})}),ht=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z M9 12l2 2 4-4"})}),gt=({size:e=20,color:t="currentColor",className:n="",style:r,filled:o=false})=>Ie("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:Ie("polygon",{points:"512,64 625,357 968,364 695,571 794,901 512,704 230,901 329,571 56,364 399,357",fill:o?t:"none",stroke:t,strokeWidth:96,strokeLinejoin:"round"})}),pt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}),mt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},fill:t,children:[ Ie("path",{d:"M518.3 459c-3.2-4.1-9.4-4.1-12.6 0l-112 141.7c-4.1 5.2-0.4 12.9 6.3 12.9h73.9V856c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V613.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 459z"}), Ie("path",{d:"M811.4 366.7C765.6 245.9 648.9 160 512.2 160S258.8 245.8 213 366.6C127.3 389.1 64 467.2 64 560c0 110.5 89.5 200 199.9 200H304c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8h-40.1c-33.7 0-65.4-13.4-89-37.7-23.5-24.2-36-56.8-34.9-90.6 0.9-26.4 9.9-51.2 26.2-72.1 16.7-21.3 40.1-36.8 66.1-43.7l37.9-9.9 13.9-36.6c8.6-22.8 20.6-44.1 35.7-63.4 14.9-19.2 32.6-35.9 52.4-49.9 41.1-28.9 89.5-44.2 140-44.2s98.9 15.3 140 44.2c19.9 14 37.5 30.8 52.4 49.9 15.1 19.3 27.1 40.7 35.7 63.4l13.8 36.5 37.8 10C846.1 454.5 884 503.8 884 560c0 33.1-12.9 64.3-36.3 87.7-23.4 23.4-54.5 36.3-87.6 36.3H720c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h40.1C870.5 760 960 670.5 960 560c0-92.7-63.1-170.7-148.6-193.3z"})]}),ft=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ Ie("circle",{cx:12,cy:12,r:10}), Ie("line",{x1:12,y1:16,x2:12,y2:12}), Ie("line",{x1:12,y1:8,x2:12.01,y2:8})]}),bt=({size:e=16,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,...r},children:[ Ie("rect",{x:"100",y:"282",width:"824",height:"80",rx:"40",fill:t}), Ie("rect",{x:"100",y:"472",width:"824",height:"80",rx:"40",fill:t}), Ie("rect",{x:"100",y:"662",width:"824",height:"80",rx:"40",fill:t})]}),yt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"})}),vt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"})}),wt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6zm10 14.5V20H8v-3.5l4-4 4 4zm-4-5l-4-4V4h8v3.5l-4 4z"})}),xt=({size:e=18,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"})}),kt=({size:e=20,className:t=""})=>Le("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ Ie("path",{d:"M15 3h6v6"}), Ie("path",{d:"M9 21H3v-6"}), Ie("path",{d:"M21 3l-7 7"}), Ie("path",{d:"M3 21l7-7"})]}),St=({size:e=20,className:t=""})=>Le("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[ Ie("path",{d:"M4 14h6v6"}), Ie("path",{d:"M20 10h-6V4"}), Ie("path",{d:"M14 10l7-7"}), Ie("path",{d:"M3 21l7-7"})]}),Ct=({size:e=20,className:t=""})=>Ie("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,children:Ie("path",{d:"M606.72 304.64V235.52H346.624l51.712-16.384c-7.168-24.576-25.088-62.464-40.448-90.112l-76.288 22.016c13.824 26.624 27.136 59.904 33.792 84.48H62.976v69.12h94.208C189.44 388.608 230.4 460.8 284.16 519.68c-61.952 48.128-139.264 82.432-232.448 105.984 14.336 15.872 35.328 49.152 43.008 66.048 96.256-27.648 176.128-67.072 242.176-120.832 62.464 52.736 139.776 92.16 233.472 117.248 10.752-19.968 31.744-50.688 47.616-66.048-89.088-20.992-164.352-55.808-225.792-103.424 52.224-57.856 92.672-128 122.88-214.016h91.648z m-171.52 0a474.624 474.624 0 0 1-97.28 165.376c-46.08-47.104-81.92-102.4-107.52-165.376h204.8z m237.568 622.08h-90.112l141.824-414.72h104.448l142.848 414.72h-93.184l-31.232-106.496h-143.872l-30.72 106.496z m100.864-351.744c-11.264 45.568-24.576 92.672-37.888 135.68l-12.8 45.568h105.472l-13.312-45.568c-13.824-43.008-28.672-90.624-41.472-135.68z",fill:"currentColor"})}),At=({size:e=20,className:t="",style:n})=>Ie("svg",{width:e,height:e,viewBox:"0 0 1024 1024",version:"1.1",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",className:t,style:n,children:Ie("path",{d:"M512 136.83c-206.88 0-375.17 168.31-375.17 375.17S305.12 887.17 512 887.17 887.17 718.86 887.17 512 718.88 136.83 512 136.83z m265.73 202h-85.94c-12.32-44.9-29.26-84.4-49.88-116.19a319.22 319.22 0 0 1 135.82 116.2zM656.3 512a625.41 625.41 0 0 1-10.54 115.44H378.24a637.45 637.45 0 0 1 0-230.88h267.52A625.41 625.41 0 0 1 656.3 512zM512 829.45c-44.2 0-91.56-54.92-119.52-144.29h239C603.56 774.53 556.2 829.45 512 829.45zM392.48 338.84c28-89.37 75.32-144.29 119.52-144.29s91.56 54.92 119.52 144.29z m-10.39-116.19c-20.62 31.79-37.56 71.29-49.88 116.19h-85.94a319.22 319.22 0 0 1 135.82-116.19z m-165.5 173.91h102.85a709.08 709.08 0 0 0 0 230.88H216.59a313.34 313.34 0 0 1 0-230.88z m29.68 288.6h85.94c12.32 44.9 29.26 84.4 49.88 116.19a319.22 319.22 0 0 1-135.82-116.19z m395.64 116.19c20.62-31.79 37.56-71.29 49.88-116.19h85.94a319.22 319.22 0 0 1-135.82 116.19z m165.5-173.91H704.56a709.08 709.08 0 0 0 0-230.88h102.85a313.34 313.34 0 0 1 0 230.88z",fill:"currentColor"})}),Et=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:[ Ie("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",ry:"2"}), Ie("line",{x1:"6",y1:"8",x2:"6",y2:"8"}), Ie("line",{x1:"10",y1:"8",x2:"10",y2:"8"}), Ie("line",{x1:"14",y1:"8",x2:"14",y2:"8"}), Ie("line",{x1:"18",y1:"8",x2:"18",y2:"8"}), Ie("line",{x1:"6",y1:"12",x2:"6",y2:"12"}), Ie("line",{x1:"10",y1:"12",x2:"10",y2:"12"}), Ie("line",{x1:"14",y1:"12",x2:"14",y2:"12"}), Ie("line",{x1:"18",y1:"12",x2:"18",y2:"12"}), Ie("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]}),Tt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}), Ie("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),Mt=({size:e=16,className:t="",...n})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"none",strokeLinecap:"round",strokeLinejoin:"round",className:`more-horizontal-icon ${t}`,style:{display:"block",width:e,height:e},...n,children:[ Ie("circle",{cx:"12",cy:"12",r:"1.5",className:"dot dot-2"}), Ie("circle",{cx:"19",cy:"12",r:"1.5",className:"dot dot-3"}), Ie("circle",{cx:"5",cy:"12",r:"1.5",className:"dot dot-1"}), Ie("style",{children:"\n .more-horizontal-icon .dot {\n transform-box: fill-box;\n transform-origin: center;\n animation: dot-jump 3s infinite;\n }\n .more-horizontal-icon .dot-1 {\n animation-delay: 0s;\n }\n .more-horizontal-icon .dot-2 {\n animation-delay: 0.1s;\n }\n .more-horizontal-icon .dot-3 {\n animation-delay: 0.2s;\n }\n @keyframes dot-jump {\n 0%, 90%, 100% { transform: translateY(0); }\n 5% { transform: translateY(-3px); }\n 10% { transform: translateY(0); }\n }\n "})]}),_t=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M18 15l-6-6-6 6"})}),It=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",...r},children:Ie("path",{d:"M6 9l6 6 6-6"})}),Lt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Ie("path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"}), Ie("path",{d:"m14.5 9-5 5"}), Ie("path",{d:"m9.5 9 5 5"})]}),Nt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Ie("path",{d:"M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z"}), Ie("path",{d:"M7 7h.01"})]}),Dt=({size:e=24,className:t,color:n="currentColor"})=>Le("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ Ie("circle",{cx:"12",cy:"12",r:"10"}), Ie("circle",{cx:"12",cy:"12",r:"4"}), Ie("line",{x1:"21.17",x2:"12",y1:"8",y2:"8"}), Ie("line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14"}), Ie("line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14"})]}),qt=({size:e=24,className:t,color:n="currentColor"})=>Ie("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:Ie("path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4"})}),Rt=({size:e=24,className:t,color:n="currentColor"})=>Le("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:t,style:{color:n},children:[ Ie("path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"}), Ie("polyline",{points:"14 2 14 8 20 8"}), Ie("path",{d:"m9 15 2 2 4-4"})]}),Pt=({size:e=24,className:t})=>Le("svg",{width:e,height:e,viewBox:"0 0 48 48",className:t,children:[ Ie("path",{fill:"#1e88e5",d:"M40.69,35.42c-9.15,11.88-21.41,8.8-26.23,6.1 c-7.35-4.11-12.5-13.68-9.44-23.25c0.9-2.82,2.27-5.23,3.98-7.23c1.67,0.13,3.65,0.13,6-0.04c14-1,18,11,17,14 c-0.51,1.53-2.32,2.02-3.97,2.13c0.16-0.22,0.36-0.54,0.64-1.02c0.87-1.54,0.98-4.49-1.73-6.27c-2.61-1.7-5.43-0.65-6.88,1.28 c-1.45,1.92-0.88,4.81-0.37,6.09c2.2,5.52,6.26,6.95,9.02,7.78c2.76,0.83,6.86,0.71,9.05-0.19c2.18-0.91,2.8-1.43,3.22-0.97 C41.41,34.29,41.11,34.82,40.69,35.42z"}), Ie("path",{fill:"#0d47a1",d:"M40.732,35.42c-3.48,4.52-7.41,6.87-11.21,7.91 c-0.03,0.01-0.06,0.01-0.08,0.02c-2.2,0.42-3.95,0.08-5.85-0.29c-3.09-0.6-7.35-4.01-8.38-10.18c-0.88-5.31,1.63-9.81,5.59-12.54 c-0.26,0.24-0.49,0.5-0.7,0.78c-1.45,1.92-0.88,4.81-0.37,6.09c2.2,5.52,6.26,6.95,9.02,7.78c2.76,0.83,6.86,0.71,9.05-0.19 c2.18-0.91,2.8-1.43,3.22-0.97C41.452,34.29,41.152,34.82,40.732,35.42z"}), Ie("path",{fill:"#00e5ff",d:"M26.94,4.25c0.02,0.26,0.03,0.54,0.03,0.81c0,3.78-1.75,7.14-4.48,9.32 c-1.02-0.52-2.21-0.94-3.65-1.22c-4.07-0.78-10.63,1.1-13.3,5.77c-0.88,1.53-1.25,3.1-1.41,4.55c0.04-1.71,0.33-3.46,0.89-5.21 C8.31,8.01,17.86,3.05,26.94,4.25z"}), Ie("path",{fill:"#00e676",d:"M41.4,27.89c-2.76,2.78-6.27,2.86-8.67,2.73 c-2.41-0.12-3.59-0.82-4.69-1.5c-1.11-0.69-0.48-1.37-0.37-1.52c0.11-0.15,0.38-0.41,1-1.49c0.29-0.51,0.5-1.18,0.54-1.91 c4.62-3.43,7.96-8.49,9.16-14.34c2.92,2.95,4.3,6.21,4.79,7.61C44.04,19.99,44.71,24.56,41.4,27.89z"}), Ie("path",{fill:"#1de9b6",d:"M38.37,9.85v0.01c-1.2,5.85-4.54,10.91-9.16,14.34c0.03-0.42,0-0.87-0.1-1.32 c0-0.02-0.01-0.04-0.01-0.05c-0.25-1.47-0.99-3.33-2.22-4.77c-1.22-1.44-2.52-2.73-4.39-3.68c2.73-2.18,4.48-5.54,4.48-9.32 c0-0.27-0.01-0.55-0.03-0.81c0.4,0.05,0.79,0.11,1.19,0.19C32.74,5.33,36.04,7.49,38.37,9.85z"})]}),zt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), Ie("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),Bt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("polyline",{points:"3 6 5 6 21 6"}), Ie("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}), Ie("line",{x1:"10",y1:"11",x2:"10",y2:"17"}), Ie("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]}),Ot=({size:e=18,color:t="currentColor",className:n="",filled:r=false,style:o})=>Ie("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...o},children: Ie("path",r?{d:"M307.370667 416l54.314666 54.314667-77.056 77.056a4.266667 4.266667 0 0 0 2.986667 7.296h158.421333l1.962667 1.962666V844.8c0 4.693333 3.84 8.533333 8.533333 8.533333h110.933334a8.533333 8.533333 0 0 0 8.533333-8.533333v-160.170667l76.8 76.8V844.8a85.333333 85.333333 0 0 1-85.333333 85.333333h-110.933334a85.333333 85.333333 0 0 1-85.333333-85.333333v-213.333333H287.616c-72.192 0-108.373333-87.296-57.301333-138.368L307.370667 416z m432.64 215.381333L663.296 554.666667h73.088a4.266667 4.266667 0 0 0 2.986667-7.253334l-221.354667-221.354666a8.533333 8.533333 0 0 0-12.032 0l-35.669333 35.626666L416 307.413333l35.669333-35.669333a85.333333 85.333333 0 0 1 120.661334 0l221.354666 221.354667c50.218667 50.176 16.085333 135.424-53.674666 138.282666zM207.530667 207.530667a38.4 38.4 0 0 1 54.272 0l554.666666 554.666666a38.4 38.4 0 1 1-54.272 54.272l-554.666666-554.666666a38.4 38.4 0 0 1 0-54.272zM217.6 128a38.4 38.4 0 0 1 38.4-38.4h512a38.4 38.4 0 1 1 0 76.8H256a38.4 38.4 0 0 1-38.4-38.4z",fill:t}:{d:"M576 554.666667h160.341333a4.266667 4.266667 0 0 0 3.029334-7.253334l-2.986667-3.072-48.341333-48.298666-18.176-18.176-151.850667-151.850667a8.533333 8.533333 0 0 0-12.032 0L354.133333 477.866667l-18.176 18.176L287.573333 544.426667l-2.986666 2.986666a4.266667 4.266667 0 0 0 2.986666 7.253334H448v290.133333c0 4.736 3.84 8.533333 8.533333 8.533333h110.933334a8.533333 8.533333 0 0 0 8.533333-8.533333V554.666667z m160.384 76.8H652.8v213.333333a85.333333 85.333333 0 0 1-85.333333 85.333333h-110.933334a85.333333 85.333333 0 0 1-85.333333-85.333333v-213.333333H287.616c-72.192 0-108.373333-87.338667-57.301333-138.410667l221.354666-221.312a85.333333 85.333333 0 0 1 120.661334 0l221.354666 221.312c51.072 51.072 14.933333 138.410667-57.301333 138.410667zM256 89.6a38.4 38.4 0 0 0 0 76.8h512a38.4 38.4 0 1 0 0-76.8H256z",fill:t})}),Ft=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}), Ie("circle",{cx:"12",cy:"12",r:"3"})]}),$t=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M2 8a10.645 10.645 0 0 0 20 0"}), Ie("path",{d:"m4 15 1.726-2.05"}), Ie("path",{d:"m9 18 .722-3.25"}), Ie("path",{d:"m15 18-.722-3.25"}), Ie("path",{d:"m20 15-1.726-2.05"})]}),Ut=({size:e=16,className:t="",...n})=>Ie("svg",{"aria-hidden":"true",focusable:"false",viewBox:"0 0 16 16",width:e,height:e,fill:"currentColor",display:"inline-block",overflow:"visible",className:t,style:{display:"block",width:e,height:e,verticalAlign:"middle"},...n,children:Ie("path",{d:"M14.85 3c.63 0 1.15.52 1.14 1.15v7.7c0 .63-.51 1.15-1.15 1.15H1.15C.52 13 0 12.48 0 11.84V4.15C0 3.52.52 3 1.15 3ZM9 11V5H7L5.5 7 4 5H2v6h2V8l1.5 1.92L7 8v3Zm2.99.5L14.5 8H13V5h-2v3H9.5Z"})}),jt=({size:e=16,className:t="",...n})=>Le("svg",{viewBox:"0 0 1024 1024",xmlns:"http://www.w3.org/2000/svg",width:e,height:e,fill:"currentColor",className:t,style:{display:"block",width:e,height:e},...n,children:[ Ie("path",{d:"M1008 464h-72c-4.4 0-8-3.6-8-8V314.5c0-17-6.7-33.3-18.7-45.3L658.7 18.7C646.7 6.7 630.5 0 613.5 0H144c-26.5 0-48 21.5-48 48v408c0 4.4-3.6 8-8 8H16c-8.8 0-16 7.2-16 16v400c0 8.8 7.2 16 16 16h80c0 35.3 14.3 67.3 37.5 90.5 23.2 23.2 55.2 37.5 90.5 37.5h656c26.5 0 48-21.5 48-48v-64c0-8.8 7.2-16 16-16h64c8.8 0 16-7.2 16-16V480c0-8.8-7.2-16-16-16zM704 154.5l69.5 69.5H708c-2.2 0-4-1.8-4-4v-65.5zM160 72c0-4.4 3.6-8 8-8h408c35.3 0 64 28.7 64 64v144c0 8.8 7.2 16 16 16h144c35.3 0 64 28.7 64 64v104c0 4.4-3.6 8-8 8H168c-4.4 0-8-3.6-8-8V72z m492.3 603.5c0 32.5-9.5 58.9-28.4 79.1-18.9 20.3-43.7 30.4-74.3 30.4-29.9 0-54.2-9.8-72.9-29.4-18.5-19.6-27.9-44.9-27.9-75.8 0-32.7 9.5-59.3 28.6-79.8s44.3-30.8 75.6-30.8c29.8 0 53.8 9.9 72 29.8 18.2 19.8 27.3 45.4 27.3 76.5z m-365.9 53.3c16.9 13.9 35.9 20.9 57.3 20.9 12.1 0 21.2-2.1 27.3-6.3 6.1-4.2 9.2-9.5 9.2-16.1 0-5.7-2.4-11-7.3-16s-17.6-11.9-38.4-20.5c-32.6-13.8-48.9-33.9-48.9-60.4 0-19.4 7.4-34.5 22.2-45.2s34.3-16.1 58.7-16.1c20.4 0 37.5 2.7 51.3 7.9v41.8c-14-9.5-30.4-14.3-49.2-14.3-11 0-19.7 2-26.3 6-6.6 4-9.8 9.4-9.8 16.1 0 5.4 2.2 10.4 6.7 14.9s15.6 10.7 33.3 18.4c20.7 8.9 35 18.3 42.8 28.2 7.8 9.9 11.7 21.6 11.7 35.3 0 20-7.1 35.3-21.3 45.8S371.3 785 345.2 785c-23.9 0-43.5-3.9-58.7-11.6l-0.1-44.6c0.1 0 0 0 0 0z m-139.6 8.9c7.7 5.8 16.5 8.8 26.4 8.8 21.4 0 32.1-16.2 32.1-48.6V572.7h44.5v126.8h-0.1c0 27.6-6.4 48.7-19.1 63.5-12.7 14.6-30.9 22-54.6 22-10.5 0-20.3-1.8-29.2-5.4v-41.9zM864 952c0 4.4-3.6 8-8 8H224c-35.3 0-64-28.7-64-64h696c4.4 0 8 3.6 8 8v48z m9.2-170.6h-45.5l-88.4-135c-4.6-7-7.9-12.7-10-17h-0.7c0.8 7.2 1.2 18.3 1.2 33.3v118.7h-42.2V572.7h48.5l85.1 131.2c5.7 8.7 9.1 14.2 10.4 16.6h0.7c-0.9-5-1.3-14.6-1.3-28.8v-119h42.2v208.7zM286.5 728.8s-0.1 0 0 0z"}), Ie("path",{d:"M605.8 678.2c0 20.9-4.8 37.5-14.5 49.8s-23.3 18.5-40.7 18.5c-17.1 0-30.5-6.4-40.3-19.3-9.8-12.9-14.7-29.5-14.7-49.8 0-20.6 5-37.3 15-50.2 10.1-12.9 23.8-19.4 41.2-19.4 17.2 0 30.5 6.3 39.9 18.9 9.4 12.6 14.1 29.8 14.1 51.5z"})]}),Ht=({size:e=16,className:t="",...n})=>Le("svg",{viewBox:"0 0 1024 1024",xmlns:"http://www.w3.org/2000/svg",width:e,height:e,fill:"currentColor",className:t,style:{display:"block",width:e,height:e},...n,children:[ Ie("path",{d:"M899.072 403.968h-14.336V275.456c0-8.192-3.072-16.384-9.216-22.016L624.128 11.776c-6.144-5.632-13.312-8.704-21.504-8.704h-465.92C89.088 3.072 50.688 41.472 50.688 89.088v845.824c0 47.616 38.4 86.016 86.016 86.016h662.528c22.528 0 45.056-9.216 60.928-25.6 16.384-16.384 25.088-37.888 24.576-60.416v-60.416h14.848c22.528 0 43.52-8.704 59.392-25.088 15.872-15.872 24.576-36.864 24.064-58.88V487.936c0-46.08-37.888-83.968-83.968-83.968z m-292.864-324.096l185.856 178.176-185.856-4.608V79.872z m217.088 855.04c0.512 6.656-2.048 12.8-6.656 17.408-4.608 4.608-10.752 7.168-17.408 7.168H136.704c-13.312 0-24.576-11.264-24.576-24.576V89.088c0-13.312 11.264-24.576 24.576-24.576h408.064v219.136c0 16.896 12.8 30.208 29.696 30.72l248.832 6.144v83.456h-527.36c-46.08 0-83.968 37.888-83.968 83.968v302.592c0 46.08 37.888 83.968 83.968 83.968h527.36v60.416z m98.304-144.384c0 6.144-2.048 11.776-6.144 15.872s-9.728 6.656-15.872 6.656H295.936c-12.288 0-22.528-10.24-22.528-22.528V487.936c0-12.288 10.24-22.528 22.528-22.528h603.136c12.288 0 22.528 10.24 22.528 22.528v302.592z"}), Ie("path",{d:"M309.76 600.064h59.392v132.608h58.88v-132.608h59.904v-43.52H309.76zM696.832 556.544h-64l-32.768 54.272-33.792-54.272H501.76l59.392 83.968L495.616 732.16h66.048l37.376-56.32 37.376 56.32h66.048l-64.512-90.624zM707.072 556.544v43.52h59.904v132.608h58.88v-132.608H885.76v-43.52h-178.176z"})]}),Wt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("circle",{cx:"11",cy:"11",r:"8"}), Ie("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),Gt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("circle",{cx:"12",cy:"12",r:"10"}), Ie("polyline",{points:"12 6 12 12 16 14"})]}),Qt=({size:e=18,color:t,className:n="",style:r})=>{const i=`sparkle-gradient-${o.useId().replace(/:/g,"")}`,a=!t||"brand"===t,s=a?`url(#${i})`:t,l="number"==typeof e?1.25*e:e; return Le("svg",{viewBox:"0 0 1024 1024",width:l,height:l,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0,overflow:"visible",transform:"translateY(1px)",filter:a?"drop-shadow(0px 2px 6px rgba(34, 211, 238, 0.4))":"none",...r},children:[ Ie("defs",{children:a&&Le("linearGradient",{id:i,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[ Ie("stop",{offset:"0%",stopColor:"#22d3ee"}), Ie("stop",{offset:"100%",stopColor:"#6366f1"})]})}), Le("g",{style:{fill:s,stroke:s,strokeWidth:12,strokeLinejoin:"round",strokeLinecap:"round"},children:[ Ie("path",{d:"M380.77 475.76c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.2 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.986 4.986 0 0 1-4.84 3.79z m-41.69-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7L380.66 367l-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM513.43 939.45h-0.04c-8-0.02-14.96-5.46-16.93-13.21L415.8 607.36l-319.06-98.3a17.495 17.495 0 0 1-12.32-17.7c0.45-8.03 6.32-14.72 14.22-16.22l191.92-36.28c9.5-1.8 18.65 4.45 20.45 13.95s-4.45 18.65-13.94 20.45l-122.51 23.16 260.96 80.4c5.84 1.8 10.31 6.51 11.81 12.43l66.26 261.97 46.87-181.85c2.41-9.36 11.95-14.99 21.31-12.58s14.99 11.95 12.58 21.31l-63.97 248.22c-2 7.73-8.97 13.13-16.95 13.13zM826.61 540.39c-7.44 0-14.35-4.79-16.69-12.27-2.89-9.22 2.24-19.04 11.46-21.94l31.03-9.73-261.1-49.94a17.496 17.496 0 0 1-13.69-12.96l-65.07-260.98-47.06 190.3c-2.32 9.38-11.8 15.11-21.19 12.79-9.38-2.32-15.11-11.81-12.79-21.19l63.97-258.72a17.497 17.497 0 0 1 16.97-13.3h0.02c8.03 0 15.04 5.47 16.98 13.27l79.41 318.52 318.43 60.91a17.5 17.5 0 0 1 14.18 16.18c0.46 8.01-4.58 15.3-12.23 17.7l-97.39 30.55c-1.74 0.55-3.5 0.81-5.24 0.81zM842.91 908.24c-2.29 0-4.29-1.55-4.85-3.77l-11.9-47.04-47.08-14.51a5.002 5.002 0 0 1-3.52-5.05c0.13-2.29 1.8-4.21 4.05-4.64l46.76-8.95 11.53-46.79c0.55-2.23 2.55-3.8 4.85-3.8h0.01c2.3 0 4.3 1.56 4.85 3.79l11.67 46.8 46.77 8.95c2.26 0.43 3.93 2.34 4.05 4.64a4.994 4.994 0 0 1-3.52 5.05l-47.07 14.5-11.76 47.03a4.975 4.975 0 0 1-4.84 3.79z m-41.68-68.96l30.57 9.42a5 5 0 0 1 3.38 3.55l7.71 30.49 7.62-30.47a5.01 5.01 0 0 1 3.38-3.57l30.57-9.42-30.18-5.77a5.006 5.006 0 0 1-3.91-3.7l-7.56-30.33-7.47 30.32c-0.47 1.9-2 3.35-3.92 3.71l-30.19 5.77zM874.6 220.76c-1.85 0-3.73-0.3-5.58-0.93l-67.48-23.04c-4.37-1.49-7.9-4.6-9.94-8.76-2.04-4.16-2.34-8.85-0.85-13.22l23.05-67.47c3.09-9.03 12.95-13.87 21.98-10.79l67.48 23.04c4.37 1.49 7.9 4.6 9.94 8.76 2.04 4.16 2.34 8.85 0.85 13.22L891 209.04c-2.45 7.19-9.2 11.72-16.4 11.72z m0.88-19.86z m0 0z m-64.94-22.17l62.4 21.31 21.31-62.39-62.4-21.31-21.31 62.39zM147.92 229.91a9.91 9.91 0 0 1-3.34-0.58 9.982 9.982 0 0 1-6.49-7.61l-17.36-93.88c-0.65-3.51 0.62-7.11 3.34-9.43 2.72-2.32 6.47-3.01 9.83-1.82l89.99 31.91a9.982 9.982 0 0 1 6.49 7.61c0.65 3.51-0.62 7.11-3.34 9.43l-72.63 61.97a9.951 9.951 0 0 1-6.49 2.4z m-4.38-88.67l11.06 59.82 46.28-39.49-57.34-20.33zM170.16 908.56c-29.21 0-52.97-23.76-52.97-52.96s23.76-52.96 52.97-52.96 52.97 23.76 52.97 52.96-23.76 52.96-52.97 52.96z m0-85.92c-18.18 0-32.97 14.79-32.97 32.96 0 18.18 14.79 32.96 32.97 32.96s32.97-14.79 32.97-32.96c0-18.18-14.79-32.96-32.97-32.96z"}), Ie("path",{d:"M720.52 570.25c-4.83 0-9.57-2.33-12.46-6.63-4.62-6.88-2.79-16.2 4.08-20.82 59.91-40.27 107.08-81.41 136.42-118.97 27-34.56 36.95-64.05 28.02-83.02-9.9-21.04-43.7-32.21-95.17-31.46-55 0.81-127.81 15.68-205.01 41.87-7.84 2.66-16.36-1.54-19.02-9.38-2.66-7.84 1.54-16.36 9.38-19.02 81.25-27.57 155.32-42.6 214.21-43.46 81.98-1.2 112 25.81 122.76 48.69 9.9 21.04 12.46 57.94-31.53 114.26-31.26 40.03-80.82 83.39-143.33 125.4a15.005 15.005 0 0 1-8.35 2.54zM206.58 758.85c-19.37 0-36.69-1.63-51.82-4.9-32.77-7.08-54.56-21.65-64.74-43.3-12.12-25.77-6.13-57.5 17.79-94.3 20.83-32.03 55.73-67.88 100.95-103.69 6.49-5.14 15.93-4.05 21.07 2.45 5.14 6.49 4.05 15.93-2.45 21.07-42.7 33.81-75.35 67.19-94.42 96.53-12.3 18.91-25.02 45.57-15.8 65.17 12.64 26.87 65.89 37.07 142.46 27.28 84.33-10.77 188.04-43.64 292.05-92.54 9.16-4.31 18.36-8.76 27.37-13.24 7.42-3.69 16.42-0.67 20.11 6.74 3.69 7.42 0.67 16.42-6.74 20.11-9.2 4.58-18.61 9.14-27.97 13.54-106.76 50.2-213.66 83.99-301.01 95.15-20.52 2.62-39.51 3.93-56.85 3.93z"}), Ie("path",{d:"M598.89 616.45a16.71 16.71 0 1 0 33.42 0 16.71 16.71 0 1 0-33.42 0Z"}), Ie("path",{d:"M664.77 608.33h-18.14c-4.2 0-7.64-3.44-7.64-7.64v-18.14c0-4.2 3.44-7.64 7.64-7.64h18.14c4.2 0 7.64 3.44 7.64 7.64v18.14c0 4.2-3.44 7.64-7.64 7.64zM690.73 554.4l-12.28 21.27c-0.98 1.7 0.25 3.83 2.21 3.83h24.57c1.97 0 3.2-2.13 2.21-3.83l-12.28-21.27c-0.99-1.7-3.45-1.7-4.43 0z"})]})]})},Vt=({size:e=15,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 1024 1024",width:e,height:e,xmlns:"http://www.w3.org/2000/svg",className:n,style:{display:"block",flexShrink:0},children:Ie("path",{d:"M674.432 64c20.224 0 37.888 18.944 37.888 40.576v297.792h232.192c7.616 0 15.168 2.752 20.16 8.128a41.92 41.92 0 0 1 10.176 56.832l-295.36 473.728a34.688 34.688 0 0 1-30.272 18.944c-20.16 0-37.824-18.944-37.824-40.576V621.632h-232.32a27.584 27.584 0 0 1-20.16-8.128 41.92 41.92 0 0 1-10.048-56.832l295.296-473.728A34.688 34.688 0 0 1 674.432 64zM44.8 140.8h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z m0 640h358.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 0 1 0-89.6z m0-320h166.4a44.8 44.8 0 0 1 0 89.6H44.8a44.8 44.8 0 1 1 0-89.6z",fill:t})}),Kt=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:Ie("polyline",{points:"20 6 9 17 4 12"})}),Zt=({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block",width:e,height:e},children:[ Ie("line",{x1:"2",y1:"2",x2:"2",y2:"22"}), Ie("rect",{x:"6",y:"4",width:"16",height:"16",rx:"2"}), Ie("polyline",{points:"15 9 11 12 15 15"})]}),Yt=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",width:e,height:e},children:Ie("path",{d:"M701.312 579.84l132.288-238.08 83.712 12.032a32 32 0 0 0 27.2-54.272L703.168 58.176 698.88 54.528a32 32 0 0 0-50.048 30.848l12.16 83.84-237.632 131.712-7.808-3.648c-79.04-35.328-151.168-26.624-209.984 32.192l-3.712 4.48a32 32 0 0 0 3.712 40.768l145.664 145.664-239.552 325.888-2.944 4.672c-14.912 28.608 19.84 60.672 47.744 40l324.992-240.32 146.496 146.496a32 32 0 0 0 45.248 0c58.176-58.24 66.176-124.736 32.32-207.36l-4.224-9.92z m24.704-408.256l105.152 105.152-10.24-1.408a32 32 0 0 0-32.576 16.128L637.44 563.072a32 32 0 0 0-0.768 29.632l5.888 12.416c21.824 48.768 24.96 84.608 8.512 116.224l-3.136 5.248-140.672-140.672-4.48-3.776a32 32 0 0 0-37.12 0.64l-177.088 130.88 130.56-177.472 3.008-4.992a32 32 0 0 0-6.144-36.608L276.032 354.688l6.208-3.456c35.584-18.24 76.544-13.312 126.464 14.08a32 32 0 0 0 30.848-0.064l271.872-150.72a32 32 0 0 0 16.128-32.576l-1.536-10.368z",fill:t})}),Jt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"})}),Xt=({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 1024 1024",width:e,height:e,fill:t,className:n,style:{display:"block",...r},children:Ie("path",{d:"M1018.912 381.792c-32.992-174.304-207.328-195.968-207.328-195.968H30.816c-25.76 0-28.96 34.048-28.96 34.048s-3.488 312.48-0.928 504.416c7.008 103.424 110.336 114.016 110.336 114.016s352.736-0.992 510.56-2.08c104.032-18.176 114.464-109.472 113.408-159.328 185.696 10.24 316.672-120.8 283.68-295.072z m-471.968 149.792c-53.152 61.984-171.136 169.632-171.136 169.632s-5.152 5.088-13.216 0.992c-3.232-2.432-4.608-3.84-4.608-3.84-18.912-18.816-143.712-130.08-172.128-168.704-30.24-41.184-44.416-115.2-3.872-158.304 40.576-43.104 128.224-46.336 186.144 17.376 0 0 66.784-76.032 147.968-41.088 81.248 34.976 78.176 128.48 30.848 183.936z m263.392 20.384c-39.584 4.96-71.776 1.184-71.776 1.184V310.752h75.52s84.096 23.52 84.096 112.544c0 81.632-42.016 113.792-87.84 128.64z"})}),en=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block",...r},fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"}), Ie("polyline",{points:"17 21 17 13 7 13 7 21"}), Ie("polyline",{points:"7 3 7 8 15 8"})]}),tn=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,className:n,style:{display:"block",...r},fill:"none",stroke:t,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}), Ie("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),nn=({size:e=20,color:t="currentColor",className:n="",style:r})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block",...r},fill:t,children:[ Ie("path",{d:"M876.89 535.11c3.22-107.02-35.43-208.89-108.85-286.85-139.4-148.03-365.98-166.35-526.67-50.07l-5.56-57.66c-2.36-24.48-24.16-42.41-48.61-40.07-24.48 2.36-42.43 24.12-40.07 48.61l17.92 185.8a44.52 44.52 0 0 0 17.77 31.48c1.51 1.13 3.07 2.13 4.68 3.04a44.528 44.528 0 0 0 30.61 4.89l178.1-35.47c24.11-4.8 39.77-28.25 34.96-52.39-4.78-24.15-28.22-39.78-52.39-34.96l-81.37 16.2c124.67-87.44 298.4-72.49 405.79 41.7 57.09 60.62 87.16 139.85 84.68 223.08-2.51 83.24-37.26 160.52-97.91 217.62C564.83 867.92 367 862.07 249.25 736.82c-16.83-17.92-45.05-18.76-62.97-1.88-17.89 16.87-18.74 45.06-1.88 62.97 28.36 30.1 60.28 54.83 94.56 74.18 148.83 83.98 341.29 66 472.1-57.18C829 741.5 873.69 642.14 876.89 535.11z"}), Ie("path",{d:"M423.44 378.04c-24.59 0.46-44.16 20.78-43.7 45.37l3.34 178.13c0.46 24.59 20.78 44.16 45.37 43.7l178.13-3.34c24.59-0.46 44.16-20.78 43.7-45.37s-20.78-44.16-45.37-43.7l-133.6 2.51-2.51-133.6c-0.46-24.59-20.77-44.16-45.36-43.7z"})]}),rn=({size:e=16,color:t="currentColor",accentColor:n="#ff8910",className:r=""})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:r,style:{display:"block"},children:[ Ie("path",{d:"M950.857143 731.428571a73.142857 73.142857 0 0 1 73.142857 73.142858v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142857H146.285714a73.142857 73.142857 0 0 1-73.142857-73.142857v-146.285714a73.142857 73.142857 0 0 1 73.142857-73.142858h804.571429z m0 73.142858H146.285714v146.285714h804.571429v-146.285714z m0-438.857143a73.142857 73.142857 0 0 1 73.142857 73.142857v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142857H512v-73.142857h438.857143v-146.285714H512v-73.142857h438.857143z m0-365.714286a73.142857 73.142857 0 0 1 73.142857 73.142857v146.285714a73.142857 73.142857 0 0 1-73.142857 73.142858H146.285714a73.142857 73.142857 0 0 1-73.142857-73.142858V73.142857a73.142857 73.142857 0 0 1 73.142857-73.142857h804.571429z m0 73.142857H146.285714v146.285714h804.571429V73.142857z",fill:t}), Ie("path",{d:"M3.364571 558.592h227.584v146.285714l189.622858-182.857143-189.622858-182.857142v146.285714H3.364571z",fill:n})]}),on=({size:e=16,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:[ Ie("path",{d:"M186.7 532.8c-14.8 0-26.8-2.3-26.8-16.9 0-14.6 12-28.9 26.8-28.9v45.8z m605.8 144.3L678.9 763c-8 7.9-32.9 11.4-40.9 3.5v-54H508L347.4 532.8H186.7v-45.9h187.5l160.7 187.4H638v-78.9c8-7.9 32.9-10 40.9-2.1l113.6 83.8z m0-342L678.9 421c-8 7.9-32.9 11.4-40.9 3.5V356.6H534.8l-93.9 128.6-33.7-28.3s94-129.8 100.8-138.5h130v-65c8-7.9 32.9-10 40.9-2.1l113.6 85.9v-2.1z",fill:t}), Ie("path",{d:"M511.3 960.2c-60.5 0-119.1-11.8-174.4-35.2-53.4-22.6-101.3-54.9-142.4-96-41.1-41.1-73.4-89-96-142.4-23.4-55.2-35.2-113.9-35.2-174.4s11.8-119.1 35.2-174.4c22.6-53.4 54.9-101.3 96-142.4 41.1-41.1 89-73.4 142.4-96C392.1 76 450.8 64.2 511.3 64.2S630.4 76 685.7 99.4c53.4 22.6 101.3 54.9 142.4 96 41.1 41.1 73.4 89 96 142.4 23.4 55.2 35.2 113.9 35.2 174.4s-11.8 119.1-35.2 174.4c-22.6 53.4-54.9 101.3-96 142.4-41.1 41.1-89 73.4-142.4 96-55.2 23.4-113.9 35.2-174.4 35.2z m0-854.7c-224.3 0-406.7 182.4-406.7 406.7 0 224.3 182.4 406.7 406.7 406.7 224.3 0 406.7-182.4 406.7-406.7 0-224.2-182.4-406.7-406.7-406.7z",fill:t})]}),an="scrollTop",sn="scrollBottom",ln="goToAnchor",cn="togglePanel",dn="togglePanelMode",un="toggleTheme",hn="openSettings",gn="switchTab1",pn="switchTab2",mn="switchTab3",fn="toggleUserQueries",bn="onlyUserQueries",yn="toggleBookmarks",vn="locateOutline",wn="searchOutline",xn="refreshOutline",kn="prevHeading",Sn="nextHeading",Cn="toggleOutlineExpand",An="expandLevel1",En="expandLevel2",Tn="expandLevel3",Mn="expandLevel4",_n="expandLevel5",In="expandLevel6",Ln="newConversation",Nn="refreshConversations",Dn="locateConversation",qn="prevConversation",Rn="nextConversation",Pn="exportConversation",zn="copyLatestReply",Bn="copyLastCodeBlock",On="toggleScrollLock",Fn="toggleZenMode",$n="focusInput",Un="openGlobalSearch",jn="stopGeneration",Hn="togglePromptQueue",Wn="showShortcuts",Gn="showModelSelector",Qn="openClaudeSettings",Vn="switchClaudeKey",Kn="openGeminiSettings",Zn="openThemeSettings",Yn="openModelLockSettings",Jn={scrollTop:{labelKey:"shortcutScrollTop",label:"去顶部",category:"navigation"},scrollBottom:{labelKey:"shortcutScrollBottom",label:"去底部",category:"navigation"},goToAnchor:{labelKey:"shortcutGoToAnchor",label:"返回锚点",category:"navigation"},togglePanel:{labelKey:"shortcutTogglePanel",label:"展开/收起面板",category:"panel"},togglePanelMode:{labelKey:"shortcutTogglePanelMode",label:"切换面板模式(吸附/悬浮)",category:"panel"},toggleTheme:{labelKey:"shortcutToggleTheme",label:"切换主题",category:"panel"},switchTab1:{labelKey:"shortcutSwitchTab1",label:"切换到第 1 个标签",category:"panel"},switchTab2:{labelKey:"shortcutSwitchTab2",label:"切换到第 2 个标签",category:"panel"},switchTab3:{labelKey:"shortcutSwitchTab3",label:"切换到第 3 个标签",category:"panel"},toggleUserQueries:{labelKey:"shortcutToggleUserQueries",label:"显示用户问题",category:"outline"},onlyUserQueries:{labelKey:"shortcutOnlyUserQueries",label:"只显示用户问题",category:"outline"},toggleBookmarks:{labelKey:"shortcutToggleBookmarks",label:"显示用户收藏",category:"outline"},locateOutline:{labelKey:"shortcutLocateOutline",label:"定位大纲",category:"outline"},searchOutline:{labelKey:"shortcutSearchOutline",label:"搜索大纲",category:"outline"},prevHeading:{labelKey:"shortcutPrevHeading",label:"上一个标题",category:"outline"},nextHeading:{labelKey:"shortcutNextHeading",label:"下一个标题",category:"outline"},refreshOutline:{labelKey:"shortcutRefreshOutline",label:"刷新大纲",category:"outline"},toggleOutlineExpand:{labelKey:"shortcutToggleOutlineExpand",label:"展开/折叠全部",category:"outline"},expandLevel1:{labelKey:"shortcutExpandLevel1",label:"展开到 1 级",category:"outline"},expandLevel2:{labelKey:"shortcutExpandLevel2",label:"展开到 2 级",category:"outline"},expandLevel3:{labelKey:"shortcutExpandLevel3",label:"展开到 3 级",category:"outline"},expandLevel4:{labelKey:"shortcutExpandLevel4",label:"展开到 4 级",category:"outline"},expandLevel5:{labelKey:"shortcutExpandLevel5",label:"展开到 5 级",category:"outline"},expandLevel6:{labelKey:"shortcutExpandLevel6",label:"展开到 6 级",category:"outline"},newConversation:{labelKey:"shortcutNewConversation",label:"新会话",category:"conversation"},refreshConversations:{labelKey:"shortcutRefreshConversations",label:"刷新会话列表",category:"conversation"},locateConversation:{labelKey:"shortcutLocateConversation",label:"定位当前会话",category:"conversation"},prevConversation:{labelKey:"shortcutPrevConversation",label:"上一个会话",category:"conversation"},nextConversation:{labelKey:"shortcutNextConversation",label:"下一个会话",category:"conversation"},exportConversation:{labelKey:"shortcutExportConversation",label:"导出对话",category:"edit"},copyLatestReply:{labelKey:"shortcutCopyLatestReply",label:"复制最新回复",category:"edit"},copyLastCodeBlock:{labelKey:"shortcutCopyLastCodeBlock",label:"复制最后代码块",category:"edit"},toggleScrollLock:{labelKey:"shortcutToggleScrollLock",label:"锁定滚动",category:"edit"},toggleZenMode:{labelKey:"shortcutToggleZenMode",label:"切换禅模式",category:"edit"},focusInput:{labelKey:"shortcutFocusInput",label:"聚焦输入框",category:"edit"},openGlobalSearch:{labelKey:"navGlobalSearch",label:"全局搜索",category:"edit"},stopGeneration:{labelKey:"shortcutStopGeneration",label:"停止生成",category:"edit"},togglePromptQueue:{labelKey:"shortcutTogglePromptQueue",label:"显示/隐藏提示词队列",category:"edit"},showModelSelector:{labelKey:"shortcutShowModelSelector",label:"模型选择菜单",category:"edit"},openSettings:{labelKey:"shortcutOpenSettings",label:"打开设置",category:"settings"},showShortcuts:{labelKey:"shortcutShowShortcuts",label:"快捷键一览",category:"settings"},openThemeSettings:{labelKey:"shortcutOpenThemeSettings",label:"打开外观主题",category:"settings"},openModelLockSettings:{labelKey:"shortcutOpenModelLockSettings",label:"打开模型锁定",category:"settings"},openGeminiSettings:{labelKey:"shortcutOpenGeminiSettings",label:"打开 Gemini 专属",category:"settings"},openClaudeSettings:{labelKey:"shortcutOpenClaudeSettings",label:"打开 Claude 专属",category:"settings"},switchClaudeKey:{labelKey:"shortcutSwitchClaudeKey",label:"一键切换可用 Claude Key",category:"settings"}},Xn={navigation:{labelKey:"shortcutCategoryNavigation",label:"导航"},panel:{labelKey:"shortcutCategoryPanel",label:"面板"},outline:{labelKey:"shortcutCategoryOutline",label:"大纲"},conversation:{labelKey:"shortcutCategoryConversation",label:"会话"},edit:{labelKey:"shortcutCategoryEdit",label:"交互控制"},settings:{labelKey:"shortcutCategorySettings",label:"设置"}},er={scrollTop:{key:"t",alt:true},scrollBottom:{key:"b",alt:true},goToAnchor:{key:"z",alt:true},togglePanel:{key:"p",alt:true},togglePanelMode:{key:"m",alt:true},toggleTheme:{key:"d",alt:true},switchTab1:{key:"1",alt:true},switchTab2:{key:"2",alt:true},switchTab3:{key:"3",alt:true},refreshOutline:{key:"r",alt:true},toggleOutlineExpand:{key:"e",alt:true},expandLevel1:{key:"1",alt:true,shift:true},expandLevel2:{key:"2",alt:true,shift:true},expandLevel3:{key:"3",alt:true,shift:true},expandLevel4:{key:"4",alt:true,shift:true},expandLevel5:{key:"5",alt:true,shift:true},expandLevel6:{key:"6",alt:true,shift:true},toggleUserQueries:{key:"q",alt:true},toggleBookmarks:{key:"c",alt:true},onlyUserQueries:{key:"q",alt:true,shift:true},prevHeading:{key:"ArrowUp",alt:true},nextHeading:{key:"ArrowDown",alt:true},locateOutline:{key:"l",alt:true},searchOutline:{key:"f",alt:true},newConversation:{key:"o",ctrl:true,shift:true},refreshConversations:{key:"r",alt:true,shift:true},locateConversation:{key:"l",alt:true,shift:true},prevConversation:{key:"[",alt:true},nextConversation:{key:"]",alt:true},exportConversation:{key:"e",ctrl:true,shift:true},copyLatestReply:{key:"c",ctrl:true,shift:true},copyLastCodeBlock:{key:";",alt:true},toggleScrollLock:{key:"s",alt:true},toggleZenMode:{key:"z",ctrl:true,shift:true},focusInput:{key:"i",alt:true},openGlobalSearch:{key:"k",ctrl:true},stopGeneration:{key:"k",alt:true},togglePromptQueue:{key:"j",alt:true},showModelSelector:{key:"/",alt:true},showShortcuts:{key:"\\",alt:true},openSettings:{key:",",alt:true},openClaudeSettings:{key:"c",ctrl:true,alt:true},switchClaudeKey:{key:"s",ctrl:true,alt:true},openGeminiSettings:{key:"g",ctrl:true,alt:true},openThemeSettings:{key:"t",ctrl:true,alt:true},openModelLockSettings:{key:"l",ctrl:true,alt:true}},tr={enabled:true,globalUrl:"https://gemini.google.com",keybindings:er},nr={Backquote:"`",Minus:"-",Equal:"=",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Semicolon:";",Quote:"'",Comma:",",Period:".",Slash:"/"},rr={"å":"a","∫":"b","ç":"c","∂":"d","´":"e","ƒ":"f","©":"g","˙":"h","ˆ":"i","∆":"j","˚":"k","¬":"l","µ":"m","˜":"n","ø":"o","π":"p","œ":"q","®":"r","ß":"s","†":"t","¨":"u","√":"v","∑":"w","≈":"x","¥":"y","Ω":"z","¡":"1","™":"2","£":"3","¢":"4","∞":"5","§":"6","¶":"7","•":"8","ª":"9","º":"0","⁄":"1","€":"2","‹":"3","›":"4","fi":"5","fl":"6","‡":"7","°":"8","·":"9","‚":"0","–":"-","—":"-","≠":"=","±":"=","“":"[","”":"[","‘":"]","’":"]","«":"\\","»":"\\","…":";","æ":"'","Æ":"'","≤":",","¯":",","≥":".","˘":".","÷":"/","¿":"/"};function or(e,t){if(t){if(/^Key[A-Z]$/.test(t))return t.slice(3).toLowerCase();if(/^Digit[0-9]$/.test(t))return t.slice(5);if(nr[t])return nr[t]}return rr[e]?rr[e]:e}function ir(e){if(!e)return e;return {key:or(e.key),alt:!!e.alt,ctrl:!!e.ctrl||!!e.meta,shift:!!e.shift}}function ar(e){return e?{enabled:e.enabled??true,globalUrl:e.globalUrl||tr.globalUrl,keybindings:(t=e.keybindings,(t?Object.fromEntries(Object.entries(t).map(([e,t])=>[e,null===t?null:ir(t)])):t)||tr.keybindings)}:e;var t;}function sr(e,t=false){const n=ir(e);if(!n)return "";const r=[];n.ctrl&&r.push(t?"⌘":"Ctrl"),n.meta&&t&&r.push("⌘"),n.alt&&r.push(t?"⌥":"Alt"),n.shift&&r.push(t?"⇧":"Shift");const o=or(n.key),i={ArrowUp:"↑",ArrowDown:"↓",ArrowLeft:"←",ArrowRight:"→",",":","}[o]||o.toUpperCase();return r.push(i),r.join(t?"":"+")}function lr(){if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"",n=navigator.userAgentData?.platform?.toLowerCase?.();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")||!!n?.includes("mac")||t.includes("mac os")||t.includes("macintosh")||t.includes("iphone")||t.includes("ipad")||t.includes("ipod")}const cr="prompts",dr="outline",ur="conversations",hr="settings",gr="general",pr="appearance",mr="features",fr="siteSettings",br="globalSearch",yr="shortcuts",vr="backup",wr="permissions",xr="about",kr="outline",Sr="conversations",Cr="prompts",Ar="tab",Er="reminder",Tr="content",Mr="readingHistory",_r="toolbox",Ir="presets",Lr="custom",Nr="layout",Dr="modelLock",qr={"appearance-sync-native-page-theme":{page:pr},"appearance-preset-light":{page:pr,subTab:Ir},"appearance-preset-dark":{page:pr,subTab:Ir},"appearance-custom-styles":{page:pr,subTab:Lr},"tab-show-notification":{page:mr,subTab:Er},"tab-notification-sound":{page:mr,subTab:Er},"tab-notification-sound-preset":{page:mr,subTab:Er},"tab-notification-volume":{page:mr,subTab:Er},"tab-notification-repeat-count":{page:mr,subTab:Er},"tab-notification-repeat-interval":{page:mr,subTab:Er},"tab-notify-when-focused":{page:mr,subTab:Er},"tab-auto-focus":{page:mr,subTab:Er},"usage-monitor-enabled":{page:mr,subTab:Er},"usage-monitor-daily-limit":{page:mr,subTab:Er},"usage-monitor-auto-reset":{page:mr,subTab:Er}},Rr=[{prefix:"panel-",route:{page:gr,subTab:"panel"}},{prefix:"quick-buttons-",route:{page:gr,subTab:"shortcuts"}},{prefix:"tools-menu-",route:{page:gr,subTab:"toolsMenu"}},{prefix:"shortcuts-",route:{page:yr}},{prefix:"shortcut-binding-",route:{page:yr}},{prefix:"layout-",route:{page:fr,subTab:Nr}},{prefix:"model-lock-",route:{page:fr,subTab:Dr}},{prefix:"gemini-",route:{page:fr,subTab:"gemini"}},{prefix:"aistudio-",route:{page:fr,subTab:"aistudio"}},{prefix:"chatgpt-",route:{page:fr,subTab:"chatgpt"}},{prefix:"claude-",route:{page:fr,subTab:"claude"}},{prefix:"global-search-",route:{page:br}},{prefix:"tab-",route:{page:mr,subTab:Ar}},{prefix:"outline-",route:{page:mr,subTab:kr}},{prefix:"conversation-",route:{page:mr,subTab:Sr}},{prefix:"export-",route:{page:mr,subTab:Sr}},{prefix:"prompt-",route:{page:mr,subTab:Cr}},{prefix:"reading-history-",route:{page:mr,subTab:Mr}},{prefix:"content-",route:{page:mr,subTab:Tr}},{prefix:"appearance-preset-",route:{page:pr,subTab:Ir}},{prefix:"appearance-custom-",route:{page:pr,subTab:Lr}}],Pr={"general.panel.panelMode":"panel-mode","general.panel.defaultPosition":"panel-default-position","general.panel.defaultEdgeDistance":"panel-edge-distance","general.panel.width":"panel-width","general.panel.height":"panel-height","general.panel.edgeSnapThreshold":"panel-edge-snap-threshold","general.shortcuts.quickButtonsOpacity":"quick-buttons-opacity","general.toolsMenu":"tools-menu-scrollTop","siteSettings.layout.pageWidth.enabled":"layout-page-width-enabled","siteSettings.layout.pageWidth.value":"layout-page-width-value","siteSettings.layout.userQueryWidth.enabled":"layout-user-query-width-enabled","siteSettings.layout.userQueryWidth.value":"layout-user-query-width-value","siteSettings.layout.zenMode.enabled":"layout-zen-mode-enabled","siteSettings.modelLock":"model-lock-gemini","globalSearch.promptEnterBehavior":"global-search-prompt-enter-behavior","globalSearch.enableFuzzySearch":"global-search-fuzzy-search","globalSearch.doubleShift":"global-search-double-shift","shortcuts.enabled":"shortcuts-enabled","shortcuts.globalUrl":"shortcuts-global-url","features.prompts.submitShortcut":"shortcuts-prompt-submit-shortcut","features.tab.openInNewTab":"tab-open-new","features.tab.autoRename":"tab-auto-rename","usageMonitor.enabled":"usage-monitor-enabled","usageMonitor.dailyLimit":"usage-monitor-daily-limit","usageMonitor.autoResetEnabled":"usage-monitor-auto-reset","features.outline.autoUpdate":"outline-auto-update","features.outline.inlineBookmarkMode":"outline-inline-bookmark-mode","features.outline.panelBookmarkMode":"outline-panel-bookmark-mode","features.outline.preventAutoScroll":"outline-prevent-auto-scroll","features.prompts.promptQueue":"prompt-queue","features.export.packaging":"export-packaging","features.export.includeThoughts":"export-include-thoughts","export.packaging":"export-packaging","features.readingHistory.persistence":"reading-history-persistence","features.content.assistantMermaid":"content-assistant-mermaid","features.content.formulaCopy":"content-formula-copy","features.content.formulaCopyFormat":"content-formula-copy-format","panel.preventAutoScroll":"outline-prevent-auto-scroll","content.markdownFix":"gemini-markdown-fix","content.watermarkRemoval":"gemini-watermark-removal","geminiEnterprise.policyRetry.enabled":"gemini-policy-retry","geminiEnterprise.policyRetry.maxRetries":"gemini-policy-max-retries","aistudio.collapseNavbar":"aistudio-collapse-navbar","aistudio.collapseRunSettings":"aistudio-collapse-run-settings","aistudio.collapseTools":"aistudio-collapse-tools","aistudio.collapseAdvanced":"aistudio-collapse-advanced","aistudio.enableSearch":"aistudio-enable-search","aistudio.removeWatermark":"aistudio-remove-watermark","aistudio.markdownFix":"aistudio-markdown-fix","chatgpt.markdownFix":"chatgpt-markdown-fix","claude.sessionKeys":"claude-session-keys","appearance.syncNativePageTheme":"appearance-sync-native-page-theme","appearance.presets.light":"appearance-preset-light","appearance.presets.dark":"appearance-preset-dark","appearance.custom.styles":"appearance-custom-styles"},zr=e=>{const t=e?.trim();if(t)return Pr[t]??t},Br=e=>{const t=zr(e);if(t)return qr[t]?qr[t]:Rr.find(e=>t.startsWith(e.prefix))?.route},Or=[{settingId:"panel-mode",title:"面板模式",keywords:["panel","mode","edge snap","floating","模式","吸附","悬浮","默认打开","自动隐藏"]},{settingId:"panel-default-position",title:"默认位置",keywords:["panel","left","right","默认侧边"]},{settingId:"panel-edge-distance",title:"默认边距",keywords:["panel","edge distance","margin"]},{settingId:"panel-width",title:"面板宽度",keywords:["panel width","宽度"]},{settingId:"panel-height",title:"面板高度",keywords:["panel height","高度"]},{settingId:"panel-edge-snap-threshold",title:"边缘吸附阈值",keywords:["snap threshold","edge snap","吸附阈值"]},{settingId:"quick-buttons-opacity",title:"快捷按钮透明度",keywords:["quick buttons","opacity","透明度"]},{settingId:"quick-buttons-hide-when-panel-open",title:"面板展开时隐藏快捷按钮组",keywords:["quick buttons","hide","panel open","快捷按钮","隐藏","面板展开"]},{settingId:"quick-buttons-proximity-radius",title:"感应唤醒距离",keywords:["quick buttons","proximity","radius","唤醒距离","感应"]},{settingId:"tools-menu-export",title:"工具箱:显示导出按钮",keywords:["tools menu","export","工具箱","导出"]},{settingId:"tools-menu-copyMarkdown",title:"工具箱:显示复制 Markdown",keywords:["tools menu","copy","markdown","工具箱"]},{settingId:"tools-menu-move",title:"工具箱:显示移动按钮",keywords:["tools menu","move","folder","工具箱"]},{settingId:"tools-menu-setTag",title:"工具箱:显示标签按钮",keywords:["tools menu","tag","标签","工具箱"]},{settingId:"tools-menu-scrollLock",title:"工具箱:显示滚动锁定",keywords:["tools menu","scroll lock","锁定滚动","工具箱"]},{settingId:"tools-menu-modelLock",title:"工具箱:显示模型锁定",keywords:["tools menu","model lock","模型锁定","工具箱"]},{settingId:"tools-menu-cleanup",title:"工具箱:显示清理按钮",keywords:["tools menu","cleanup","清理","工具箱"]},{settingId:"tools-menu-settings",title:"工具箱:显示设置按钮",keywords:["tools menu","settings","设置","工具箱"]},{settingId:"tab-open-new",title:"新会话打开方式",keywords:["tab","new conversation","open in new tab","新标签页"]},{settingId:"tab-auto-rename",title:"自动重命名标签页",keywords:["tab","auto rename","自动命名"]},{settingId:"tab-rename-interval",title:"标签页重命名间隔",keywords:["tab","rename interval","重命名间隔"]},{settingId:"tab-title-format",title:"标签页标题格式",keywords:["tab","title format","标题模板"]},{settingId:"tab-show-status",title:"显示状态图标",keywords:["tab","status","状态图标"]},{settingId:"tab-hide-status-when-read",title:"仅在未读时显示完成标记",keywords:["tab","hide status","unread","未读","完成标记","✅"]},{settingId:"tab-show-notification",title:"启用新消息通知",keywords:["tab","notification","消息提醒"]},{settingId:"tab-notification-sound",title:"通知音效",keywords:["tab","notification sound","声音提醒"]},{settingId:"tab-notification-volume",title:"通知音量",keywords:["tab","notification volume","音量"]},{settingId:"tab-notify-when-focused",title:"标签页聚焦时也提醒",keywords:["tab","focused","notify","聚焦提醒"]},{settingId:"tab-auto-focus",title:"自动聚焦到对话页",keywords:["tab","auto focus","自动聚焦"]},{settingId:"usage-monitor-enabled",title:"启用高级模型对话本地计数与预估",keywords:["usage","counter","estimate","token","quota","limit","advanced model","高级模型","本地计数","预估"]},{settingId:"usage-monitor-daily-limit",title:"每日对话次数预估上限",keywords:["daily limit","quota","limit","每日上限","次数上限","token"]},{settingId:"usage-monitor-auto-reset",title:"自动归零",keywords:["auto reset","reset","midnight","自动归零","重置","清零"]},{settingId:"tab-privacy-mode",title:"隐私模式",keywords:["tab","privacy","隐私"]},{settingId:"tab-privacy-title",title:"隐私模式标题",keywords:["tab","privacy title","隐私标题"]},{settingId:"outline-auto-update",title:"自动更新大纲",keywords:["outline","auto update","自动刷新"]},{settingId:"outline-update-interval",title:"大纲更新间隔",keywords:["outline","interval","刷新频率"]},{settingId:"outline-follow-mode",title:"自动跟随浏览位置",keywords:["outline","follow","自动跟随"]},{settingId:"outline-show-word-count",title:"显示字数统计",keywords:["outline","word count","字数"]},{settingId:"outline-inline-bookmark-mode",title:"内联收藏模式",keywords:["outline","bookmark","收藏","inline"]},{settingId:"outline-panel-bookmark-mode",title:"面板收藏模式",keywords:["outline","bookmark","收藏","panel"]},{settingId:"outline-prevent-auto-scroll",title:"阻止自动滚动页面",keywords:["outline","auto scroll","禁止滚动"]},{settingId:"conversation-folder-rainbow",title:"会话文件夹彩虹色",keywords:["conversation","folder","rainbow","文件夹颜色"]},{settingId:"conversation-sync-unpin",title:"同步时自动取消置顶",keywords:["conversation","sync","unpin","置顶"]},{settingId:"conversation-sync-delete",title:"删除时同步删除云端",keywords:["conversation","sync","delete","cloud","删除","云端"]},{settingId:"export-packaging",title:"Markdown 导出方式",keywords:["export","packaging","markdown","zip","assets","导出","附件"]},{settingId:"export-custom-user-name",title:"导出:自定义用户名称",keywords:["export","user name","导出用户名"]},{settingId:"export-custom-model-name",title:"导出:自定义模型名称",keywords:["export","model name","导出模型名"]},{settingId:"export-filename-timestamp",title:"导出文件名包含时间戳",keywords:["export","filename","timestamp","时间戳"]},{settingId:"export-include-thoughts",title:"导出包含思维链",keywords:["export","thoughts","reasoning","thinking","思维链","思路","推理"]},{settingId:"export-images-base64",title:"导出时将图片转 Base64",keywords:["export","image","base64","图片"]},{settingId:"prompt-double-click-send",title:"提示词双击发送",keywords:["prompt","double click","send","双击发送"]},{settingId:"prompt-queue",title:"提示词队列",keywords:["prompt","queue","提示词队列","连续提问"]},{settingId:"reading-history-persistence",title:"阅读记录持久化",keywords:["reading history","persistence","持久化"]},{settingId:"reading-history-auto-restore",title:"自动恢复阅读位置",keywords:["reading history","restore","恢复位置"]},{settingId:"reading-history-cleanup-days",title:"阅读记录清理天数",keywords:["reading history","cleanup","days","清理周期"]},{settingId:"content-assistant-mermaid",title:"AI 回复 Mermaid 渲染",keywords:["content","mermaid","diagram","assistant response","AI 回复"]},{settingId:"content-user-query-markdown",title:"用户提问样式优化",keywords:["content","markdown","latex","math","user query","用户提问","数学公式"]},{settingId:"content-formula-copy",title:"公式复制增强",keywords:["content","formula","copy","数学公式"]},{settingId:"content-formula-copy-format",title:"公式复制格式",keywords:["content","formula","copy","format","latex","mathml","复制格式","LaTeX","MathML"]},{settingId:"content-formula-delimiter",title:"公式分隔符",keywords:["content","formula delimiter","分隔符"]},{settingId:"content-table-copy",title:"表格复制增强",keywords:["content","table copy","复制表格"]},{settingId:"layout-page-width-enabled",title:"页面宽度覆盖",keywords:["layout","page width","页面宽度"]},{settingId:"layout-page-width-value",title:"页面宽度值",keywords:["layout","page width value","页面宽度值"]},{settingId:"layout-user-query-width-enabled",title:"用户问题宽度覆盖",keywords:["layout","user query width","提问宽度"]},{settingId:"layout-user-query-width-value",title:"用户问题宽度值",keywords:["layout","user query width value","提问宽度值"]},{settingId:"layout-zen-mode-enabled",title:"布局:启用禅模式 (Zen Mode)",keywords:["layout","zen mode","禅模式","disclaimer","免责声明","隐藏"]},{settingId:"model-lock-gemini",title:"模型锁定:Gemini",keywords:["model lock","gemini","模型锁定"]},{settingId:"model-lock-gemini-enterprise",title:"模型锁定:Gemini Enterprise",keywords:["model lock","gemini enterprise","模型锁定"]},{settingId:"model-lock-aistudio",title:"模型锁定:AI Studio",keywords:["model lock","aistudio","模型锁定"]},{settingId:"model-lock-chatgpt",title:"模型锁定:ChatGPT",keywords:["model lock","chatgpt","模型锁定"]},{settingId:"model-lock-claude",title:"模型锁定:Claude",keywords:["model lock","claude","模型锁定"]},{settingId:"model-lock-grok",title:"模型锁定:Grok",keywords:["model lock","grok","模型锁定"]},{settingId:"model-lock-qianwen",title:"模型锁定:Qianwen",keywords:["model lock","qianwen","tongyi","通义千问","模型锁定"]},{settingId:"model-lock-qwenai",title:"模型锁定:Qwen Studio",keywords:["model lock","qwen studio","qwenai","chat.qwen.ai","国际版千问","模型锁定"]},{settingId:"model-lock-yuanbao",title:"模型锁定:Yuanbao",keywords:["model lock","yuanbao","腾讯元宝","模型锁定"]},{settingId:"model-lock-ima",title:"模型锁定:ima",keywords:["model lock","ima","ima.qq.com","腾讯 ima","模型锁定"]},{settingId:"model-lock-zai",title:"模型锁定:Z.ai",keywords:["model lock","z.ai","zai","模型锁定"]},{settingId:"gemini-markdown-fix",title:"Gemini:Markdown 修复",keywords:["gemini","markdown","fix","修复"]},{settingId:"gemini-watermark-removal",title:"Gemini:去水印",keywords:["gemini","watermark","去水印"]},{settingId:"gemini-policy-retry",title:"Gemini:策略重试",keywords:["gemini","policy retry","策略重试"]},{settingId:"gemini-policy-max-retries",title:"Gemini:最大重试次数",keywords:["gemini","max retries","最大重试"]},{settingId:"aistudio-collapse-navbar",title:"AI Studio:折叠左侧导航",keywords:["aistudio","collapse navbar","折叠导航"]},{settingId:"aistudio-collapse-run-settings",title:"AI Studio:折叠 Run settings",keywords:["aistudio","run settings","折叠运行设置"]},{settingId:"aistudio-collapse-tools",title:"AI Studio:折叠 Tools",keywords:["aistudio","tools","折叠工具"]},{settingId:"aistudio-collapse-advanced",title:"AI Studio:折叠 Advanced",keywords:["aistudio","advanced","折叠高级选项"]},{settingId:"aistudio-enable-search",title:"AI Studio:启用搜索",keywords:["aistudio","search","启用搜索"]},{settingId:"aistudio-remove-watermark",title:"AI Studio:去水印",keywords:["aistudio","watermark","去水印"]},{settingId:"aistudio-markdown-fix",title:"AI Studio:Markdown 修复",keywords:["aistudio","markdown","fix","修复"]},{settingId:"chatgpt-markdown-fix",title:"ChatGPT:Markdown 修复",keywords:["chatgpt","markdown","fix","修复"]},{settingId:"claude-session-keys",title:"Claude:Session Keys",keywords:["claude","session key","token","密钥"]},{settingId:"global-search-prompt-enter-behavior",title:"全局搜索:提示词回车行为",keywords:["global search","prompt","enter","全局搜索","提示词","回车"]},{settingId:"global-search-fuzzy-search",title:"Global Search: Enable fuzzy search",keywords:["global search","fuzzy","search everywhere","matching"]},{settingId:"global-search-double-shift",title:"全局搜索:双击 Shift 触发",keywords:["global search","double shift","shortcut","全局搜索","双击 shift","快捷键"]},{settingId:"global-search-shortcut-setting-link",title:"全局搜索:快捷键设置入口",keywords:["global search","shortcut","keybinding","全局搜索","快捷键","键位设置"]},{settingId:"shortcuts-enabled",title:"启用自定义快捷键",keywords:["shortcuts","enable","快捷键","自定义","总开关"]},{settingId:"shortcuts-global-url",title:"全局快捷键 URL",keywords:["shortcuts","global url","alt+o","快捷键","url"]},{settingId:"shortcuts-browser-shortcuts",title:"浏览器快捷键设置入口",keywords:["shortcuts","browser shortcuts","chrome://extensions/shortcuts","快捷键"]},{settingId:"shortcuts-prompt-submit-shortcut",title:"发送快捷键",keywords:["shortcuts","submit","enter","ctrl+enter","发送","快捷键"]},{settingId:"appearance-sync-native-page-theme",title:"同步原生页面主题",keywords:["appearance","theme","native page theme","sync native page theme","sync page theme","同步原生页面主题","原生页面主题","同步主题","亮暗模式联动","宿主页面主题"]},{settingId:"appearance-preset-light",title:"浅色主题预设",keywords:["appearance","theme","light","浅色"]},{settingId:"appearance-preset-dark",title:"深色主题预设",keywords:["appearance","theme","dark","深色"]},{settingId:"appearance-custom-styles",title:"自定义主题样式",keywords:["appearance","custom style","主题样式","css"]},...Object.entries(Jn).map(([e,t])=>({settingId:`shortcut-binding-${e}`,title:`快捷键:${t.label}`,keywords:["shortcut","shortcuts","keybinding","hotkey","keyboard","快捷键","键位","按键",t.label,t.labelKey,e,t.category]}))],Fr=Object.entries(Pr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),$r=e=>e.trim().toLowerCase(),Ur=(e,t)=>{const n=$r(e),r=(e=>$r(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0))(n);return Or.map((e,t)=>{const o=$r(e.title),i=$r((e.keywords||[]).join(" ")),a=$r(e.settingId),s=$r((Fr[e.settingId]||[]).join(" ")),l=`${o} ${i} ${a} ${s}`;if(r.some(e=>!l.includes(e)))return null;let c=0;return n?(o===n&&(c+=200),o.startsWith(n)&&(c+=120),o.includes(n)&&(c+=80),i.includes(n)&&(c+=70),a.includes(n)&&(c+=60),s.includes(n)&&(c+=50),r.forEach(e=>{o.startsWith(e)&&(c+=16),o.includes(e)&&(c+=8),i.includes(e)&&(c+=6),a.includes(e)&&(c+=5),s.includes(e)&&(c+=4);}),c+=Math.max(0,24-Math.min(24,o.length))):c=1e3-t,{item:e,score:c,index:t}}).filter(e=>!!e).sort((e,t)=>t.score!==e.score?t.score-e.score:e.index-t.index).map(({item:e})=>e)},jr={[cr]:{label:"tabPrompts",icon:"✏️",IconComponent:He},[ur]:{label:"tabConversations",icon:"💬",IconComponent:Ge},[dr]:{label:"tabOutline",icon:"📑",IconComponent:Ue},[hr]:{label:"tabSettings",icon:"⚙️"}},Hr={scrollTop:{icon:"⬆",labelKey:"scrollTop",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:tt},panel:{icon:"✨",labelKey:"panelTitle",canToggle:false,isPanelOnly:true,IconComponent:Qt},floatingToolbar:{icon:"🧰",labelKey:"tools",canToggle:true,isPanelOnly:false,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(0 12 12)"}), Ie("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(60 12 12)"}), Ie("ellipse",{cx:"12",cy:"12",rx:"10",ry:"4",stroke:"currentColor",strokeWidth:"1.5",transform:"rotate(120 12 12)"}), Ie("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})},globalSearch:{icon:"🔎",labelKey:"navGlobalSearch",canToggle:true,isPanelOnly:false,IconComponent:Wt},anchor:{icon:"⚓",canToggle:true,labelKey:"showCollapsedAnchorLabel",isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:Pe},theme:{icon:"☀",labelKey:"showCollapsedThemeLabel",canToggle:true,isPanelOnly:false,IconComponent:qe},manualAnchor:{icon:"📍",labelKey:"manualAnchorLabel",canToggle:true,isPanelOnly:false,isGroup:true,IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{viewBox:"0 0 24 24",width:e,height:e,fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,style:{display:"block"},children:[ Ie("path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}), Ie("line",{x1:"12",y1:"7",x2:"12",y2:"13"}), Ie("line",{x1:"9",y1:"10",x2:"15",y2:"10"})]})},scrollBottom:{icon:"⬇",labelKey:"scrollBottom",canToggle:true,isPanelOnly:false,hideWhenPanelOpen:true,IconComponent:nt},zenMode:{icon:"🧘",labelKey:"zenModeTitle",canToggle:true,isPanelOnly:false,IconComponent:Ft},settings:{icon:"⚙️",labelKey:"tabSettings",canToggle:true,isPanelOnly:false,IconComponent:Oe}},Wr=["📁","📂","📥","🗂️","📊","📈","📉","📋","💼","📅","📌","📎","📝","✒️","🔍","💡","💻","⌨️","🖥️","🖱️","🐛","🔧","🔨","⚙️","🤖","👾","🧠","⚡","🔥","✨","🎓","📚","🎨","🎭","🎬","🎹","🎵","📷","🖌️","🖍️","🏠","🛒","✈️","🎮","⚽","🍔","☕","❤️","🔴","🟠","🟡","🟢","🔵","🟣","⚫","⚪","⭐","🌟","🎉","🔒","🔑","🚫","✅","❓"],Gr=["#FF461F","#FF6B6B","#FA8072","#DC143C","#CD5C5C","#FF4500","#FFA500","#FFB347","#F0E68C","#DAA520","#FFD700","#9ACD32","#32CD32","#3CB371","#20B2AA","#00CED1","#5F9EA0","#4682B4","#6495ED","#4169E1","#0000CD","#8A2BE2","#9370DB","#BA55D3","#DB7093","#C71585","#8B4513","#A0522D","#708090","#2F4F4F"],Qr=1500,Vr=2e3,Kr=3e3,Zr="#10b981",Yr="#ef4444",Jr="var(--gh-text-secondary)",Xr=[{id:"default",labelKey:"notificationSoundPresetDefault",fallback:"Default"},{id:"softChime",labelKey:"notificationSoundPresetSoftChime",fallback:"Soft Chime"},{id:"glassPing",labelKey:"notificationSoundPresetGlassPing",fallback:"Glass Ping"},{id:"brightAlert",labelKey:"notificationSoundPresetBrightAlert",fallback:"Bright Alert"}],eo=["settings","prompts","folders","tags","conversations","readingHistory"],to=["conversations","readingHistory"],no=()=>[{id:"default_1",title:se("defaultPromptCodeOptTitle"),content:se("defaultPromptCodeOptContent"),category:se("defaultPromptCodeOptCategory")},{id:"default_2",title:se("defaultPromptTranslateTitle"),content:se("defaultPromptTranslateContent"),category:se("defaultPromptTranslateCategory")}],ro=[{id:"inbox",name:"收件箱",icon:"📥",isDefault:true}],oo={PAGE_WIDTH:{DEFAULT_PX:"1280",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:1200},USER_QUERY_WIDTH:{DEFAULT_PX:"600",DEFAULT_PERCENT:"81",MIN_PERCENT:40,MAX_PERCENT:99,MIN_PX:600}},io={CLAUDE_KEY:/^sk-ant-sid\d{2}-/},ao=500,so="claude",lo="gemini",co="chatgpt",uo="chatglm",ho="gemini-enterprise",go="grok",po="aistudio",mo="doubao",fo="ima",bo="deepseek",yo="kimi",vo="qianwen",wo="qwenai",xo="yuanbao",ko="zai",So=[{id:co,name:"ChatGPT",pattern:/chatgpt\.com/,url:"https://chatgpt.com",icon:"💬"},{id:lo,name:"Gemini",pattern:/gemini\.google\.com/,url:"https://gemini.google.com",icon:"🌟"},{id:so,name:"Claude",pattern:/claude\.(ai|com)/,url:"https://claude.ai",icon:"🎭"},{id:po,name:"AI Studio",pattern:/aistudio\.google\.com/,url:"https://aistudio.google.com",icon:"🧪"},{id:go,name:"Grok",pattern:/grok\.com/,url:"https://grok.com",icon:"🤖"},{id:ho,name:"Gemini Enterprise",pattern:/business\.gemini\.google/,url:"https://business.gemini.google",icon:"🏢"},{id:mo,name:"Doubao",pattern:/www\.doubao\.com/,url:"https://www.doubao.com",icon:"🌱"},{id:bo,name:"DeepSeek",pattern:/chat\.deepseek\.com/,url:"https://chat.deepseek.com",icon:"🌀"},{id:yo,name:"Kimi",pattern:/www\.kimi\.com/,url:"https://www.kimi.com",icon:"🌙"},{id:ko,name:"Z.ai",pattern:/chat\.z\.ai/,url:"https://chat.z.ai",icon:"⚡"},{id:uo,name:"ChatGLM",pattern:/chatglm\.cn/,url:"https://chatglm.cn/main/alltoolsdetail?lang=zh",icon:"🧠"},{id:xo,name:"Yuanbao",pattern:/yuanbao\.tencent\.com/,url:"https://yuanbao.tencent.com",icon:"💎"},{id:vo,name:"Qianwen",pattern:/www\.qianwen\.com/,url:"https://www.qianwen.com",icon:"🔮"},{id:wo,name:"Qwen Studio",pattern:/chat\.qwen\.ai/,url:"https://chat.qwen.ai",icon:"🪄"},{id:fo,name:"ima",pattern:/ima\.qq\.com/,url:"https://ima.qq.com",icon:"🐼"}],Co="__all__",Ao="__recent__",Eo="export",To="copyMarkdown",Mo="move",_o="setTag",Io="scrollLock",Lo="modelLock",No="cleanup",Do="settings",qo=[{id:Eo,labelKey:"export",defaultLabel:"Export",IconComponent:Ve,defaultVisible:true},{id:To,labelKey:"exportToClipboard",defaultLabel:"Copy Markdown",IconComponent:Tt,defaultVisible:true},{id:Mo,labelKey:"conversationsMoveTo",defaultLabel:"Move",IconComponent:ze,defaultVisible:true},{id:_o,labelKey:"conversationsSetTag",defaultLabel:"Set Tag",IconComponent:Nt,defaultVisible:true},{id:Io,labelKey:"shortcutToggleScrollLock",defaultLabel:"Scroll Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Ie("path",{d:"M12 3v12"}), Ie("path",{d:"m8 11 4 4 4-4"}), Ie("path",{d:"M19 19H5"}), Ie("circle",{cx:"12",cy:"11",r:"9",strokeOpacity:"0.3"}), Ie("path",{d:"m4.9 4.9 14.2 14.2"})]}),isToggle:true,defaultVisible:true},{id:Lo,labelKey:"modelLockTitle",defaultLabel:"Model Lock",IconComponent:({size:e=18,color:t="currentColor",className:n=""})=>Le("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:t,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:n,children:[ Ie("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}), Ie("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}), Ie("circle",{cx:"9",cy:"15",r:"1.5",fill:t,stroke:"none"}), Ie("circle",{cx:"15",cy:"15",r:"1.5",fill:t,stroke:"none"}), Ie("path",{d:"M9 19h6"})]}),isToggle:true,defaultVisible:true},{id:No,labelKey:"cleanup",defaultLabel:"Cleanup",IconComponent:Lt,isDanger:true,defaultVisible:true},{id:Do,labelKey:"tabSettings",defaultLabel:"Settings",IconComponent:Oe,isSystem:true,defaultVisible:true}],Ro=e=>{let t;const n=new Set,r=(e,r)=>{const o="function"==typeof e?e(t):e;if(!Object.is(o,t)){const e=t;t=(null!=r?r:"object"!=typeof o||null===o)?o:Object.assign({},t,o),n.forEach(n=>n(t,e));}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e))},a=t=e(r,o,i);return i},Po=e=>e;const zo=e=>{const t=(e=>e?Ro(e):Ro)(e),n=e=>function(e,t=Po){const n=o.useSyncExternalStore(e.subscribe,o.useCallback(()=>t(e.getState()),[e,t]),o.useCallback(()=>t(e.getInitialState()),[e,t]));return o.useDebugValue(n),n}(t,e);return Object.assign(n,t),n},Bo=e=>zo;function Oo(e,t){let n;try{n=e();}catch(r){return}return {getItem:e=>{var t;const r=e=>null===e?null:JSON.parse(e,void 0),o=null!=(t=n.getItem(e))?t:null;return o instanceof Promise?o.then(r):r(o)},setItem:(e,t)=>n.setItem(e,JSON.stringify(t,void 0)),removeItem:e=>n.removeItem(e)}}const Fo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then:e=>Fo(e)(n),catch(e){return this}}}catch(n){return {then(e){return this},catch:e=>Fo(e)(n)}}},$o=(e,t)=>(n,r,o)=>{let i={storage:Oo(()=>localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},a=false,s=0;const l=new Set,c=new Set;let d=i.storage;if(!d)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...e);},r,o);const u=()=>{const e=i.partialize({...r()});return d.setItem(i.name,{state:e,version:i.version})},h=o.setState;o.setState=(e,t)=>(h(e,t),u());const g=e((...e)=>(n(...e),u()),r,o);let p;o.getInitialState=()=>g;const m=()=>{var e,t;if(!d)return;const o=++s;a=false,l.forEach(e=>{var t;return e(null!=(t=r())?t:g)});const h=(null==(t=i.onRehydrateStorage)?void 0:t.call(i,null!=(e=r())?e:g))||void 0;return Fo(d.getItem.bind(d))(i.name).then(e=>{if(e){if("number"!=typeof e.version||e.version===i.version)return [false,e.state];if(i.migrate){const t=i.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[true,e]):[true,t]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided");}return [false,void 0]}).then(e=>{var t;if(o!==s)return;const[a,l]=e;return p=i.merge(l,null!=(t=r())?t:g),n(p,true),a?u():void 0}).then(()=>{o===s&&(null==h||h(p,void 0),p=r(),a=true,c.forEach(e=>e(p)));}).catch(e=>{o===s&&(null==h||h(void 0,e));})};return o.persist={setOptions:e=>{i={...i,...e},e.storage&&(d=e.storage);},clearStorage:()=>{null==d||d.removeItem(i.name);},getOptions:()=>i,rehydrate:()=>m(),hasHydrated:()=>a,onHydrate:e=>(l.add(e),()=>{l.delete(e);}),onFinishHydration:e=>(c.add(e),()=>{c.delete(e);})},i.skipHydration||m(),p||g};const Uo=true;new class{area;constructor(e){this.area=e?.area||"local";}async get(e){const t=GM_getValue(e);if(null!=t)return t}async set(e,t){GM_setValue(e,t);}async remove(e){GM_deleteValue(e);}async getAll(){return console.warn("[Storage Polyfill] getAll() is not supported in userscript"),{}}async setMany(e){for(const[t,n]of Object.entries(e))GM_setValue(t,n);}watch(e){if("string"==typeof e){const t=GM_addValueChangeListener(e,(e,t,n,r)=>{});return ()=>GM_removeValueChangeListener(t)}{const t=[];for(const[n,r]of Object.entries(e)){const e=GM_addValueChangeListener(n,(e,t,n,o)=>{r({newValue:n,oldValue:t});});t.push(e);}return ()=>t.forEach(e=>GM_removeValueChangeListener(e))}}}({area:"local"});const jo="ophel:clearAllFlag",Ho="ophel_skip_restore",Wo={mode:"light",lightStyleId:"google-gradient",darkStyleId:"classic-dark"},Go={enabled:false,value:"81",unit:"%"},Qo={enabled:false,value:"81",unit:"%"},Vo={enabled:false},Ko={enabled:true},Zo=[{id:"panel",enabled:true},{id:"floatingToolbar",enabled:true},{id:"globalSearch",enabled:true},{id:"theme",enabled:true},{id:"zenMode",enabled:true},{id:"settings",enabled:true},{id:"scrollTop",enabled:true},{id:"manualAnchor",enabled:false},{id:"anchor",enabled:true},{id:"scrollBottom",enabled:true}],Yo={collapsed:Zo.map(e=>({...e})),opacity:1,floatingToolbar:{open:true},hideWhenPanelOpen:false,proximityRadius:150},Jo={language:"auto",hasAgreedToTerms:false,hasSeenOphelAdvancedGuide:false,panel:{panelExpanded:true,panelMode:"edge-snap",preventAutoScroll:false,defaultPosition:"right",defaultEdgeDistance:0,edgeSnapThreshold:30,height:85,width:320},geminiEnterprise:{policyRetry:{enabled:false,maxRetries:3}},content:{assistantMermaid:true,markdownFix:false, // 油猴脚本环境默认开启(GM_xmlhttpRequest 已通过 @grant 声明) watermarkRemoval:Uo,formulaCopy:true,formulaCopyFormat:"latex",formulaDelimiter:true,tableCopy:true,exportImagesToBase64:false,userQueryMarkdown:true},export:{customUserName:"",customModelName:"",exportFilenameTimestamp:false,includeThoughts:true,packaging:"markdown"},theme:{syncNativePageTheme:true,sites:{gemini:{...Wo},"gemini-enterprise":{...Wo},doubao:{...Wo},ima:{...Wo},deepseek:{...Wo},yuanbao:{...Wo},zai:{...Wo},_default:{...Wo}},customStyles:[]},layout:{pageWidth:{gemini:{...Go},"gemini-enterprise":{...Go},aistudio:{...Go},doubao:{...Go},ima:{...Go},deepseek:{...Go},yuanbao:{...Go},zai:{...Go},_default:{...Go}},userQueryWidth:{gemini:{...Qo},"gemini-enterprise":{...Qo},aistudio:{...Qo},doubao:{...Qo},ima:{...Qo},deepseek:{...Qo},yuanbao:{...Qo},zai:{...Qo},_default:{...Qo}},zenMode:{gemini:{...Vo},"gemini-enterprise":{...Vo},aistudio:{...Vo},doubao:{...Vo},ima:{...Vo},deepseek:{...Vo},yuanbao:{...Vo},zai:{...Vo},_default:{...Vo}},cleanMode:{gemini:{...Ko},"gemini-enterprise":{...Ko},aistudio:{...Ko},doubao:{...Ko},ima:{...Ko},deepseek:{...Ko},yuanbao:{...Ko},zai:{...Ko},_default:{...Ko}}},modelLock:{gemini:{enabled:false,keyword:""},"gemini-enterprise":{enabled:false,keyword:""},ima:{enabled:false,keyword:""},qwenai:{enabled:false,keyword:""},yuanbao:{enabled:false,keyword:""}},globalSearch:{promptEnterBehavior:"smart",enableFuzzySearch:false,doubleShift:false},usageMonitor:{enabled:false,dailyLimit:100,autoResetEnabled:false},features:{order:["outline","conversations","prompts"],prompts:{enabled:true,doubleClickToSend:false,submitShortcut:"enter",promptQueue:false},conversations:{enabled:true,syncUnpin:false,syncDelete:true,folderRainbow:true},outline:{enabled:true,maxLevel:6,autoUpdate:true,updateInterval:2,showUserQueries:true,followMode:"current",expandLevel:6,inlineBookmarkMode:"always",panelBookmarkMode:"always",showWordCount:false}},tab:{openInNewTab:false,autoRename:true,renameInterval:3,showStatus:true,hideStatusWhenRead:false,titleFormat:"{status}{title}->{model}", // 油猴脚本环境默认开启(GM_notification 已通过 @grant 声明) showNotification:Uo,notificationSound:true,notificationSoundPreset:"softChime",notificationVolume:.5,notificationRepeatCount:3,notificationRepeatInterval:2,notifyWhenFocused:false,autoFocus:false,privacyMode:false,privacyTitle:"Google",customIcon:"default"},readingHistory:{persistence:true,autoRestore:true,cleanupDays:3},quickButtons:{collapsed:Zo.map(e=>({...e})),opacity:Yo.opacity,floatingToolbar:{...Yo.floatingToolbar},hideWhenPanelOpen:Yo.hideWhenPanelOpen,proximityRadius:Yo.proximityRadius},claude:{currentKeyId:""},webdav:{enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:"ophel",dataSources:["settings","conversations","prompts","claudeSessionKeys"]},shortcuts:tr,aistudio:{collapseNavbar:false,collapseTools:false,collapseAdvanced:false,enableSearch:true,defaultModel:"",markdownFix:Uo,removeWatermark:Uo},chatgpt:{markdownFix:false}};function Xo(e,t){const n=e.theme?.sites;return n&&t in n?n[t]:n?._default??Wo}function ei(e,t){const n=e.layout?.pageWidth;return n&&t in n?n[t]:n?._default??Go}function ti(e,t){return e.modelLock?.[t]??{enabled:false,keyword:""}}function ni(e,t){const n=e.layout?.userQueryWidth;return n&&t in n?n[t]:n?._default??Qo}function ri(e,t){const n=e.layout?.zenMode;return n&&t in n?n[t]:n?._default??Vo}function oi(e,t){const n=e.layout?.cleanMode;return n&&t in n?n[t]:n?._default??Ko}let ii=null;const ai="ophel:restoreFlag";let si=null;function li(){if("undefined"==typeof window)return false;const e=new URL(window.location.href);if("1"!==e.searchParams.get(Ho))return false;e.searchParams.delete(Ho);const t=`${e.pathname}${e.search}${e.hash}`||window.location.pathname+window.location.search+window.location.hash;return window.history.replaceState(window.history.state,"",t),true}const ci=(e,t)=>{if(null==t)return null;const n="string"==typeof t?(e=>{try{return JSON.parse(e)}catch{return}})(t):t;return "settings"===e&&void 0!==n&&!(e=>"object"==typeof e&&null!==e&&"state"in e)(n)&&(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&["hasAgreedToTerms","panel","content","theme","layout"].some(t=>t in e))(n)?JSON.stringify({state:{settings:n},version:0}):"string"==typeof t?t:JSON.stringify(t)},di={getItem:e=>{try{const t=GM_getValue(e);return ci(e,t)}catch(t){throw console.error(`[ophel] userscriptStorageAdapter.getItem("${e}") THREW:`,t),t}},setItem:(e,t)=>{GM_setValue(e,t);},removeItem:e=>{GM_deleteValue(e);}};let ui=0;const hi=e=>{ui+=1;try{return e()}finally{(()=>{const e=()=>{ui=Math.max(0,ui-1);};"function"!=typeof queueMicrotask?Promise.resolve().then(e):queueMicrotask(e);})();}},gi=(e,t,n)=>{if(e.some(e=>e.id===t.id))return e;const r=[...e],o=n?r.findIndex(e=>e.id===n)+1:r.length;return r.splice(o>0?o:r.length,0,t),r},pi=e=>{if(!e)return;const t=Number(e.xRatio),n=Number(e.yRatio);return Number.isFinite(t)&&Number.isFinite(n)?{xRatio:Math.min(1,Math.max(0,t)),yRatio:Math.min(1,Math.max(0,n))}:void 0},mi=e=>{const t=Array.isArray(e.collapsedButtons)?e.collapsedButtons:[],n=e.quickButtons||{},r=n.collapsed??t;let o=r.length>0?r.filter(e=>Boolean(e?.id)).map(e=>({id:e.id,enabled:false!==e.enabled})):Yo.collapsed.map(e=>({...e}));return o=gi(o,{id:"floatingToolbar",enabled:true},"panel"),o=gi(o,{id:"globalSearch",enabled:true},"floatingToolbar"),o=gi(o,{id:"zenMode",enabled:true},"theme"),o=gi(o,{id:"settings",enabled:true},"zenMode"),{collapsed:o,opacity:n.opacity??e.quickButtonsOpacity??Yo.opacity,hideWhenPanelOpen:n.hideWhenPanelOpen??Yo.hideWhenPanelOpen,toolsMenu:n.toolsMenu??e.toolsMenu,floatingToolbar:{...Yo.floatingToolbar,...e.floatingToolbar||{},...n.floatingToolbar||{}},position:pi(n.position),proximityRadius:(()=>{const e=Number(n.proximityRadius);return Number.isFinite(e)?Math.min(300,Math.max(0,e)):Yo.proximityRadius})()}},fi=(e,t,n)=>{const r={...n}; return new Set([...Object.keys(n),...Object.keys(e??{})]).forEach(o=>{r[o]=((e,t)=>{const n=oo[t],r=Number.parseInt(n.DEFAULT_PERCENT,10),o=Number.parseInt(n.DEFAULT_PX,10),i=Number.parseInt(String(e?.value??n.DEFAULT_PERCENT),10),a="px"===e?.unit?"px":"%";let s=Number.isNaN(i)?r:i;return "px"===a&&(s=Math.round(s/o*r)),{enabled:e?.enabled??false,value:String((l=s,c=n.MIN_PERCENT,d=n.MAX_PERCENT,Math.min(d,Math.max(c,l)))),unit:"%"};var l,c,d;})(e?.[o]??n[o],t);}),r},bi=e=>{const t={...Jo.theme.sites}; return new Set([...Object.keys(Jo.theme.sites),...Object.keys(e??{})]).forEach(n=>{t[n]={...Jo.theme.sites[n]??Jo.theme.sites._default,...e?.[n]??{}};}),t},yi=(e,t)=>{const n={...t}; return new Set([...Object.keys(t),...Object.keys(e??{})]).forEach(r=>{n[r]={...t[r]??t._default??{},...e?.[r]??{}};}),n},vi=e=>{const t=Jo.panel;return {panelExpanded:e?.panelExpanded??t.panelExpanded,panelMode:"edge-snap"===e?.panelMode||"floating"===e?.panelMode?e.panelMode:t.panelMode,preventAutoScroll:e?.preventAutoScroll??t.preventAutoScroll,defaultPosition:"left"===e?.defaultPosition||"right"===e?.defaultPosition?e.defaultPosition:t.defaultPosition,defaultEdgeDistance:e?.defaultEdgeDistance??t.defaultEdgeDistance,edgeSnapThreshold:e?.edgeSnapThreshold??t.edgeSnapThreshold,height:e?.height??t.height,width:e?.width??t.width}},wi=e=>{const t=Jo.export,n="zip"===e?.packaging||"markdown"===e?.packaging?e.packaging:t.packaging;return {...t,...e,packaging:n}},xi=e=>{const{collapsedButtons:t,quickButtonsOpacity:n,toolsMenu:r,floatingToolbar:o,quickButtons:i,...a}=e;return {...Jo,...a,panel:vi(e.panel),content:{...Jo.content,...e.content},theme:{...Jo.theme,...e.theme,sites:bi(e.theme?.sites),customStyles:e.theme?.customStyles??Jo.theme.customStyles},layout:{...Jo.layout,...e.layout,pageWidth:fi(e.layout?.pageWidth,"PAGE_WIDTH",Jo.layout.pageWidth),userQueryWidth:fi(e.layout?.userQueryWidth,"USER_QUERY_WIDTH",Jo.layout.userQueryWidth),zenMode:yi(e.layout?.zenMode,Jo.layout.zenMode),cleanMode:yi(e.layout?.cleanMode,Jo.layout.cleanMode)},modelLock:yi(e.modelLock,Jo.modelLock),globalSearch:{...Jo.globalSearch,...e.globalSearch},usageMonitor:{...Jo.usageMonitor,...e.usageMonitor},features:{...Jo.features,...e.features,outline:{...Jo.features.outline,...e.features?.outline},prompts:{...Jo.features.prompts,...e.features?.prompts},conversations:{...Jo.features.conversations,...e.features?.conversations}},tab:{...Jo.tab,...e.tab},readingHistory:{...Jo.readingHistory,...e.readingHistory},export:wi(e.export),geminiEnterprise:{...Jo.geminiEnterprise,...e.geminiEnterprise,policyRetry:{...Jo.geminiEnterprise?.policyRetry,...e.geminiEnterprise?.policyRetry}},webdav:{...Jo.webdav,...e.webdav},aistudio:{...Jo.aistudio,...e.aistudio},chatgpt:{...Jo.chatgpt,...e.chatgpt},shortcuts:ar(e.shortcuts)||Jo.shortcuts,quickButtons:mi(e)}},ki={...di,setItem:async(e,t)=>{if(!(ui>0))return di.setItem(e,t)}},Si=(e,t)=>t?xi({...e,...t}):e;let Ci=null;const Ai=Bo()($o((e,t)=>(Ci=e,{settings:Jo,persistedSettings:Jo,previewSettings:null,_hasHydrated:false,_syncVersion:0,setSettings:t=>e(e=>{const n=xi({...e.persistedSettings,...t});return {persistedSettings:n,previewSettings:null,settings:n}}),setPreviewSettings:t=>hi(()=>e(e=>({previewSettings:t,settings:Si(e.persistedSettings,t)}))),clearPreviewSettings:()=>hi(()=>e(e=>({previewSettings:null,settings:e.persistedSettings}))),updateNestedSetting:(t,n,r)=>e(e=>{const o=xi({...e.persistedSettings,[t]:{...e.persistedSettings[t],[n]:r}});return {persistedSettings:o,previewSettings:null,settings:o}}),updateDeepSetting:(t,n,r,o)=>e(e=>{const i=e.persistedSettings[t],a=i?.[n]||{},s=xi({...e.persistedSettings,[t]:{...i,[n]:{...a,[r]:o}}});return {persistedSettings:s,previewSettings:null,settings:s}}),replaceSettings:t=>e(()=>{const e=xi({...Jo,...t});return {persistedSettings:e,previewSettings:null,settings:e}}),resetSettings:()=>e(()=>{const e=xi(Jo);return {persistedSettings:e,previewSettings:null,settings:e}}),setHasHydrated:t=>hi(()=>e({_hasHydrated:t}))}),{name:"settings",storage:Oo(()=>ki),partialize:e=>({settings:e.persistedSettings}),merge:(e,t)=>{try{const n=e?.settings,r=xi(n??t.persistedSettings);return {...t,settings:r,persistedSettings:r,previewSettings:null}}catch(n){throw console.error("[ophel] settings merge THREW:",n),n}},onRehydrateStorage:()=>(e,t)=>{hi(()=>{if(e){const t=xi(e.settings);return void Ci?.({persistedSettings:t,previewSettings:null,settings:t,_hasHydrated:!0})}Ci?.({_hasHydrated:!0});});}})),Ei=()=>Ai(e=>e._hasHydrated),Ti=()=>Ai.getState().settings,Mi=e=>Ai.subscribe(t=>e(t.settings)),_i=Object.freeze(Object.defineProperty({__proto__:null,getSettingsState:Ti,subscribeSettings:Mi,useSettingsHydrated:Ei,useSettingsStore:Ai},Symbol.toStringTag,{value:"Module"})),Ii=new Map;function Li(e,t=2e3,n={}){let r=document.body,o=null;const i=document.querySelectorAll("plasmo-csui, #ophel-userscript-root");for(const u of i)if(u.shadowRoot){const e=u.shadowRoot.querySelector(".gh-root, #plasmo-shadow-container, .plasmo-csui-container, #ophel-app-container");if(e){r=e,o=u;break}r=u.shadowRoot,o=u;}const a=r.getRootNode(),s=a instanceof ShadowRoot?a:document.head,l=document.getElementById("gh-toast");l&&l.remove();for(const u of i)if(u.shadowRoot){const e=u.shadowRoot.querySelector("#gh-toast");e&&e.remove();}if(!s.querySelector("#gh-toast-style")){const e=document.createElement("style");e.id="gh-toast-style",e.textContent=`\n${ue}\n .gh-toast {\n position: fixed !important;\n left: 50% !important;\n background: color-mix(in srgb, var(--gh-bg, #ffffff) 90%, transparent) !important;\n color: var(--gh-text, #1f2937) !important;\n border: 1px solid color-mix(in srgb, var(--gh-primary, #6366f1) 20%, var(--gh-border, #d1d5db)) !important;\n padding: 10px 22px !important;\n border-radius: 9999px !important;\n font-size: 14px !important;\n font-weight: 600 !important;\n box-shadow:\n var(--gh-shadow-lg, 0 8px 32px rgba(0, 0, 0, 0.35)),\n 0 0 0 1px inset color-mix(in srgb, var(--gh-primary, #6366f1) 15%, transparent) !important;\n z-index: 2147483646 !important; /* 刚好在一级最高层(禅模式按钮 2147483647)之下 */\n pointer-events: none !important;\n opacity: 0 !important;\n transform: translateY(-20px) translateX(-50%) scale(0.92) !important;\n transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1), transform 0.3s cubic-bezier(0.16, 1, 0.3, 1) !important;\n font-family: ${fe()} !important;\n letter-spacing: 0.2px !important;\n backdrop-filter: blur(16px) saturate(160%) !important;\n -webkit-backdrop-filter: blur(16px) saturate(160%) !important;\n max-width: min(calc(100vw - 32px), 480px);\n white-space: nowrap !important;\n overflow: hidden !important;\n text-overflow: ellipsis !important;\n }\n .gh-toast.show {\n opacity: 1 !important;\n transform: translateY(0) translateX(-50%) scale(1) !important;\n }\n .gh-toast--outline-nav {\n max-width: 360px !important;\n }\n @media (prefers-reduced-motion: reduce) {\n .gh-toast {\n transition: opacity 0.2s ease !important;\n transform: translateX(-50%) !important;\n }\n .gh-toast.show {\n transform: translateX(-50%) !important;\n }\n }\n `,s.appendChild(e);}const c=document.createElement("div");c.id="gh-toast",c.className="gh-toast";const d=!(!document.getElementById("gh-zen-mode-exit-host")&&!o?.shadowRoot?.querySelector("#gh-zen-mode-exit-host"));c.style.setProperty("top",d?"84px":"32px","important"),n.className&&c.classList.add(n.className),n.maxWidth&&Number.isFinite(n.maxWidth)&&(c.style.maxWidth=`${n.maxWidth}px`),c.textContent=e,r.appendChild(c),requestAnimationFrame(()=>{c.classList.add("show");}),setTimeout(()=>{c.classList.remove("show"),setTimeout(()=>{c.parentNode&&c.parentNode.removeChild(c);},300);},t);}function Ni(e,t=2e3,n={},r=1500,o=e){const i=Date.now();i-(Ii.get(o)||0){t(r,n);});return ()=>GM_removeValueChangeListener(n)}},fetch:async(e,t)=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,data:t?.body,responseType:"text",onload(r){const o=r.status>=200&&r.status<300;n({ok:o,status:r.status,statusText:r.statusText,text:async()=>r.responseText,json:async()=>JSON.parse(r.responseText),blob:async()=>new Promise((n,r)=>{GM_xmlhttpRequest({url:e,method:t?.method||"GET",headers:t?.headers,responseType:"blob",onload(e){n(e.response);},onerror:r});})});},onerror(e){r(e);}});}),notify(e){GM_notification({title:e.title,text:e.message,timeout:e.timeout??5e3,silent:e.silent??true,onclick:()=>{window.focus();}});},getNotificationSoundUrl:e=>window.__OPHEL_NOTIFICATION_SOUND_URLS__?.[e],focusWindow(){window.focus();},openTab(e){window.open(e,"_blank");},hasCapability:e=>!["cookies","permissions","tabs","declarativeNetRequest","commands"].includes(e),async getClaudeSessionKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:se("claudeNotOnSiteHint")};const e=document.cookie.match(/sessionKey=([^;]+)/);return e&&e[1]?{success:true,sessionKey:decodeURIComponent(e[1])}:{success:false,error:se("claudeNoCookieFound")}},testClaudeSessionKey:async e=>new Promise(t=>{GM_xmlhttpRequest({url:"https://claude.ai/api/organizations",method:"GET",headers:{Accept:"application/json",Cookie:`sessionKey=${e}`},onload(e){try{if(200!==e.status)return void t({success:!0,isValid:!1,error:`HTTP ${e.status}`});const n=e.responseText;if(n.toLowerCase().includes("unauthorized"))return void t({success:!0,isValid:!1,error:"Unauthorized"});const r=JSON.parse(n);if(!Array.isArray(r)||0===r.length)return void t({success:!0,isValid:!1,error:"No organizations"});const o=r[0],i=o?.rate_limit_tier,a=o?.capabilities||[],s=o?.api_disabled_reason;let l="Unknown";"default_claude_max_5x"===i?l="Max(5x)":"default_claude_max_20x"===i?l="Max(20x)":"default_claude_ai"===i?l="Free":"auto_api_evaluation"===i?l="out_of_credits"===s?"API(无额度)":"API":a.includes("claude_max")?l="Max":a.includes("api")?l="API":a.includes("chat")&&(l="Free"),t({success:!0,isValid:!0,accountType:l});}catch{t({success:true,isValid:false,error:"Parse error"});}},onerror(){t({success:false,isValid:false,error:"Request failed"});}});}),async setClaudeSessionKey(e){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:se("claudeNotOnSiteHint")};const t=new Date(Date.now()+31536e6).toUTCString();return document.cookie=`sessionKey=${encodeURIComponent(e)}; domain=.claude.ai; path=/; expires=${t}; secure; samesite=lax`,location.href="https://claude.ai/",{success:true}},async switchNextClaudeKey(){if(!location.hostname.endsWith("claude.ai"))return {success:false,error:se("claudeNotOnSiteHint")};try{const e=GM_getValue("claudeSessionKeys"),t=e?.state?.keys||[];if(0===t.length)return {success:!1,error:"noClaudeKeys"};const n=e?.state?.currentKeyId;let r=t.filter(e=>!1!==e.isValid);0===r.length&&(r=[...t]),r.sort((e,t)=>{const n=e.accountType?.toLowerCase()?.includes("pro"),r=t.accountType?.toLowerCase()?.includes("pro");return n&&!r?-1:!n&&r?1:e.name.localeCompare(t.name)});const o=r.findIndex(e=>e.id===n);if(1===r.length&&-1!==o)return {success:!1,error:"claudeOnlyOneKey"};let i=0;-1!==o&&(i=(o+1)%r.length);const a=r[i];if(!a)return {success:!1,error:"nextKeyNotFound"};if(a.key){const e=new Date(Date.now()+31536e6).toUTCString();document.cookie=`sessionKey=${encodeURIComponent(a.key)}; domain=.claude.ai; path=/; expires=${e}; secure; samesite=lax`;}return e?.state&&(e.state.currentKeyId=a.id,GM_setValue("claudeSessionKeys",e)),location.href="https://claude.ai/",{success:!0,keyName:a.name}}catch(e){return {success:false,error:e.message}}}};const Ri=Object.freeze(Object.defineProperty({__proto__:null,get platform(){return qi}},Symbol.toStringTag,{value:"Module"})),Pi=String.fromCodePoint(128228),zi=String.fromCodePoint(128587),Bi=String.fromCodePoint(129302),Oi="data-ophel-export-markdown-href";function Fi(e){if(!e)return "";const t=e=>e.replace(/\r\n?/g,"\n"),n=e=>{const t=e?.split(/\r?\n/)[0]?.trim().toLowerCase()||"";return !t||/^(copy|复制)$/.test(t)?"":t.replace(/\s+/g,"")},r=e=>{const n=t(e).replace(/\s*\n\s*/g," ").trim();return n?`$${n}$`:""},o=e=>{const n=t(e).trim();if(!n)return "";return n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n)?`\n$$\n${n}\n$$\n`:`\n$$${n}$$\n`},i=e=>{const t=e.querySelector('annotation[encoding="application/x-tex"]'),n=t?.textContent?.trim();if(n)return n;const r=e.getAttribute("data-tex")||e.getAttribute("data-latex");if(r)return r.trim();const o=e.getAttribute("aria-label");return o?o.trim():""},a=e=>{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const t=e,n=t.tagName?.toLowerCase()||"";return "br"===n?"\n":"style"===n||"script"===n||"template"===n||"noscript"===n||"button"===n||"svg"===n||"annotation"===n||"annotation-xml"===n||t.classList?.contains("gh-assistant-mermaid")||t.classList?.contains("katex-mathml")||t.classList?.contains("katex-html")?"":Array.from(t.childNodes).map(a).join("")},s=e=>{const t=e.querySelector("code"),r=t?.className.match(/language-([A-Za-z0-9_#+-]+)/),o=!!e.querySelector("#code-block-viewer, .cm-editor"),i=[e.getAttribute("data-language"),e.querySelector(".cm-content")?.getAttribute("data-language"),r?.[1],e.querySelector(".code-block-decoration span")?.textContent,o?e.querySelector('.sticky [class*="font-medium"]')?.textContent:null];for(const a of i){const e=n(a);if(e)return e}return ""},l=e=>{const n=!!e.querySelector("#code-block-viewer, .cm-editor"),r=e.matches(".cm-content")?e:e.querySelector(".cm-content")??null;if(r){const n=t(a(r)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}const o=e.matches("code")?e:e.querySelector("pre code, code")??null;if(o){const n=t(a(o)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}if(!n){const n=t(a(e)).replace(/\n+$/,"");if(n.trim())return {lang:s(e),code:n}}return null},c=(e,t)=>Array.from(e.childNodes).map(e=>h(e,t)).join(""),d=(e,t)=>{const n="ol"===e.tagName.toLowerCase(),r=Array.from(e.children).filter(e=>"li"===e.tagName?.toLowerCase()).map((e,r)=>u(e,t,n?r+1:null)).filter(Boolean).join("\n");return r?`\n${r}\n\n`:""},u=(e,n,r)=>{const o=" ".repeat(n),i=null===r?"-":`${r}.`,a=[],s=[];for(const t of Array.from(e.childNodes)){if(t.nodeType===Node.ELEMENT_NODE){const e=t,r=e.tagName.toLowerCase();if("ul"===r||"ol"===r){const t=d(e,n+1).replace(/^\n+|\n+$/g,"");t&&s.push(t);continue}}a.push(h(t,{listDepth:n,inListItem:true}));}const l=(c=a.join(""),t(c).replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim());var c;let u=l?((e,n,r)=>{const o=t(e).split("\n"),[i="",...a]=o;return 0===a.length?`${n}${i}`:[`${n}${i}`,...a.map(e=>e?`${r}${e}`:"")].join("\n")})(l,`${o}${i} `,`${o} `):`${o}${i}`;return s.length>0&&(u=`${u.trimEnd()}\n${s.join("\n")}`),u},h=(e,t={listDepth:0,inListItem:false})=>{try{if(!e)return "";if(e.nodeType===Node.TEXT_NODE)return e.textContent||"";if(e.nodeType!==Node.ELEMENT_NODE)return "";const n=e;if(n.classList?.contains("gh-assistant-mermaid"))return "";if(n.classList?.contains("math-block")){const e=n.getAttribute("data-math");if(e)return o(e)}if(n.classList?.contains("math-inline")){const e=n.getAttribute("data-math");if(e)return r(e)}if(n.classList?.contains("katex-display")){const e=i(n);if(e)return o(e)}if(n.classList?.contains("katex")){const e=i(n);if(e)return r(e)}if(n.classList?.contains("katex-mathml"))return "";if(n.classList?.contains("katex-html"))return "";if("BUTTON"===n.tagName||"SVG"===n.tagName)return "";if(n.classList?.contains("cm-content")&&n.getAttribute("data-language")){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if(n.classList?.contains("cm-cursorLayer")||n.classList?.contains("cm-selectionLayer")||n.classList?.contains("cm-announced"))return "";const a=n.tagName?.toLowerCase()||"";if(!a)return "";if("annotation"===a||"annotation-xml"===a)return "";if("style"===a||"script"===a||"template"===a||"noscript"===a)return "";if("img"===a){const e=n.alt||n.getAttribute("alt")||"图片";return `![${e}](${n.getAttribute("src")||n.src||""})`}if("code-block"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("pre"===a){const e=l(n);if(e)return `\n\`\`\`${e.lang}\n${e.code}\n\`\`\`\n`}if("code"===a)return "pre"===n.parentElement?.tagName.toLowerCase()?"":`\`${n.textContent}\``;if("table"===a){const e=[],t=n.querySelector("thead"),r=n.querySelector("tbody"),o=e=>e.textContent?.trim()||"";if(t){const n=t.querySelector("tr");if(n){const t=Array.from(n.querySelectorAll("td, th")).map(o);t.some(e=>e)&&(e.push("| "+t.join(" | ")+" |"),e.push("| "+t.map(()=>"---").join(" | ")+" |"));}}if(r){r.querySelectorAll("tr").forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&e.push("| "+n.join(" | ")+" |");});}if(!t&&!r){const t=n.querySelectorAll("tr");let r=!0;t.forEach(t=>{const n=Array.from(t.querySelectorAll("td, th")).map(o);n.some(e=>e)&&(e.push("| "+n.join(" | ")+" |"),r&&(e.push("| "+n.map(()=>"---").join(" | ")+" |"),r=!1));});}return e.length>0?"\n"+e.join("\n")+"\n":""}if("table-block"===a||"ucs-markdown-table"===a){const e=n.querySelector("table");if(e)return h(e)}switch(a){case "h1":return `\n# ${c(n,t)}\n`;case "h2":return `\n## ${c(n,t)}\n`;case "h3":return `\n### ${c(n,t)}\n`;case "h4":return `\n#### ${c(n,t)}\n`;case "h5":return `\n##### ${c(n,t)}\n`;case "h6":return `\n###### ${c(n,t)}\n`;case "strong":case "b":return `**${c(n,t)}**`;case "em":case "i":return `*${c(n,t)}*`;case "a":return `[${c(n,t)}](${n.getAttribute(Oi)||n.href||""})`;case "li":return u(n,t.listDepth,"ol"===n.parentElement?.tagName?.toLowerCase()?Array.from(n.parentElement.children).filter(e=>"li"===e.tagName?.toLowerCase()).indexOf(n)+1:null);case "p":return t.inListItem?`${c(n,t).trim()}\n`:`${c(n,t)}\n\n`;case "br":return "\n";case "ul":case "ol":return d(n,t.listDepth);case "blockquote":{const e=c(n,t).replace(/\r\n/g,"\n").split("\n");return `\n${e.map(e=>e.trim().length>0?`> ${e}`:">").join("\n")}\n`}default:return n.shadowRoot?Array.from(n.shadowRoot.childNodes).map(e=>h(e,t)).join(""):c(n,t)}}catch(n){return console.error("Error processing node in htmlToMarkdown:",n),e.textContent||""}};return h(e).trim()}function $i(e,t){const n=[];return n.push(`# ${e.title}`),n.push(""),n.push("---"),n.push(""),n.push(`## ${Pi} ${se("exportMetaTitle")}`),n.push(`- **${se("exportMetaConvTitle")}**: ${e.title}`),n.push(`- **${se("exportMetaTime")}**: ${e.exportTime}`),n.push(`- **${se("exportMetaSource")}**: ${e.source}`),n.push(`- **${se("exportMetaUrl")}**: ${e.url}`),n.push(""),n.push("---"),n.push(""),t.forEach(t=>{if("user"===t.role){const r=e.customUserName||se("exportUserLabel");n.push(`## ${zi} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}else {const r=e.customModelName||e.source;n.push(`## ${Bi} ${r}`),n.push(""),n.push(t.content),n.push(""),n.push("---"),n.push("");}}),n.join("\n")}const Ui=new TextEncoder;let ji=null;function Hi(e){const t=function(){if(ji)return ji;const e=new Uint32Array(256);for(let t=0;t<256;t+=1){let n=t;for(let e=0;e<8;e+=1)n=1&n?3988292384^n>>>1:n>>>1;e[t]=n>>>0;}return ji=e,e}();let n=4294967295;for(const r of e)n=t[255&(n^r)]^n>>>8;return (4294967295^n)>>>0}function Wi(e,t,n){return e[t]=255&n,e[t+1]=n>>>8&255,t+2}function Gi(e,t,n){return e[t]=255&n,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24&255,t+4}function Qi(e){const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length;}),n}async function Vi(e){return "string"==typeof e?Ui.encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(await e.arrayBuffer())}function Ki(e,t){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim()||t}function Zi(e,t){const n=e.replace(/\\/g,"/").replace(/^[a-zA-Z]:\//,"").replace(/^\/+/,"").split("/").map(e=>Ki(e,"asset")).filter(e=>"."!==e&&".."!==e);return n.length>0?n.join("/"):t}function Yi(e,t){if(!t.has(e))return t.add(e),e;const n=e.lastIndexOf("/"),r=n>=0?`${e.slice(0,n+1)}`:"",o=n>=0?e.slice(n+1):e,i=o.lastIndexOf("."),a=i>0?o.slice(0,i):o,s=i>0?o.slice(i):"";for(let l=2;l<1e4;l+=1){const e=`${r}${a}-${l}${s}`;if(!t.has(e))return t.add(e),e}throw new Error(`Unable to create unique zip path for ${e}`)}function Ji(e,t,n="assets/asset"){return Yi(function(e,t="assets/asset"){return Zi(e,t)}(e,n),t)}function Xi(e){return `assets/${Ki(e.name,e.id||"asset")}`}async function ea(e){if(void 0!==e.content)return e.content;if(!e.sourceUrl)throw new Error("Asset has no content or source URL");try{const t=await fetch(e.sourceUrl,{credentials:"include"});if(!t.ok)throw new Error(`Asset fetch failed with HTTP ${t.status}`);return t.blob()}catch(t){if(!/^https?:\/\//i.test(e.sourceUrl))throw t;try{const t=await qi.fetch(e.sourceUrl);if(!t.ok)throw new Error(`Asset proxy fetch failed with HTTP ${t.status}`);return t.blob()}catch(n){throw new Error(`Asset fetch failed: ${ta(t)}; proxy fetch failed: ${ta(n)}`)}}}function ta(e){return e instanceof Error?e.message:String(e)}async function na(e){const t=[],n=[],{dosDate:r,dosTime:o}=function(e=new Date){const t=Math.max(1980,e.getFullYear());return {dosTime:e.getHours()<<11|e.getMinutes()<<5|Math.floor(e.getSeconds()/2),dosDate:t-1980<<9|e.getMonth()+1<<5|e.getDate()}}();let i=0;for(const d of e){const e=Zi(d.path,"file"),a=Ui.encode(e),s=await Vi(d.data),l=Hi(s),c=new Uint8Array(30+a.length);let u=0;u=Gi(c,u,67324752),u=Wi(c,u,20),u=Wi(c,u,2048),u=Wi(c,u,0),u=Wi(c,u,o),u=Wi(c,u,r),u=Gi(c,u,l),u=Gi(c,u,s.length),u=Gi(c,u,s.length),u=Wi(c,u,a.length),u=Wi(c,u,0),c.set(a,u),t.push({path:e,data:s,crc32:l,dosTime:o,dosDate:r,localHeaderOffset:i}),n.push(c,s),i+=c.length+s.length;}const a=i;t.forEach(e=>{const t=Ui.encode(e.path),r=new Uint8Array(46+t.length);let o=0;o=Gi(r,o,33639248),o=Wi(r,o,20),o=Wi(r,o,20),o=Wi(r,o,2048),o=Wi(r,o,0),o=Wi(r,o,e.dosTime),o=Wi(r,o,e.dosDate),o=Gi(r,o,e.crc32),o=Gi(r,o,e.data.length),o=Gi(r,o,e.data.length),o=Wi(r,o,t.length),o=Wi(r,o,0),o=Wi(r,o,0),o=Wi(r,o,0),o=Wi(r,o,0),o=Gi(r,o,0),o=Gi(r,o,e.localHeaderOffset),r.set(t,o),n.push(r),i+=r.length;});const s=i-a,l=new Uint8Array(22);let c=0;return c=Gi(l,c,101010256),c=Wi(l,c,0),c=Wi(l,c,0),c=Wi(l,c,t.length),c=Wi(l,c,t.length),c=Gi(l,c,s),c=Gi(l,c,a),Wi(l,c,0),n.push(l),new Blob([Qi(n)],{type:"application/zip"})}async function ra(e,t,n="text/plain;charset=utf-8"){try{const r=new Blob([e],{type:n});return await oa(r,t)}catch(r){return console.error("[Exporter] Download failed:",r),Li(se("exportFailed")),false}}async function oa(e,t){try{const n=URL.createObjectURL(e),r=document.createElement("a");return r.href=n,r.download=t,r.click(),URL.revokeObjectURL(n),!0}catch(n){return console.error("[Exporter] Download failed:",n),Li(se("exportFailed")),false}}function ia(){return {assets:[],usedPaths:new Set,imagePathsBySource:new Map,filePathsBySource:new Map}}function aa(e,t="file",n=120){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim().substring(0,n)||t}function sa(e){return e.replace(/[[\]]/g,"\\$&")}function la(e,t="asset"){const n=e.filter(e=>Boolean(e)).map(e=>function(e,t="asset"){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}(e,"")).filter(Boolean).join("-");return n||t}function ca(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.host.toLowerCase()}${t.pathname}`}catch{return e.split(/[?#]/)[0]}}function da(e,t={}){if(!e)return "";try{const n=new URL(e,window.location.href).pathname,r=decodeURIComponent(n.split("/").pop()||"");return t.ignoreGenericDownload&&"download"===r?"":r}catch{return ""}}function ua(e){return e.match(/\.([A-Za-z0-9]{1,10})(?:$|[?#\s])/)?.[1]?.toLowerCase()||""}function ha(e){return ua(da(e))}function ga(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean);let n="";for(let a=0;a/^[^.\s].*\.[A-Za-z0-9]{1,10}$/.test(e))||"");const r=t.find(e=>/^\.[A-Za-z0-9]{1,10}$/.test(e))||"",o=t.find(e=>/^\d+(?:\.\d+)?\s*(?:B|KB|MB|GB|TB)$/i.test(e))||"",i=n||t.find(e=>e!==o&&!/^\.[A-Za-z0-9]{1,10}$/.test(e))||r;return {name:i,type:ua(i)||(r?r.slice(1):""),sizeLabel:o}}function pa(e,t="document"){const n=e.replace(/\r\n/g,"\n").split("\n").find(e=>/^#\s+/.test(e.trim()));return n?.replace(/^#\s+/,"").trim()||t}function ma(e,t="document"){return `${aa(e,t,80)}.md`}function fa(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}function ba(e){if(!e)return false;if(/^(blob:|data:)/i.test(e))return true;if(!/^https?:\/\//i.test(e))return false;try{const t=new URL(e);return (t.hostname!==window.location.hostname||!/^\/?(app|share)(\/|$)/.test(t.pathname))&&!/faviconV2|google_logo_icon|\/32\/type\//i.test(t.href)}catch{return false}}function ya(e){const[t,n=""]=e.split(",",2),r=t.match(/^data:([^;]+)/)?.[1]||"application/octet-stream";if(!/;base64/i.test(t))return new Blob([decodeURIComponent(n)],{type:r});const o=atob(n),i=new Uint8Array(o.length);for(let a=0;aTa(e,t,n)).filter(Boolean)}function _a(e,t,n){return e.filter(e=>"image"===e.kind&&Boolean(e.source)).map(e=>Ta({source:e.source||"",alt:n.getAlt?.(e)||e.name,extensionHint:n.getExtensionHint?.(e)||e.name||e.type||""},t,{siteId:n.siteId,role:n.role||"user",category:n.category||"image",fallbackAlt:n.fallbackAlt||"uploaded image",directory:n.directory,prefix:n.prefix})).filter(Boolean)}function Ia(e,t,n){const r=n.prefix||la([n.siteId,n.role||"user",n.category||"file"]),o=n.fallbackName||"attachment";return e.filter(e=>n.includeAttachment?n.includeAttachment(e):"file"===e.kind).map(e=>{const i=sa(n.getLabel?.(e)||function(e){const t=e.name||"attachment",n=e.type?.trim()||"",r=[n&&!t.toLowerCase().endsWith(`.${n.toLowerCase()}`)?n:"",e.sizeLabel||""].filter(Boolean);return r.length>0?`${t} (${r.join(", ")})`:t}(e)||o),a=e.source&&t?Ea(t,{source:e.source,name:e.name||o,mimeHint:n.getMimeHint?.(e)||e.type||e.name,directory:n.directory||"assets/files",idPrefix:r}):e.source;return a?`- [${i}](${a})`:`- ${i}`})}function La(e,t,n={}){const r=function(e,t,n={}){const r=n.fallbackTitle||"document",o=ma(n.title||pa(t,r),r),i=n.description??(n.title||void 0),a=e.assets.find(e=>"document"===e.kind&&e.content===t&&e.description===i);if(a?.relativePath)return {name:a.name,path:a.relativePath};const s=Ji(`${(n.directory||"assets/documents").replace(/\/+$/,"")}/${o}`,e.usedPaths),l=s.split("/").pop()||o;return e.assets.push({id:`${n.idPrefix||"document"}-${e.assets.length+1}`,name:l,relativePath:s,mimeType:"text/markdown;charset=utf-8",kind:"document",content:t,description:i}),{name:l,path:s}}(e,t,n);return `[${sa(n.title||r.name)}](${r.path})`}const Na="data-ophel-managed-tab-title",Da=/\{(?:status|title|model|site)\}/g,qa="{model}",Ra={"(":")","[":"]","{":"}","<":">","(":")","【":"】","《":"》","「":"」","『":"』"};function Pa(e){const t=e?.replace(/\s+/g," ").trim();return t||null}function za(){"undefined"!=typeof document&&document.documentElement?.removeAttribute(Na);}function Ba(){return "undefined"==typeof document?null:document.documentElement?.getAttribute(Na)||null}function Oa(e,t={}){const n=Pa(e);if(!n)return null;const r=Ba(),o=Pa(t.expectedManagedTitle),i=Pa(t.privacyTitle),a=Pa(t.siteName),s=Boolean(o&&n===o)||Boolean(r&&n===r),l=s||true===t.hasManagedTitleSignal;if(i&&n===i)return null;const c=function(e,t){let n=e,r=t.hasManagedSignal;r&&/^(?:[⏳✅]\s*)+/u.test(n)&&(n=n.replace(/^(?:[⏳✅]\s*)+/u,""));const o=function(e,t){const n=t.titleFormat||"";if(!n.includes("{title}"))return null;const r=function(e,t){const n=[e],r=Fa(e);r!==e&&n.push(r);const o=[];return n.forEach(e=>{const n=function(e,t){const n=/\{(status|title|model|site)\}/g;let r="^\\s*",o=0,i=false,a=0;for(const s of e.matchAll(n)){r+=Ha(e.slice(o,s.index));const n=s[1];if("title"===n)r+=i?"[\\s\\S]*?":"(?[\\s\\S]+?)",i=true;else if("status"===n)r+=`(?(?:[⏳✅]\\s*)*)`,a+=1;else if("model"===n)r+=`(?\\[[^\\]]{1,160}\\])?`,a+=1;else if("site"===n){const e=Pa(t);r+=e?`(?${Ha(e)})`:`(?[\\s\\S]*?)`,a+=1;}o=s.index+s[0].length;}if(r+=Ha(e.slice(o)),r+="\\s*$",!i)return null;try{return new RegExp(r,"u")}catch{return null}}(e,t);n&&o.push(n);}),o}(n,t.siteName);if(0===r.length)return null;let o=e,i=false,a=t.hasManagedSignal;for(let s=0;s<20;s+=1){const e=ja(o,r);if(!e)break;if(!a&&!e.hasManagedSignal)break;if(!e.title||e.title===o)break;o=e.title,i=true,a=true;}return i?Pa(o):null}(n,{hasManagedSignal:r,siteName:t.siteName,titleFormat:t.titleFormat});o&&o!==n&&(n=o,r=true);return Pa(n)}(n,{hasManagedSignal:l,siteName:t.siteName,titleFormat:t.titleFormat});return c?a&&c===a&&c!==n&&s||i&&c===i?null:c:null}function Fa(e){let t=e;for(;t.includes(qa);){const e=$a(t);if(e===t)return t.replace(/\{model\}/g,"");t=e;}return t}function $a(e){const t=Array.from(e.matchAll(Da)),n=t.findIndex(e=>e[0]===qa&&void 0!==e.index);if(n<0)return e;const r=t[n-1],o=t[n+1],i=t[n],a=i.index??0,s=a+i[0].length,l=void 0!==r?.index?r.index+r[0].length:0,c=o?.index??e.length,d=r&&o&&"{status}"!==r[0]&&"{status}"!==o[0]?function(e,t){const n=function(e,t){const n=e.match(/^(.*?)([\[({<(【《「『])\s*$/u),r=t.match(/^\s*([\])}>)】》」』])(.*)$/u);if(!n||!r)return null;const o=n[2],i=r[1];return Ra[o]!==i?null:`${n[1]}${r[2]}`}(e,t);if(null!==n)return n;const r=Ua(e),o=Ua(t);return r&&!o?t:!r&&o||e.trim()&&e.trim()===t.trim()?e:e.trim()?(t.trim(),e):t}(e.slice(l,a),e.slice(s,c)):"";return `${e.slice(0,l)}${d}${e.slice(c)}`}function Ua(e){return /[\p{L}\p{N}]/u.test(e)}function ja(e,t){for(const n of t){const t=n.exec(e),r=Pa(t?.groups?.ophelTitle);if(t&&r)return {title:r,hasManagedSignal:false}}return null}function Ha(e){return Wa(e).replace(/\s+/g,"\\s+")}function Wa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Ga={MAX_DEPTH:15,DEFAULT_TIMEOUT:5e3,POLL_INTERVAL:50,CACHE_TTL:3e5},Qa={ELEMENT:1,DOCUMENT:9,FRAGMENT:11},Va=["keydown","keypress","keyup"],Ka="data-ophel-interaction-layer",Za={[Ka]:"true"},Ya=[`[${Ka}="true"]`,".gh-dialog-overlay",".conversations-dialog-overlay",".conversations-folder-menu",".conversations-tag-filter-menu",".prompt-modal",".prompt-preview-modal",".import-dialog",".settings-modal-overlay",".settings-search-overlay",".quick-menu-popover"].join(", "),Ja=e=>(e??("undefined"!=typeof document&&document.body?[document.body]:[])).some(e=>Boolean(e.querySelector(Ya))),Xa=e=>e instanceof HTMLElement&&("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||e.isContentEditable||"true"===e.getAttribute("contenteditable")||e.classList.contains("ProseMirror")),es=(e,t={})=>{const{events:n=Va,capture:r=true}=t,o=e=>{(e=>{const t=("function"==typeof e.composedPath?e.composedPath():[]).find(e=>e instanceof HTMLElement)||null;return Xa(t)?t:Xa(e.target)?e.target:null})(e)&&(e.stopPropagation(),e.stopImmediatePropagation());};return n.forEach(t=>{e.addEventListener(t,o,r);}),()=>{n.forEach(t=>{e.removeEventListener(t,o,r);});}},ts={isValidContext:e=>null!==e&&Object.values(Qa).includes(e.nodeType),isVisible:e=>e&&null!==e.offsetParent,isConnected:e=>e&&e.isConnected,createCleanupManager(){const e=new Set;return {add:t=>(e.add(t),()=>e.delete(t)),execute(){e.forEach(e=>{try{e();}catch(t){console.error("[DOMToolkit] Cleanup error:",t);}}),e.clear();},get size(){return e.size}}}};class ns{enabled=true;ttl;store=new WeakMap;timestamps=new WeakMap;constructor(e=Ga.CACHE_TTL){this.ttl=e;}setEnabled(e){this.enabled=e;}get(e,t){if(!this.enabled)return null;const n=this.store.get(e),r=this.timestamps.get(e);if(!n||!r)return null;const o=n.get(t);if(!o)return null;const i=r.get(t);return i&&Date.now()-i>this.ttl?(n.delete(t),r.delete(t),null):ts.isConnected(o)?o:(n.delete(t),r.delete(t),null)}set(e,t,n){if(!this.enabled||!n)return;let r=this.store.get(e),o=this.timestamps.get(e);r||(r=new Map,this.store.set(e,r)),o||(o=new Map,this.timestamps.set(e,o)),r.set(t,n),o.set(t,Date.now());}clear(){this.store=new WeakMap,this.timestamps=new WeakMap;}}class rs{observers=new Map;getSharedObserver(e){if(!this.observers.has(e)){const t=new Set,n=new MutationObserver(e=>{for(const n of e)for(const e of n.addedNodes)e.nodeType===Qa.ELEMENT&&t.forEach(t=>{try{t(e,n);}catch(r){console.error("[DOMToolkit] Observer callback error:",r);}});});n.observe(e,{childList:true,subtree:true}),this.observers.set(e,{observer:n,callbacks:t,refCount:0});}const t=this.observers.get(e);return t.refCount++,{addCallback:e=>t.callbacks.add(e),removeCallback:n=>{t.callbacks.delete(n),t.refCount--,0===t.refCount&&(t.observer.disconnect(),this.observers.delete(e));}}}destroy(){this.observers.forEach(({observer:e})=>e.disconnect()),this.observers.clear();}}const os=new class{cache;observerManager;doc;constructor(){this.doc=document,this.cache=new ns,this.observerManager=new rs;}configCache(e={}){"boolean"==typeof e.enabled&&this.cache.setEnabled(e.enabled);}clearCache(){this.cache.clear();}getComposedParent(e){if(!e)return null;if(e instanceof ShadowRoot)return e.host;if(e instanceof Element&&e.assignedSlot)return e.assignedSlot;if(e.parentNode)return e.parentNode;const t=e.getRootNode?.();return t instanceof ShadowRoot?t.host:null}getComposedParentElement(e){let t=this.getComposedParent(e);for(;t;){if(t instanceof HTMLElement)return t;t=this.getComposedParent(t);}return null}closestComposed(e,t){let n=e;for(;n;){if(n instanceof HTMLElement)try{if(n.matches(t))return n}catch{return null}n=this.getComposedParent(n);}return null}query(e,t={}){const{parent:n=this.doc,all:r=false,shadow:o=true,maxDepth:i=Ga.MAX_DEPTH,useCache:a=true,filter:s=null}=t,l=Array.isArray(e)?e:[e],c=a&&!s;if(!r&&c&&1===l.length){const e=this.cache.get(n,l[0]);if(e)return e}for(const d of l)try{if(r){const e=Array.from(n.querySelectorAll(d)),t=s?e.filter(s):[...e];if(o&&this.collectInShadow(n,d,t,0,i,s),t.length>0)return t}else {const e=n.querySelectorAll(d);for(const t of e)if(!s||s(t))return c&&this.cache.set(n,d,t),t}}catch{}if(o&&!r){const e=this.findInShadow(n,l,0,i,s);return e&&c&&1===l.length&&this.cache.set(n,l[0],e),e}return r?[]:null}findInShadow(e,t,n,r,o){if(n>r)return null;if(e!==this.doc&&e.querySelectorAll)for(const a of t)try{const t=e.querySelectorAll(a);for(const e of t)if(!o||o(e))return e}catch{}const i=e.querySelectorAll?e.querySelectorAll("*"):[];for(const a of i)if(a.shadowRoot){const e=this.findInShadow(a.shadowRoot,t,n+1,r,o);if(e)return e}return null}collectInShadow(e,t,n,r,o,i){if(r>o)return;if(e!==this.doc&&e.querySelectorAll)try{const r=e.querySelectorAll(t);for(const e of r)n.includes(e)||i&&!i(e)||n.push(e);}catch{}const a=e.querySelectorAll?e.querySelectorAll("*"):[];for(const s of a)s.shadowRoot&&this.collectInShadow(s.shadowRoot,t,n,r+1,o,i);}async get(e,t={}){const{parent:n=this.doc,timeout:r=Ga.DEFAULT_TIMEOUT,shadow:o=true,filter:i=null}=t,a=this.query(e,{parent:n,shadow:o,filter:i});return a&&!Array.isArray(a)?a:new Promise(t=>{const a=ts.createCleanupManager(),s=Date.now();let l;r>0&&(l=setTimeout(()=>{a.execute(),t(null);},r),a.add(()=>clearTimeout(l)));const c=()=>{if(r>0&&Date.now()-s>=r)return;const l=this.query(e,{parent:n,shadow:o,filter:i});if(l&&!Array.isArray(l))return a.execute(),void t(l);const d=setTimeout(c,Ga.POLL_INTERVAL);a.add(()=>clearTimeout(d));},d=Array.isArray(e)?e:[e],u=this.observerManager.getSharedObserver(n),h=e=>{for(const n of d)try{if(e.matches?.(n)&&(!i||i(e)))return a.execute(),void t(e);if(e.querySelectorAll){const r=e.querySelectorAll(n);for(const e of r)if(!i||i(e))return a.execute(),void t(e)}}catch{}};u.addCallback(h),a.add(()=>u.removeCallback(h)),c();})}each(e,t,n={}){const{parent:r=this.doc,shadow:o=true}=n;if("function"!=typeof t)return console.error("[DOMToolkit] each: callback must be a function"),()=>{};const i=new WeakSet;let a=true;const s=(e,n)=>{if(a&&!i.has(e)){i.add(e);try{!1===t(e,n)&&d();}catch(r){console.error("[DOMToolkit] each callback error:",r),d();}}};this.query(e,{parent:r,all:true,shadow:o}).forEach(e=>s(e,false));const l=this.observerManager.getSharedObserver(r),c=t=>{if(a)try{t.matches?.(e)&&s(t,!0),t.querySelectorAll&&t.querySelectorAll(e).forEach(e=>s(e,!0));}catch{}};l.addCallback(c);const d=()=>{a&&(a=false,l.removeCallback(c));};return d}watch(e,t,n={}){const{debounce:r=0,childList:o=true,attributes:i=true,characterData:a=false,subtree:s=false,attributeFilter:l}=n;if(!ts.isValidContext(e))return console.error("[DOMToolkit] watch: invalid element"),()=>{};let c=null;const d=new MutationObserver((e,n)=>{if(r>0)c&&clearTimeout(c),c=setTimeout(()=>{try{t(e,n);}catch(r){console.error("[DOMToolkit] watch callback error:",r);}},r);else try{t(e,n);}catch(o){console.error("[DOMToolkit] watch callback error:",o);}});return d.observe(e,{childList:o,attributes:i,characterData:a,subtree:s,attributeFilter:l}),()=>{c&&clearTimeout(c),d.disconnect();}}watchMultiple(e,t={}){const{debounce:n=0,characterData:r=true,childList:o=true,attributes:i=false}=t;if(!ts.isValidContext(e))return console.error("[DOMToolkit] watchMultiple: invalid container"),{add:()=>{},remove:()=>{},stop:()=>{}};const a=new Map;let s=null;const l=new Set,c=()=>{l.forEach(e=>{const t=a.get(e);if(t)try{t(e);}catch(n){console.error("[DOMToolkit] watchMultiple callback error:",n);}}),l.clear();},d=new MutationObserver(t=>{for(const n of t){let t=n.target;for(;t&&t!==e;){if(a.has(t)){l.add(t);break}t=t.parentNode;}}0!==l.size&&(n>0?(s&&clearTimeout(s),s=setTimeout(c,n)):c());});return d.observe(e,{characterData:r,childList:o,attributes:i,subtree:true}),{add:(e,t)=>a.set(e,t),remove:e=>a.delete(e),stop:()=>{s&&clearTimeout(s),d.disconnect(),a.clear();}}}on(e,t,n,r={}){const{parent:o=this.doc,capture:i=false}=r,a=e=>{const r=e.composedPath?e.composedPath():[e.target];for(const i of r){if(i===o||i===window)break;try{if(i.matches?.(t))return void n(e,i)}catch{}}try{const r=e.target.closest?.(t);r&&o.contains(r)&&n(e,r);}catch{}};return o.addEventListener(e,a,i),()=>o.removeEventListener(e,a,i)}create(e,t={},n=""){const r=this.doc.createElement(e);for(const[o,i]of Object.entries(t))"className"===o?r.className=i:"style"===o&&"object"==typeof i?Object.assign(r.style,i):"style"===o?r.setAttribute("style",i):"dataset"===o&&"object"==typeof i?Object.assign(r.dataset,i):o.startsWith("on")&&"function"==typeof i?r.addEventListener(o.slice(2).toLowerCase(),i):r.setAttribute(o,i);return n&&(r.textContent=n),r}createFromHTML(e,t={}){const{parent:n=null,mapIds:r=false}=t,o=this.doc.createElement("template");o.innerHTML=e.trim();const i=o.content.firstElementChild;if(!i)return null;if(n instanceof Element&&n.appendChild(i),r){const e={root:i};return i.id&&(e[i.id]=i),i.querySelectorAll("[id]").forEach(t=>{t.id&&(e[t.id]=t);}),e}return i}clear(e){for(;e.firstChild;)e.removeChild(e.firstChild);}css(e,t=null){if(t){const n=this.doc.getElementById(t);if(n)return n.textContent!==e&&(n.textContent=e),n}const n=this.doc.createElement("style");return t&&(n.id=t),n.textContent=e,this.doc.head.appendChild(n),n}cssToShadow(e,t,n=null){if(!e)return null;try{if(n){const r=e.getElementById(n);if(r)return r.textContent!==t&&(r.textContent=t),r}const r=this.doc.createElement("style");return n&&(r.id=n),r.textContent=t,e.appendChild(r),r}catch{return null}}cssToAllShadows(e,t,n={}){const{root:r=this.doc.body,filter:o=null}=n;if(!r)return 0;let i=0;const a=n=>{if(n.shadowRoot){if(o&&!o(n));else try{this.cssToShadow(n.shadowRoot,e,t),i++;}catch{}try{a(n.shadowRoot);}catch{}}const r=n.childNodes;for(let e=0;e{if(n>r)return;if(t.shadowRoot){try{e(t.shadowRoot,t);}catch(a){console.error("[DOMToolkit] walkShadowRoots callback error:",a);}try{o(t.shadowRoot,n+1);}catch{}}const i=t.childNodes;for(let e=0;ee.clientHeight)return e}const o=(e,t)=>{if(t>Ga.MAX_DEPTH)return null;const n=e.querySelectorAll?e.querySelectorAll("*"):[];for(const i of n){if(i.scrollHeight>i.clientHeight+r){const e=window.getComputedStyle(i);if("auto"===e.overflowY||"scroll"===e.overflowY||"auto"===e.overflow||"scroll"===e.overflow)return i}if(i.shadowRoot){const e=o(i.shadowRoot,t+1);if(e)return e}}return null},i=o(t,0);return i||(this.doc.documentElement.scrollHeight>this.doc.documentElement.clientHeight?this.doc.documentElement:this.doc.body)}destroy(){this.observerManager.destroy(),this.cache.clear();}},is=[/^flowchart\b/i,/^graph\b/i,/^sequenceDiagram\b/i,/^classDiagram(?:-v2)?\b/i,/^stateDiagram(?:-v2)?\b/i,/^erDiagram\b/i,/^gantt\b/i,/^gitGraph\b/i],as=[{pattern:/^flow\s*-?\s*chart\b/i,replacement:"flowchart"},{pattern:/^sequence\s*-?\s*diagram\b/i,replacement:"sequenceDiagram"},{pattern:/^class\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"classDiagram-v2"},{pattern:/^class\s*-?\s*diagram\b/i,replacement:"classDiagram"},{pattern:/^state\s*-?\s*diagram(?:\s*-\s*|\s+)v2\b/i,replacement:"stateDiagram-v2"},{pattern:/^state\s*-?\s*diagram\b/i,replacement:"stateDiagram"},{pattern:/^er\s*-?\s*diagram\b/i,replacement:"erDiagram"},{pattern:/^git\s*-?\s*graph\b/i,replacement:"gitGraph"}];function ss(e){const t="code"===e.nodeName.toLowerCase()?e:e.querySelector("code"),n=[e.getAttribute("data-language"),e.getAttribute("data-test-language"),t?.getAttribute("data-language"),t?.getAttribute("data-test-language"),e.className,t?.className].filter(Boolean).join(" ").toLowerCase();return n.includes("language-mermaid")||n.includes("lang-mermaid")||/\bmermaid\b/.test(n)}function ls(e){const t=cs(e);if(!t)return false;const n=t.split("\n").map(e=>e.trim()).find(e=>e&&!e.startsWith("%%"));return !!n&&is.some(e=>e.test(n))}function cs(e){const t=e.replace(/\r\n/g,"\n").replace(/\n+$/,"").trim();if(!t)return "";const n=t.split("\n"),r=function(e){return e.findIndex(e=>{const t=e.trim();return Boolean(t)&&!t.startsWith("%%")})}(n);if(-1===r)return t;const o=n[r],i=o.trim(),a=o.match(/^\s*/)?.[0]||"";for(const{pattern:s,replacement:l}of as){const e=i.match(s);if(e)return n[r]=`${a}${l}${i.slice(e[0].length)}`,n.join("\n")}return t}function ds(e){const t="code"===e.nodeName.toLowerCase()?e:e.querySelector("code");return (t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"").trim()||null}function us(e){const t=e.closest("code-block, ms-code-block, ucs-code-block");if(t)return t;const n=e.closest("pre");if(n)return n;const r=e.closest(".cm-editor, #code-block-viewer");return r||e}function hs(e){const t=os.query("code-block, ms-code-block, pre, pre code, [data-language], [data-test-language], [data-test-id='code-content'], .cm-content, #code-block-viewer",{parent:e,all:true,shadow:true})||[],n=new Set,r=[];for(const o of t){if(!(o instanceof HTMLElement))continue;if(o.closest(".gh-assistant-mermaid"))continue;const e=us(o);if(!e||n.has(e))continue;const t=ds(e);t&&((ss(e)||ls(t))&&(n.add(e),r.push({element:e,source:t})));}return r}class gs{textarea=null;_cachedFlutterScrollContainer=null;extractFormulaCopySource(e,t){return null}supportsFormulaCopy(){return true}getSessionId(){const e=window.location.href.split("?")[0].split("/").filter(e=>e);return e.length>0?e[e.length-1]:"default"}supportsNewTab(){return true}getNewTabUrl(){return window.location.origin}supportsTabRename(){return true}getSessionName(){return this.getDocumentConversationTitle()}getDocumentConversationTitle(e=this.getName()){return function(e,t={}){const n=Oa(e,t);if(!n)return null;const r=Pa(t.siteName);return r&&n===r?null:Pa(r?n.replace(new RegExp(`\\s*[-|]\\s*${Wa(r)}$`,"i"),"").replace(new RegExp(`^${Wa(r)}\\s*[-|]\\s*`,"i"),"").trim():n)}(document.title,{siteName:e})}isNewConversation(){return false}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){const e=this.getSessionId()?.trim();return Boolean(e)&&"default"!==e&&!this.isSharePage()&&!this.isNewConversation()} /** * 获取当前团队 ID(用于会话隔离) * 仅在支持多团队的站点(如 Gemini Enterprise)中实现 * @returns 团队 ID 或 null(无团队/默认团队) */getCurrentCid(){return null}getConversationList(){return []}getCurrentConversationInfo(){const e=this.getSessionId();return !e||"default"===e||this.isNewConversation()?null:{id:e,title:this.getConversationTitle()||this.getSessionName()||"",url:window.location.href,cid:this.getCurrentCid()||void 0}}getSidebarScrollContainer(){return null}getConversationObserverConfig(){return null} /** * 导航到指定会话(SPA 导航,不刷新页面) * 各站点适配器应覆盖此方法实现站点特定的导航逻辑 * @param id 会话 ID * @param url 会话 URL(用于降级硬刷新) * @returns 是否成功导航 */navigateToConversation(e,t){return !!t&&(window.location.href=t,true)}async deleteConversationOnSite(e){return {id:e.id,success:false,method:"none",reason:"not_supported"}}async deleteConversationsOnSite(e){const t=[];for(const n of e)t.push(await this.deleteConversationOnSite(n));return t}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!e)return false;let t=0,n=0;for(;n<3;){e.scrollTop=e.scrollHeight,await new Promise(e=>setTimeout(e,500));const r=(os.query(".conversation",{all:true,shadow:true})||[]).length;r===t?n++:(t=r,n=0);}return true}isGenerating(){return false}requiresDomConfirmationForNetworkGeneration(){return false}getModelName(){return null}getModelLockCheckText(e){return e?.textContent||e?.innerText||""}getNetworkMonitorConfig(){return null}supportsHostThemeSync(){return true} /** * 切换站点主题(子类可覆盖以实现站点特定的主题切换逻辑) * @param targetMode 目标主题模式 * @returns 是否成功切换 */async toggleTheme(e){return false}hasCustomToggleTheme(){return this.toggleTheme!==gs.prototype.toggleTheme}getNativeThemeCss(){return null}getWidthSelectors(){return []}getUserQueryWidthSelectors(){return []}getZenModeConfig(){return null}getCleanModeConfig(){return null}getMarkdownFixerConfig(){return null}getAssistantMermaidSupportMode(){return "native"}getAssistantMermaidBlocks(e){return hs(e)}getSubmitButtonSelectors(){return []}findSubmitButton(e){return null} /** * 获取发送消息的快捷键配置 * 子类可覆盖以适配不同平台的发送键设置 * @returns 发送键配置:key 为 "Enter" 或 "Ctrl+Enter" */getSubmitKeyConfig(){return {key:"Enter"}}findTextarea(){for(const e of this.getTextareaSelectors()){const t=document.querySelectorAll(e);for(const e of Array.from(t))if(this.isValidTextarea(e))return this.textarea=e,e}return null}isValidTextarea(e){return !e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&(!Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-"))&&null!==e.offsetParent)}clearTextarea(){this.textarea&&(this.textarea instanceof HTMLInputElement||this.textarea instanceof HTMLTextAreaElement?this.textarea.value="":this.textarea.textContent="",this.textarea.dispatchEvent(new Event("input",{bubbles:true})));}getTextareaElement(){return this.textarea&&this.textarea.isConnected?this.textarea:this.findTextarea()}getScrollContainer(){const e=["infinite-scroller.chat-history",".chat-mode-scroller","main",'[role="main"]',".conversation-container",".chat-container","div.content-container"];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return this._cachedFlutterScrollContainer=null,e}if(this._cachedFlutterScrollContainer&&this._cachedFlutterScrollContainer.isConnected)return this._cachedFlutterScrollContainer;if(this.getSiteId()===lo){const e=document.querySelectorAll('iframe[sandbox*="allow-same-origin"]');for(const n of Array.from(e))try{const e=n.contentDocument||n.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]:not([style*="overflow-x: scroll"])');if(t&&t.scrollHeight>t.clientHeight)return this._cachedFlutterScrollContainer=t,t}}catch(t){console.warn("[Ophel] Failed to access iframe:",t.message);}}return null}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=e.scrollTop,n=this.getChatContentSelectors();if(!n.length)return null;const r=Array.from(e.querySelectorAll(n.join(", ")));if(!r.length)return null;let o=null;for(let i=0;i0&&(o=r[0]),o){const e=t-o.offsetTop,n=o.getAttribute("data-message-id")||o.id;if(n){let t=`[data-message-id="${n}"]`;return o.matches(t)||(t=`#${n}`),{type:"selector",selector:t,offset:e}}{const t=r.indexOf(o);if(-1!==t){return {type:"index",index:t,offset:e,textSignature:(o.textContent||"").trim().substring(0,50)}}}}return null}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}if(n){const r=n.offsetTop+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}return false}getResponseContainerSelector(){return ""}getObserveTarget(){const e=this.getResponseContainerSelector();return e?document.querySelector(e):null}getChatContentSelectors(){return []}getUserQuerySelector(){return null}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()} /** * 使用 Range API 计算两个 DOM 节点之间的文本长度 * 通用于 Heading 类型的 OutlineItem 字数统计 * @param startEl 起始元素(不包含其内容,从其之后开始) * @param endEl 结束元素(不包含,在其之前结束);若为 null 则使用 fallbackContainer * @param fallbackContainer 当 endEl 为 null 时使用的容器末尾 * @returns 文本字符数 */calculateRangeWordCount(e,t,n){if(!e)return 0;try{const r=document.createRange();if(r.setStartAfter(e),t)r.setEndBefore(t);else {if(!n?.lastChild)return 0;r.setEndAfter(n.lastChild);}return r.toString().trim().length}catch{return 0}}extractUserQueryText(e){return this.extractTextWithLineBreaks(e)}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryText(e)} /** * @deprecated 使用 extractUserQueryExportContent */extractUserQueryExportText(e){return this.extractUserQueryExportContent(e)} /** * 将渲染后的 HTML 替换到用户提问元素中 * 子类可重写以处理特殊的 DOM 结构 * @returns 是否成功替换 */replaceUserQueryContent(e,t){return false}extractAssistantResponseText(e){return this.extractTextWithLineBreaks(e)}isInRenderedMarkdownContainer(e){return null!==e.closest(".gh-user-query-markdown")}usesShadowDOM(){return false}extractOutline(e=6,t=false,n=false){return []}getOutlineSources(){return [{id:"conversation",kind:"conversation",label:"对话",available:true}]}supportsDynamicOutlineSources(){return false}getOutlineSourcesSignature(){return this.getOutlineSources().map(e=>`${e.id}:${e.kind}:${e.available}:${e.count??""}`).join("|")}extractOutlineForSource(e,t=6,n=false,r=false){return "conversation"!==e?[]:this.extractOutline(t,n,r)}getInlineBookmarkItems(){return this.extractOutline(6,true,false).filter(e=>e.isUserQuery&&e.element?.isConnected)} /** * 根据标题级别和文本查找元素(支持 Shadow DOM 穿透) * 用于大纲跳转时元素失效后的重新查找 * @param level 标题级别 (1-6) * @param text 标题文本内容 * @returns 匹配的元素,未找到返回 null */findElementByHeading(e,t){const n=document.querySelectorAll(`h${e}`);for(const r of Array.from(n))if(r.textContent?.trim()===t)return r;return null} /** * 根据 queryIndex 和文本查找用户提问元素 * 用于大纲跳转时元素失效后的重新查找 * @param queryIndex 用户提问的序号(从 1 开始) * @param text 用户提问文本(用于验证和回退搜索) * @returns 匹配的元素,未找到返回 null */findUserQueryElement(e,t){const n=this.getUserQuerySelector();if(!n)return null;const r=os.query(n,{all:true,shadow:true});if(!r||0===r.length)return null;if(r.length>=e){const n=r[e-1],o=this.extractUserQueryText(n);if(o===t||o.startsWith(t)||t.startsWith(o))return n}for(const o of r){const e=this.extractUserQueryText(o);if(e===t||e.startsWith(t)||t.startsWith(e))return o}return null}async resolveOutlineTarget(e,t,n="conversation"){return e.isUserQuery&&0===e.level&&void 0!==t?this.findUserQueryElement(t,e.text):this.findElementByHeading(e.level,e.text)}scrollToOutlineTarget(e){e.scrollIntoView({behavior:"instant",block:"start",__bypassLock:true});}getOutlineScrollContainer(e="conversation"){return this.getScrollContainer()}scrollToOutlineSourceTarget(e,t="conversation"){this.scrollToOutlineTarget(e);}supportsScrollLock(){return false}getExportConfig(){return null}async extractExportMessages(e){return null}async extractExportBundle(e){return null}async createExportBundleFromMessages(e){const t=ia(),n=await e(t);return 0===n.length?null:{messages:n,assets:t.assets}}async prepareConversationExport(e){return null}async restoreConversationAfterExport(e,t){}getLatestReplyText(){return null}getLastCodeBlockText(){const e=this.getLatestReplyText(),t=this.extractLastFencedCodeBlockText(e||"");if(t)return t;const n=this.getAssistantResponseElementsForCodeSearch();for(let r=n.length-1;r>=0;r-=1){const e=n[r],t=this.extractLastCodeBlockTextFromDomRoot(e);if(t)return t;const o=this.extractAssistantResponseText(e).trim(),i=this.extractLastFencedCodeBlockText(o);if(i)return i}return 0===n.length?this.extractLastCodeBlockTextFromDomRoot(this.getPrimaryCodeSearchRoot()):null}getNewChatButtonSelectors(){return []}startNewConversation(){const e=this.captureConversationNavigationState(),t=this.findVisibleElementBySelectors(this.getNewChatButtonSelectors());return t?(this.simulateClick(t),window.setTimeout(()=>{this.hasConversationNavigationChanged(e)||this.navigateToNewConversationUrl();},150),true):this.navigateToNewConversationUrl()}getStopButtonSelectors(){return []}stopGeneration(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());return !!e&&(this.simulateClick(e),true)}bindNewChatListeners(e){document.addEventListener("keydown",t=>{t.ctrlKey&&t.shiftKey&&("o"===t.key||"O"===t.key)&&setTimeout(e,500);}),document.addEventListener("click",t=>{const n=this.getNewChatButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)if(o.matches&&o.matches(t))return void setTimeout(e,500)}},true);}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return null}simulateClick(e){e.click();} /** * 点击模型选择器按钮(公开方法,供外部调用) * 使用 simulateClick 确保在 Radix UI 等框架中也能正常工作 * 使用 findElementBySelectors 支持 Shadow DOM 穿透(与 lockModel 一致) * @returns 是否成功点击 */clickModelSelector(){const e=this.getModelSwitcherConfig("");if(!e||!e.selectorButtonSelectors)return false;const t=this.findElementBySelectors(e.selectorButtonSelectors);return !(!t||null===t.offsetParent)&&(this.simulateClick(t),true)}lockModel(e,t){const n=this.getModelSwitcherConfig(e);if(!n)return;const{targetModelKeyword:r,selectorButtonSelectors:o,menuItemSelector:i,checkInterval:a=1e3,maxAttempts:s=10,menuRenderDelay:l=500,subMenuTriggers:c=[],subMenuSelector:d}=n,u=e=>(e||"").toLowerCase().trim(),h=u(r);let g=0;const p=s,m=setInterval(()=>{g++;const e=this.findElementBySelectors(o);if(e){clearInterval(m);if(u(this.getModelLockCheckText(e)).includes(h))return void(t&&t());this.performMenuSearch(e,h,i,l,c,d,t,s);}else g>=p&&(clearInterval(m),console.warn(`Ophel: Model selector button not found after ${p} attempts.`),this.showModelLockFailure(r,"button_not_found"));},a);}performMenuSearch(e,t,n,r,o,i,a,s=10){this.simulateClick(e);const l=Math.max(3,s);let c=0;const d=()=>{c++;const s=this.getVisibleMenuItems(n,e);if(!(s.length>0))return c>=l?(document.body.click(),console.warn("Ophel: Menu items not found."),void this.showModelLockFailure(t,"menu_empty")):void setTimeout(d,r);this.searchAndSelectModel(s,t,n,r,o,i,a);};setTimeout(d,r);}searchAndSelectModel(e,t,n,r,o,i,a){const s=e=>(e||"").toLowerCase().trim(),l=this.findBestMatchingItem(e,t);if(l)return this.simulateClick(l),void setTimeout(()=>{document.body.click(),a&&a();},100);let c;if(i&&(c=e.find(e=>e.matches(i))),!c&&o.length>0&&(c=e.find(e=>{const t=s(e.textContent||"");return o.some(e=>t.includes(s(e)))})),c)return this.simulateClick(c),void setTimeout(()=>{const e=this.getVisibleMenuItems(n,c),r=this.findBestMatchingItem(e,t);if(r)return this.simulateClick(r),void setTimeout(()=>{document.body.click(),a&&a();},100);document.body.click(),console.warn(`Ophel: Model "${t}" not found in sub-menu.`),this.showModelLockFailure(t,"not_found");},r);document.body.click(),console.warn(`Ophel: Model "${t}" not found in menu.`),this.showModelLockFailure(t,"not_found");}getVisibleMenuItems(e,t){const n=this.getVisibleElementsBySelector(e);if(!t||0===n.length)return n;const r=this.getMenuContainerByAria(t);if(r){const e=n.filter(e=>r.contains(e));if(e.length>0)return e}const o=this.getMenuContainerSelector(),i=new Map;for(const a of n){const e=a.closest(o);if(!e||!this.isElementVisible(e))continue;const t=i.get(e);t?t.push(a):i.set(e,[a]);}if(i.size>0){const e=this.pickBestMenuContainer(t,i);if(e)return i.get(e)||n}return n}getVisibleElementsBySelector(e){return os.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)})||[]}getMenuContainerByAria(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=`#${this.escapeSelector(t)}`,r=os.query(n,{shadow:true});return r&&this.isElementVisible(r)?r:null}getMenuContainerSelector(){return ['[role="menu"]','[role="listbox"]',"md-menu-surface",".mdc-menu-surface",".mat-menu-panel",".menu[popover]","[data-radix-popper-content-wrapper]",".cdk-overlay-pane"].join(", ")}pickBestMenuContainer(e,t){const n=e.getBoundingClientRect();let r=null;return t.forEach((e,t)=>{if(0===e.length)return;const o=t.getBoundingClientRect(),i=this.getRectDistance(n,o);(!r||ir.count)&&(r={container:t,distance:i,count:e.length});}),r?r.container:null}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}isElementVisible(e){if(!e)return false;const t=e;if(!t.isConnected)return false;const n=window.getComputedStyle(t);if("none"===n.display||"hidden"===n.visibility||0===parseFloat(n.opacity))return false;const r=t.getBoundingClientRect();return r.width>0&&r.height>0}escapeSelector(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,"\\$&")}findBestMatchingItem(e,t){const n=e=>(e||"").toLowerCase().trim();for(const r of e){const e=n(r.textContent||r.innerText||"");if(e.split("\n")[0].trim()===t||e===t)return r}for(const r of e){if(n(r.textContent||r.innerText||"").split("\n")[0].trim().endsWith(t))return r}for(const r of e){if(n(r.textContent||r.innerText||"").includes(t))return r}}async showModelLockFailure(e,t){try{const{showToast:n}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Di);return {showToast:e}},void 0),{t:o}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>de);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=o("modelLockFailedNoButton");break;case "menu_empty":i=o("modelLockFailedMenuEmpty");break;default:i=o("modelLockFailedNotFound").replace("{model}",e);}n(i,3e3);}catch(n){console.error("Ophel: Failed to show toast:",n);}}findElementBySelectors(e){return os.query(e,{shadow:true})}findAllElementsBySelector(e){return os.query(e,{all:true,shadow:true})||[]}afterPropertiesSet(e={}){const{modelLockConfig:t}=e;t&&t.enabled&&this.lockModel(t.keyword);}shouldInjectIntoShadow(e){return true}findVisibleElementBySelectors(e){if(0===e.length)return null;const t=os.query(e,{all:true,shadow:true,filter:e=>this.isElementVisible(e)});for(const n of t||[]){if(!(n instanceof HTMLElement))continue;const e=this.resolveClickableTarget(n);if(e&&this.isElementVisible(e))return e}return null}extractLastFencedCodeBlockText(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDomRoot(e){const t=os.query("pre code, pre, pre.code-block, .code-block code",{parent:e,all:true,shadow:true,filter:e=>this.shouldIncludeCodeElement(e)})||[];for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"], .gh-copy-btn, [data-testid*="copy"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}getAssistantResponseElementsForCodeSearch(){const e=this.getExportConfig();return e?.assistantResponseSelector&&os.query(e.assistantResponseSelector,{parent:this.getPrimaryCodeSearchRoot(),all:true,shadow:true,filter:e=>this.shouldIncludeAssistantResponseElement(e)})||[]}getPrimaryCodeSearchRoot(){const e=this.getResponseContainerSelector();if(e){const t=os.query(e,{shadow:true});if(t)return t}return this.getScrollContainer()||document}resolveClickableTarget(e){return e?e.matches("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")?e:e.closest("button, a, [role='button'], [tabindex], md-icon-button, ms-stop-button")||e:null}shouldIncludeAssistantResponseElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}shouldIncludeCodeElement(e){return !e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview, .gh-assistant-mermaid")&&this.isElementVisible(e)}isAssistantMermaidCandidate(e){return ss(e)}extractAssistantMermaidSource(e){return ds(e)}navigateToNewConversationUrl(){const e=this.getNewTabUrl();if(!e)return false;try{const t=new URL(e,window.location.origin).href;return t===window.location.href&&this.isNewConversation()||(window.location.href=t),!0}catch{return window.location.href=e,true}}captureConversationNavigationState(){return {href:window.location.href,sessionId:this.getSessionId(),isNewConversation:this.isNewConversation()}}hasConversationNavigationChanged(e){return window.location.href!==e.href||this.getSessionId()!==e.sessionId||this.isNewConversation()!==e.isNewConversation}}const ps="delete_ui_failed",ms="delete_batch_aborted_after_ui_failure",fs="delete_api_disabled_unstable",bs="delete_api_auth_missing",ys="delete_api_key_missing",vs="delete_api_request_failed",ws="delete_api_not_found_but_visible",xs=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","löschen","excluir","hapus","удалить"],ks=["cancel","取消","キャンセル","취소","annuler","abbrechen","annulla","batal","cancelar","отмена"],Ss="/$rpc/google.internal.alkali.applications.makersuite.v1.MakerSuiteService",Cs="ms-chat-turn",As=".chat-turn-container.model, .model-prompt-container",Es=".chat-turn-container.model",Ts="ms-thought-chunk",Ms="data-gh-aistudio-export-root",_s="data-gh-aistudio-export-turn",Is="data-gh-aistudio-export-role",Ls="user",Ns="assistant",Ds=`[${Ms}="1"] [${_s}="1"]`,qs=`[${Ms}="1"] [${Is}="${Ls}"]`,Rs=`[${Ms}="1"] [${Is}="${Ns}"]`;const Ps=new Set(["chatglm.cn"]),zs="share_conversation_id",Bs="SKIN_MODE",Os={light:"1",dark:"2",system:"3"},Fs=[".userInfoBar-header .me-icon",".userInfoBar-header .me",".userInfoBar-header img.avatar"],$s=".selecttheme-list",Us=".conversation-list",js=".conversation.question",Hs=".question-txt",Ws=".answer-content-wrap",Gs=".answer-content-wrap .markdown-body",Qs=[".advance-thinking",".advance-thinking-area",".advanced-thinking",".advanced-thinking-data",".text-advance-thinking-content",".thinking-chain-container",".thinking-block",".thinking-content",".thinking-item","[class*='thinking']","[class*='think']","[class*='reason']","[class*='cot']"].join(", "),Vs=[".gh-root",".gh-user-query-markdown",".assistant-name",".interact-container",".code-no-artifacts .top-outer",".code-no-artifacts .copy-button","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Ks=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Zs=["#search-input-box textarea",".main-chat-search #search-input-box textarea",".main-chat-search textarea"],Ys=".enter-icon-container";const Js="ChatGPT",Xs=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удалить","excluir"],el="delete_ui_failed",tl="delete_batch_aborted_after_ui_failure",nl="delete_api_token_missing",rl="delete_api_request_failed",ol="delete_api_not_found_but_visible",il=new Set(["yaml","yml","json","js","javascript","ts","typescript","py","python","bash","sh","shell","html","css","sql","cpp","c++","c","cs","csharp","java","go","rust","php","rb","ruby","pl","perl","swift","kotlin","scala","xml","md","markdown","diff","dockerfile","ini","toml","powershell","ps1","r","dart","groovy","haskell","lua","objectivec","objc","ocaml","tex","latex","vhdl","verilog","wasm"]),al=['button[class*="__composer-pill"][aria-haspopup="menu"]'],sl='[data-radix-popper-content-wrapper] [role="menu"][data-radix-menu-content]',ll=`${sl} [data-testid^="model-switcher-"]`,cl="data-gh-chatgpt-export-root",dl="data-gh-chatgpt-export-turn",ul="data-gh-chatgpt-export-role",hl="user",gl="assistant",pl=`[${cl}="1"] [${dl}="1"]`,ml=`[${cl}="1"] [${ul}="${hl}"]`,fl=`[${cl}="1"] [${ul}="${gl}"]`,bl=/^chatgpt-native-user-query::(\d+)::/;function yl(e,t=6,n){return Array.from(e.querySelectorAll(function(e=6){const t=Math.min(Math.max(e,1),6);return Array.from({length:t},(e,t)=>`h${t+1}`).join(", ")}(t))).filter(e=>!n?.(e))}function vl(e,t={}){const{maxLevel:n=6,showWordCount:r=false,idPrefix:o,maxTextLength:i,shouldSkipHeading:a,calculateWordCount:s}=t,l=yl(e,n,a);return l.map((t,n)=>{const a=parseInt(t.tagName.charAt(1),10),c=t.textContent?.trim()||"",d={level:a,text:i&&c.length>i?c.slice(0,i):c,element:t,isTruncated:i?c.length>i:void 0};if(o&&(d.id=`${o}:${a}:${c}:${n}`),r&&s){let r=null;for(let e=n+1;e!r?.(e)).find(e=>e.textContent?.trim()===n)||null}function xl(e){let t=e?.parentElement||null;for(;t&&t!==document.body;){const e=window.getComputedStyle(t).overflowY;if(t.scrollHeight>t.clientHeight&&("auto"===e||"scroll"===e||"overlay"===e))return t;t=t.parentElement;}return null}function kl(e,t,n=12){if(!t||t===e)return false;const r=t.getBoundingClientRect(),o=e.getBoundingClientRect();return t.scrollTo({top:t.scrollTop+o.top-r.top-n,behavior:"instant"}),true}function Sl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Cl(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=false;try{n=this instanceof e;}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype;}else n={};return Object.defineProperty(n,"__esModule",{value:true}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:true,get:function(){return e[t]}});}),n}var Al,El;function Tl(){if(El)return Al;function e(t){return t instanceof Map?t.clear=t.delete=t.set=function(){throw new Error("map is read-only")}:t instanceof Set&&(t.add=t.clear=t.delete=function(){throw new Error("set is read-only")}),Object.freeze(t),Object.getOwnPropertyNames(t).forEach(n=>{const r=t[n],o=typeof r;"object"!==o&&"function"!==o||Object.isFrozen(r)||e(r);}),t}El=1;class t{ /** * @param {CompiledMode} mode */ constructor(e){ void 0===e.data&&(e.data={}),this.data=e.data,this.isMatchIgnored=false;}ignoreMatch(){this.isMatchIgnored=true;}}function n(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function r(e,...t){const n=Object.create(null);for(const r in e)n[r]=e[r];return t.forEach(function(e){for(const t in e)n[t]=e[t];}), /** @type {T} */n}const o=e=>!!e.scope;class i{ /** * Creates a new HTMLRenderer * * @param {Tree} parseTree - the parse tree (must support `walk` API) * @param {{classPrefix: string}} options */ constructor(e,t){this.buffer="",this.classPrefix=t.classPrefix,e.walk(this);} /** * Adds texts to the output stream * * @param {string} text */addText(e){this.buffer+=n(e);} /** * Adds a node open to the output stream (if needed) * * @param {Node} node */openNode(e){if(!o(e))return;const t=((e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){const n=e.split(".");return [`${t}${n.shift()}`,...n.map((e,t)=>`${e}${"_".repeat(t+1)}`)].join(" ")}return `${t}${e}`})(e.scope,{prefix:this.classPrefix});this.span(t);} /** * Adds a node close to the output stream (if needed) * * @param {Node} node */closeNode(e){o(e)&&(this.buffer+="");}value(){return this.buffer} /** * Builds a span element * * @param {string} className */ span(e){this.buffer+=``;}}const a=(e={})=>{const t={children:[]};return Object.assign(t,e),t};class s{constructor(){this.rootNode=a(),this.stack=[this.rootNode];}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode} /** @param {Node} node */add(e){this.top.children.push(e);} /** @param {string} scope */openNode(e){const t=a({scope:e});this.add(t),this.stack.push(t);}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)} /** * @typedef { import("./html_renderer").Renderer } Renderer * @param {Renderer} builder */walk(e){return this.constructor._walk(e,this.rootNode)} /** * @param {Renderer} builder * @param {Node} node */static _walk(e,t){return "string"==typeof t?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e} /** * @param {Node} node */static _collapse(e){"string"!=typeof e&&e.children&&(e.children.every(e=>"string"==typeof e)?e.children=[e.children.join("")]:e.children.forEach(e=>{s._collapse(e);}));}}class l extends s{ /** * @param {*} options */ constructor(e){super(),this.options=e;} /** * @param {string} text */addText(e){""!==e&&this.add(e);} /** @param {string} scope */startScope(e){this.openNode(e);}endScope(){this.closeNode();} /** * @param {Emitter & {root: DataNode}} emitter * @param {string} name */__addSublanguage(e,t){const n=e.root;t&&(n.scope=`language:${t}`),this.add(n);}toHTML(){return new i(this,this.options).value()}finalize(){return this.closeAllNodes(),true}}function c(e){return e?"string"==typeof e?e:e.source:null}function d(e){return g("(?=",e,")")}function u(e){return g("(?:",e,")*")}function h(e){return g("(?:",e,")?")}function g(...e){return e.map(e=>c(e)).join("")}function p(...e){const t=function(e){const t=e[e.length-1];return "object"==typeof t&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}(e);return "("+(t.capture?"":"?:")+e.map(e=>c(e)).join("|")+")"}function m(e){return new RegExp(e.toString()+"|").exec("").length-1}const f=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function b(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;const t=n;let r=c(e),o="";for(;r.length>0;){const e=f.exec(r);if(!e){o+=r;break}o+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),"\\"===e[0][0]&&e[1]?o+="\\"+String(Number(e[1])+t):(o+=e[0],"("===e[0]&&n++);}return o}).map(e=>`(${e})`).join(t)}const y="[a-zA-Z]\\w*",v="[a-zA-Z_]\\w*",w="\\b\\d+(\\.\\d+)?",x="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",k="\\b(0b[01]+)",S={begin:"\\\\[\\s\\S]",relevance:0},C={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[S]},A={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[S]},E=function(e,t,n={}){const o=r({scope:"comment",begin:e,end:t,contains:[]},n);o.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:true,relevance:0});const i=p("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return o.contains.push({begin:g(/[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */ "(",i,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),o},T=E("//","$"),M=E("/\\*","\\*/"),_=E("#","$"),I={scope:"number",begin:w,relevance:0},L={scope:"number",begin:x,relevance:0},N={scope:"number",begin:k,relevance:0},D={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[S,{begin:/\[/,end:/\]/,relevance:0,contains:[S]}]},q={scope:"title",begin:y,relevance:0},R={scope:"title",begin:v,relevance:0},P={begin:"\\.\\s*"+v,relevance:0};var z=Object.freeze({__proto__:null,APOS_STRING_MODE:C,BACKSLASH_ESCAPE:S,BINARY_NUMBER_MODE:N,BINARY_NUMBER_RE:k,COMMENT:E,C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:T,C_NUMBER_MODE:L,C_NUMBER_RE:x,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{ /** @type {ModeCallback} */ "on:begin":(e,t)=>{t.data._beginMatch=e[1];}, /** @type {ModeCallback} */ "on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch();}})},HASH_COMMENT_MODE:_,IDENT_RE:y,MATCH_NOTHING_RE:/\b\B/,METHOD_GUARD:P,NUMBER_MODE:I,NUMBER_RE:w,PHRASAL_WORDS_MODE:{begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},QUOTE_STRING_MODE:A,REGEXP_MODE:D,RE_STARTERS_RE:"!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",SHEBANG:(e={})=>{const t=/^#![ ]*\//;return e.binary&&(e.begin=g(t,/.*\b/,e.binary,/\b.*/)),r({scope:"meta",begin:t,end:/$/,relevance:0, /** @type {ModeCallback} */ "on:begin":(e,t)=>{0!==e.index&&t.ignoreMatch();}},e)},TITLE_MODE:q,UNDERSCORE_IDENT_RE:v,UNDERSCORE_TITLE_MODE:R});function B(e,t){"."===e.input[e.index-1]&&t.ignoreMatch();}function O(e,t){ void 0!==e.className&&(e.scope=e.className,delete e.className);}function F(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=B,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,void 0===e.relevance&&(e.relevance=0));}function $(e,t){Array.isArray(e.illegal)&&(e.illegal=p(...e.illegal));}function U(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match;}}function j(e,t){ void 0===e.relevance&&(e.relevance=1);}const H=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");const n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t];}),e.keywords=n.keywords,e.begin=g(n.beforeMatch,d(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:true})]},e.relevance=0,delete n.beforeMatch;},W=["of","and","for","in","not","or","if","then","parent","list","value"];function G(e,t,n="keyword"){const r=Object.create(null);return "string"==typeof e?o(n,e.split(" ")):Array.isArray(e)?o(n,e):Object.keys(e).forEach(function(n){Object.assign(r,G(e[n],t,n));}),r;function o(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){const n=t.split("|");r[n[0]]=[e,Q(n[0],n[1])];});}}function Q(e,t){return t?Number(t):function(e){return W.includes(e.toLowerCase())}(e)?0:1}const V={},K=e=>{console.error(e);},Z=(e,...t)=>{console.log(`WARN: ${e}`,...t);},Y=(e,t)=>{V[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),V[`${e}/${t}`]=true);},J=new Error;function X(e,t,{key:n}){let r=0;const o=e[n],i={},a={};for(let s=1;s<=t.length;s++)a[s+r]=o[s],i[s+r]=true,r+=m(t[s-1]);e[n]=a,e[n]._emit=i,e[n]._multi=true;}function ee(e){!function(e){e.scope&&"object"==typeof e.scope&&null!==e.scope&&(e.beginScope=e.scope,delete e.scope);}(e),"string"==typeof e.beginScope&&(e.beginScope={_wrap:e.beginScope}),"string"==typeof e.endScope&&(e.endScope={_wrap:e.endScope}),function(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw K("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),J;if("object"!=typeof e.beginScope||null===e.beginScope)throw K("beginScope must be object"),J;X(e,e.begin,{key:"beginScope"}),e.begin=b(e.begin,{joinWith:""});}}(e),function(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw K("skip, excludeEnd, returnEnd not compatible with endScope: {}"),J;if("object"!=typeof e.endScope||null===e.endScope)throw K("endScope must be object"),J;X(e,e.end,{key:"endScope"}),e.end=b(e.end,{joinWith:""});}}(e);}function te(e){function t(t,n){return new RegExp(c(t),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(n?"g":""))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0;} // @ts-ignore addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=m(e)+1;}compile(){0===this.regexes.length&&(this.exec=()=>null);const e=this.regexes.map(e=>e[1]);this.matcherRe=t(b(e,{joinWith:"|"}),true),this.lastIndex=0;} /** @param {string} s */exec(e){this.matcherRe.lastIndex=this.lastIndex;const t=this.matcherRe.exec(e);if(!t)return null;const n=t.findIndex((e,t)=>t>0&&void 0!==e),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class o{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0;} // @ts-ignore getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];const t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return 0!==this.regexIndex}considerAll(){this.regexIndex=0;} // @ts-ignore addRule(e,t){this.rules.push([e,t]),"begin"===t.type&&this.count++;} /** @param {string} s */exec(e){const t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition())if(n&&n.index===this.lastIndex);else {const t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e);}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=r(e.classNameAliases||{}),function n(i,a){const s= /** @type CompiledMode */i;if(i.isCompiled)return s;[O,U,ee,H].forEach(e=>e(i,a)),e.compilerExtensions.forEach(e=>e(i,a)),i.__beforeBegin=null,[F,$,j].forEach(e=>e(i,a)),i.isCompiled=true;let l=null;return "object"==typeof i.keywords&&i.keywords.$pattern&&(i.keywords=Object.assign({},i.keywords),l=i.keywords.$pattern,delete i.keywords.$pattern),l=l||/\w+/,i.keywords&&(i.keywords=G(i.keywords,e.case_insensitive)),s.keywordPatternRe=t(l,true),a&&(i.begin||(i.begin=/\B|\b/),s.beginRe=t(s.begin),i.end||i.endsWithParent||(i.end=/\B|\b/),i.end&&(s.endRe=t(s.end)),s.terminatorEnd=c(s.end)||"",i.endsWithParent&&a.terminatorEnd&&(s.terminatorEnd+=(i.end?"|":"")+a.terminatorEnd)),i.illegal&&(s.illegalRe=t( /** @type {RegExp | string} */ i.illegal)),i.contains||(i.contains=[]),i.contains=[].concat(...i.contains.map(function(e){return function(e){e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return r(e,{variants:null},t)}));if(e.cachedVariants)return e.cachedVariants;if(ne(e))return r(e,{starts:e.starts?r(e.starts):null});if(Object.isFrozen(e))return r(e);return e}("self"===e?i:e)})),i.contains.forEach(function(e){n( /** @type Mode */ e,s);}),i.starts&&n(i.starts,a),s.matcher=function(e){const t=new o;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:"begin"})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:"end"}),e.illegal&&t.addRule(e.illegal,{type:"illegal"}),t}(s),s}( /** @type Mode */ e)}function ne(e){return !!e&&(e.endsWithParent||ne(e.starts))}class re extends Error{constructor(e,t){super(e),this.name="HTMLInjectionError",this.html=t;}}const oe=n,ie=r,ae=Symbol("nomatch"),se=function(n){const r=Object.create(null),o=Object.create(null),i=[];let a=true;const s="Could not find the language '{}', did you forget to load/include a language module?",c={disableAutodetect:true,name:"Plain text",contains:[]};let m={ignoreUnescapedHTML:false,throwUnescapedHTML:false,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:l};function f(e){return m.noHighlightRe.test(e)}function b(e,t,n){let r="",o="";"object"==typeof t?(r=e,n=t.ignoreIllegals,o=t.language):(Y("10.7.0","highlight(lang, code, ...args) has been deprecated."),Y("10.7.0","Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"),o=e,r=t),void 0===n&&(n=true);const i={code:r,language:o};E("before:highlight",i);const a=i.result?i.result:y(i.language,i.code,n);return a.code=i.code,E("after:highlight",a),a}function y(e,n,o,i){const l=Object.create(null);function c(e,t){return e.keywords[t]}function d(){if(!T.keywords)return void _.addText(I);let e=0;T.keywordPatternRe.lastIndex=0;let t=T.keywordPatternRe.exec(I),n="";for(;t;){n+=I.substring(e,t.index);const r=C.case_insensitive?t[0].toLowerCase():t[0],o=c(T,r);if(o){const[e,i]=o;if(_.addText(n),n="",l[r]=(l[r]||0)+1,l[r]<=7&&(L+=i),e.startsWith("_"))n+=t[0];else {const n=C.classNameAliases[e]||e;h(t[0],n);}}else n+=t[0];e=T.keywordPatternRe.lastIndex,t=T.keywordPatternRe.exec(I);}n+=I.substring(e),_.addText(n);}function u(){null!=T.subLanguage?function(){if(""===I)return;let e=null;if("string"==typeof T.subLanguage){if(!r[T.subLanguage])return void _.addText(I);e=y(T.subLanguage,I,true,M[T.subLanguage]),M[T.subLanguage]=/** @type {CompiledMode} */ e._top;}else e=v(I,T.subLanguage.length?T.subLanguage:null);T.relevance>0&&(L+=e.relevance),_.__addSublanguage(e._emitter,e.language);}():d(),I="";}function h(e,t){""!==e&&(_.startScope(t),_.addText(e),_.endScope());}function g(e,t){let n=1;const r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}const r=C.classNameAliases[e[n]]||e[n],o=t[n];r?h(o,r):(I=o,d(),I=""),n++;}}function p(e,t){return e.scope&&"string"==typeof e.scope&&_.openNode(C.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(h(I,C.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),I=""):e.beginScope._multi&&(g(e.beginScope,t),I="")),T=Object.create(e,{parent:{value:T}}),T}function f(e,n,r){let o=function(e,t){const n=e&&e.exec(t);return n&&0===n.index}(e.endRe,r);if(o){if(e["on:end"]){const r=new t(e);e["on:end"](n,r),r.isMatchIgnored&&(o=false);}if(o){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return f(e.parent,n,r)}function b(e){return 0===T.matcher.regexIndex?(I+=e[0],1):(q=true,0)}function w(e){const t=e[0],r=n.substring(e.index),o=f(T,e,r);if(!o)return ae;const i=T;T.endScope&&T.endScope._wrap?(u(),h(t,T.endScope._wrap)):T.endScope&&T.endScope._multi?(u(),g(T.endScope,e)):i.skip?I+=t:(i.returnEnd||i.excludeEnd||(I+=t),u(),i.excludeEnd&&(I=t));do{T.scope&&_.closeNode(),T.skip||T.subLanguage||(L+=T.relevance),T=T.parent;}while(T!==o.parent);return o.starts&&p(o.starts,e),i.returnEnd?0:t.length}let x={};function k(r,i){const s=i&&i[0];if(I+=r,null==s)return u(),0;if("begin"===x.type&&"end"===i.type&&x.index===i.index&&""===s){if(I+=n.slice(i.index,i.index+1),!a){const t=new Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=x.rule,t}return 1}if(x=i,"begin"===i.type)return function(e){const n=e[0],r=e.rule,o=new t(r),i=[r.__beforeBegin,r["on:begin"]];for(const t of i)if(t&&(t(e,o),o.isMatchIgnored))return b(n);return r.skip?I+=n:(r.excludeBegin&&(I+=n),u(),r.returnBegin||r.excludeBegin||(I=n)),p(r,e),r.returnBegin?0:n.length}(i);if("illegal"===i.type&&!o){const e=new Error('Illegal lexeme "'+s+'" for mode "'+(T.scope||"")+'"');throw e.mode=T,e}if("end"===i.type){const e=w(i);if(e!==ae)return e}if("illegal"===i.type&&""===s)return I+="\n",1;if(D>1e5&&D>3*i.index){throw new Error("potential infinite loop, way more iterations than matches")}return I+=s,s.length}const C=S(e);if(!C)throw K(s.replace("{}",e)),new Error('Unknown language: "'+e+'"');const A=te(C);let E="",T=i||A;const M={},_=new m.__emitter(m);!function(){const e=[];for(let t=T;t!==C;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>_.openNode(e));}();let I="",L=0,N=0,D=0,q=false;try{if(C.__emitTokens)C.__emitTokens(n,_);else {for(T.matcher.considerAll();;){D++,q?q=!1:T.matcher.considerAll(),T.matcher.lastIndex=N;const e=T.matcher.exec(n);if(!e)break;const t=k(n.substring(N,e.index),e);N=e.index+t;}k(n.substring(N));}return _.finalize(),E=_.toHTML(),{language:e,value:E,relevance:L,illegal:!1,_emitter:_,_top:T}}catch(R){if(R.message&&R.message.includes("Illegal"))return {language:e,value:oe(n),illegal:true,relevance:0,_illegalBy:{message:R.message,index:N,context:n.slice(N-100,N+100),mode:R.mode,resultSoFar:E},_emitter:_};if(a)return {language:e,value:oe(n),illegal:false,relevance:0,errorRaised:R,_emitter:_,_top:T};throw R}}function v(e,t){t=t||m.languages||Object.keys(r);const n=function(e){const t={value:oe(e),illegal:false,relevance:0,_top:c,_emitter:new m.__emitter(m)};return t._emitter.addText(e),t}(e),o=t.filter(S).filter(A).map(t=>y(t,e,false));o.unshift(n);const i=o.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(S(e.language).supersetOf===t.language)return 1;if(S(t.language).supersetOf===e.language)return -1}return 0}),[a,s]=i,l=a;return l.secondBest=s,l}function w(e){let t=null;const n=function(e){let t=e.className+" ";t+=e.parentNode?e.parentNode.className:"";const n=m.languageDetectRe.exec(t);if(n){const t=S(n[1]);return t||(Z(s.replace("{}",n[1])),Z("Falling back to no-highlight mode for this block.",e)),t?n[1]:"no-highlight"}return t.split(/\s+/).find(e=>f(e)||S(e))}(e);if(f(n))return;if(E("before:highlightElement",{el:e,language:n}),e.dataset.highlighted)return void console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);if(e.children.length>0&&(m.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(e)),m.throwUnescapedHTML)){throw new re("One of your code blocks includes unescaped HTML.",e.innerHTML)}t=e;const r=t.textContent,i=n?b(r,{language:n,ignoreIllegals:true}):v(r);e.innerHTML=i.value,e.dataset.highlighted="yes",function(e,t,n){const r=t&&o[t]||n;e.classList.add("hljs"),e.classList.add(`language-${r}`);}(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),E("after:highlightElement",{el:e,result:i,text:r});}let x=false;function k(){if("loading"===document.readyState)return x||window.addEventListener("DOMContentLoaded",function(){k();},false),void(x=true);document.querySelectorAll(m.cssSelector).forEach(w);}function S(e){return e=(e||"").toLowerCase(),r[e]||r[o[e]]}function C(e,{languageName:t}){"string"==typeof e&&(e=[e]),e.forEach(e=>{o[e.toLowerCase()]=t;});}function A(e){const t=S(e);return t&&!t.disableAutodetect}function E(e,t){const n=e;i.forEach(function(e){e[n]&&e[n](t);});}Object.assign(n,{highlight:b,highlightAuto:v,highlightAll:k,highlightElement:w,highlightBlock:function(e){return Y("10.7.0","highlightBlock will be removed entirely in v12.0"),Y("10.7.0","Please use highlightElement now."),w(e)},configure:function(e){m=ie(m,e);},initHighlighting:()=>{k(),Y("10.6.0","initHighlighting() deprecated. Use highlightAll() now.");},initHighlightingOnLoad:function(){k(),Y("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.");},registerLanguage:function(e,t){let o=null;try{o=t(n);}catch(i){if(K("Language definition for '{}' could not be registered.".replace("{}",e)),!a)throw i;K(i),o=c;}o.name||(o.name=e),r[e]=o,o.rawDefinition=t.bind(null,n),o.aliases&&C(o.aliases,{languageName:e});},unregisterLanguage:function(e){delete r[e];for(const t of Object.keys(o))o[t]===e&&delete o[t];},listLanguages:function(){return Object.keys(r)},getLanguage:S,registerAliases:C,autoDetection:A,inherit:ie,addPlugin:function(e){!function(e){e["before:highlightBlock"]&&!e["before:highlightElement"]&&(e["before:highlightElement"]=t=>{e["before:highlightBlock"](Object.assign({block:t.el},t));}),e["after:highlightBlock"]&&!e["after:highlightElement"]&&(e["after:highlightElement"]=t=>{e["after:highlightBlock"](Object.assign({block:t.el},t));});}(e),i.push(e);},removePlugin:function(e){const t=i.indexOf(e);-1!==t&&i.splice(t,1);}}),n.debugMode=function(){a=false;},n.safeMode=function(){a=true;},n.versionString="11.11.1",n.regex={concat:g,lookahead:d,either:p,optional:h,anyNumberOfTimes:u};for(const t in z)"object"==typeof z[t]&&e(z[t]);return Object.assign(n,z),n},le=se({});return le.newInstance=()=>se({}),Al=le,le.HighlightJS=le,le.default=le,Al}const Ml=Sl(Tl());function _l(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/, // Perl at all like $ident$, @ident@, etc. "(?![\\w\\d])(?![$])")},r]});const o={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},i=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),a={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},s={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,o]};o.contains.push(s);const l={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},c=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),d={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:true,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return {name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],literal:["true","false"],built_in:["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset","alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias","set","shopt","autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp","chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"]},contains:[c,e.SHEBANG(),d,l,i,a,{match:/(\/[a-z._-]+)+/},s,{match:/\\"/},{className:"string",begin:/'/,end:/'/},{match:/\\'/},n]}}const Il=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video","defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Ll=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),Nl=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Dl=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),ql=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src", // @font-face "stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function Rl(e){const t=e.regex,n=(e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}))(e),r=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return {name:"CSS",case_insensitive:true,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,{begin:/-(webkit|moz|ms|o)-(?=[a-z])/},n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\.[a-zA-Z-][a-zA-Z0-9_-]*",relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+Nl.join("|")+")"},{begin:":(:)?("+Dl.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+ql.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,...r,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...r,{className:"string",begin:/[^)]/,endsWithParent:true,excludeEnd:true}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/, // break on Less variables @var: ... contains:[{className:"keyword",begin:/@-?\w[\w]*(-\w+)*/},{begin:/\s/,endsWithParent:true,excludeEnd:true,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:"and or not only",attribute:Ll.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...r,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+Il.join("|")+")\\b"}]}}function Pl(e){const t=e.regex;return {name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function zl(e){return {name:"Dockerfile",aliases:["docker"],case_insensitive:true,keywords:["from","maintainer","expose","env","arg","user","onbuild","stopsignal"],contains:[e.HASH_COMMENT_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{beginKeywords:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{end:/[^\\]$/,subLanguage:"bash"}}],illegal:"Ul(e,t,n-1))}const jl="[A-Za-z$_][0-9A-Za-z$_]*",Hl=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Wl=["true","false","null","undefined","NaN","Infinity"],Gl=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Ql=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Vl=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Kl=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Zl=[].concat(Vl,Gl,Ql);function Yl(e){const t=e.regex,n=jl,r="<>",o="",i={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/, /** * @param {RegExpMatchArray} match * @param {CallbackResponse} response */ isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let o;">"===r&&(((e,{after:t})=>{const n="`${e}\\s*\\(`),t.concat("(?!",A.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var A;const E={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:true,keywords:"prototype",className:"property",relevance:0},T={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},w]},M="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",_={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(M)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[w]};return {name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:a,exports:{PARAMS_CONTAINS:v,CLASS_REFERENCE:k},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,g,p,m,f,{match:/\$\d+/},d,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},_,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[f,e.REGEXP_MODE,{className:"function",begin:M,returnBegin:true,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:true},{begin:/(\s*)\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:a,contains:v}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:o},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:i.begin,"on:begin":i.isTrulyOpeningTag,end:i.end}],subLanguage:"xml",contains:[{begin:i.begin,end:i.end,skip:true,contains:["self"]}]}]},S,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:true,label:"func.def",contains:[w,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},E,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[w]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},x,T,{match:/\$[(.]/}]}}const Jl="[A-Za-z$_][0-9A-Za-z$_]*",Xl=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],ec=["true","false","null","undefined","NaN","Infinity"],tc=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],nc=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],rc=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],oc=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],ic=[].concat(rc,tc,nc);function ac(e){const t=e.regex,n=function(e){const t=e.regex,n=Jl,r="<>",o="",i={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/, /** * @param {RegExpMatchArray} match * @param {CallbackResponse} response */ isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];if("<"===r||","===r)return void t.ignoreMatch();let o;">"===r&&(((e,{after:t})=>{const n="`${e}\\s*\\(`),t.concat("(?!",A.join("|"),")")),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0};var A;const E={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:true,keywords:"prototype",className:"property",relevance:0},T={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},w]},M="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",_={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(M)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[w]};return {name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:a,exports:{PARAMS_CONTAINS:v,CLASS_REFERENCE:k},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,g,p,m,f,{match:/\$\d+/},d,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},_,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[f,e.REGEXP_MODE,{className:"function",begin:M,returnBegin:true,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:true},{begin:/(\s*)\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:a,contains:v}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r,end:o},{match:/<[A-Za-z0-9\\._:-]+\s*\/>/},{begin:i.begin,"on:begin":i.isTrulyOpeningTag,end:i.end}],subLanguage:"xml",contains:[{begin:i.begin,end:i.end,skip:true,contains:["self"]}]}]},S,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:true,label:"func.def",contains:[w,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},E,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[w]},C,{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},x,T,{match:/\$[(.]/}]}}(e),r=Jl,o=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},a={beginKeywords:"interface",end:/\{/,excludeEnd:true,keywords:{keyword:"interface extends",built_in:o},contains:[n.exports.CLASS_REFERENCE]},s={$pattern:Jl,keyword:Xl.concat(["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"]),literal:ec,built_in:ic.concat(o),"variable.language":oc},l={className:"meta",begin:"@"+r},c=(e,t,n)=>{const r=e.contains.findIndex(e=>e.label===t);if(-1===r)throw new Error("can not find mode to replace");e.contains.splice(r,1,n);};Object.assign(n.keywords,s),n.exports.PARAMS_CONTAINS.push(l);const d=n.contains.find(e=>"attr"===e.scope),u=Object.assign({},d,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,d,u]),n.contains=n.contains.concat([l,i,a,u]),c(n,"shebang",e.SHEBANG()),c(n,"use_strict",{className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/});return n.contains.find(e=>"func.def"===e.label).relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function sc(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},o={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},i=e.inherit(o,{begin:/\(/,end:/\)/}),a=e.inherit(e.APOS_STRING_MODE,{className:"string"}),s=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),l={endsWithParent:true,illegal:/`]+/}]}]}]};return {name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:true,unicodeRegex:true,contains:[{className:"meta",begin://,relevance:10,contains:[o,s,a,i,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[o,i,s,a]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[s]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[l],starts:{end:/<\/style>/,returnEnd:true,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:true,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:l}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:true}]}]}}function lc(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},o=e.inherit(r,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),i={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},a={end:",",endsWithParent:true,excludeEnd:true,keywords:t,relevance:0},s={begin:/\{/,end:/\}/,contains:[a],illegal:"\\n",relevance:0},l={begin:"\\[",end:"\\]",contains:[a],illegal:"\\n",relevance:0},c=[{className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:true,excludeEnd:true,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},i,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,l,{className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},r],d=[...c];return d.pop(),d.push(o),a.contains=d,{name:"YAML",case_insensitive:true,aliases:["yml"],contains:c}}const cc=String.raw`\[`,dc=String.raw`\(`,uc=(e,t,n=0)=>{let r=0,o=t-1;for(;o>=n&&92===e.charCodeAt(o);)r++,o--;return r},hc=(e,t,n)=>{let r=e.src.charCodeAt(t-1),o=e.src.charCodeAt(t+1),i=e.md.utils.isSpace;return {canOpen:n||!i(o),canClose:!(o>=48&&o<=57)&&(n||!i(r))}},gc=(e,t,n,r)=>{let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(36!==e.src.charCodeAt(o)||36!==e.src.charCodeAt(o+1))return false;if(r)return true;let a,s=e.skipSpacesBack(i,o),l=o+2,c=false;s-l>=2&&36===e.src.charCodeAt(s-1)&&36===e.src.charCodeAt(s-2)?(a=e.src.slice(l,s-2),c=true):a=e.src.slice(l,i);let d=t,u="";for(;!(c||(d++,d>=n||(l=e.bMarks[d]+e.tShift[d],i=e.eMarks[d],l=2&&36===e.src.charCodeAt(s-1)&&36===e.src.charCodeAt(s-2)&&(u=e.src.slice(l,s-2),c=true);e.line=c?d+1:d;let h=e.push("math_block","math",0);return h.block=true,h.content=(a?`${a}\n`:"")+e.getLines(t+1,d,e.tShift[t],true)+(u?`${u}\n`:""),h.map=[t,e.line],h.markup="$$",true},pc=(e,t,n,r)=>{let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(92!==e.src.charCodeAt(o)||91!==e.src.charCodeAt(o+1))return false;if(r)return true;let a,s=e.skipSpacesBack(i,o),l=o+2,c=false;s-l>=2&&93===e.src.charCodeAt(s-1)&&92===e.src.charCodeAt(s-2)?(a=e.src.slice(l,s-2),c=true):a=e.src.slice(l,i);let d=t,u="";for(;!(c||(d++,d>=n||(l=e.bMarks[d]+e.tShift[d],i=e.eMarks[d],l=2&&93===e.src.charCodeAt(s-1)&&92===e.src.charCodeAt(s-2)&&(u=e.src.slice(l,s-2).trimEnd(),c=true);if(!c)return false;e.line=d+1;let h=e.push("math_block","math",0);return h.block=true,h.content=(a?`${a}\n`:"")+e.getLines(t+1,d,e.tShift[t],true)+(u?`${u}\n`:""),h.map=[t,e.line],h.markup=cc,true},mc={alt:["paragraph","reference","blockquote","list"]},fc=(e,t)=>{if("function"!=typeof t?.render)throw TypeError('[@mdit/plugin-tex]: "render" option should be a function');let{allowInlineWithSpace:n=false,mathFence:r=false,delimiters:o="dollars",render:i}=t;if(r){let t=e.renderer.rules.fence;e.renderer.rules.fence=(e,n,r,o,a)=>{let s=e[n];return "math"===s.info.trim()?i(s.content,true,o):t(e,n,r,o,a)};}("dollars"===o||"all"===o)&&(e.inline.ruler.after("escape","math_inline_dollar",(e=>(t,n)=>{if("$"!==t.src[t.pos])return false;let r=hc(t,t.pos,e);if(!r.canOpen)return n||(t.pending+="$"),t.pos++,true;let o,i=t.pos+1;for(;-1!==(i=t.src.indexOf("$",i));){for(o=i-1;92===t.src.charCodeAt(o);)o--;if((i-o)%2==1)break;i++;}if(-1===i)return n||(t.pending+="$"),t.pos+=1,true;if(i-(t.pos+1)===0)return n||(t.pending+="$$"),t.pos+=2,true;if(r=hc(t,i,e),!r.canClose)return n||(t.pending+="$"),t.pos+=1,true;if(!n){let e=t.push("math_inline","math",0);e.markup="$",e.content=t.src.slice(t.pos+1,i);}return t.pos=i+1,true})(n)),e.block.ruler.after("blockquote","math_block_dollar",gc,mc)),("brackets"===o||"all"===o)&&(e.inline.ruler.before("escape","math_inline_bracket",(e,t)=>{let n=e.pos;if(92!==e.src.charCodeAt(n)||40!==e.src.charCodeAt(n+1))return false;let r=n+2,o=false,i=e.src.length;for(;ri(e[t].content,false,r),e.renderer.rules.math_block=(e,t,n,r)=>i(e[t].content,true,r);},bc={};function yc(e,t){"string"!=typeof t&&(t=yc.defaultChars);const n=function(e){let t=bc[e];if(t)return t;t=bc[e]=[];for(let n=0;n<128;n++){const e=String.fromCharCode(n);t.push(e);}for(let n=0;n=55296&&e<=57343?"���":String.fromCharCode(e),r+=6;continue}}if(240==(248&i)&&r+91114111?t+="����":(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(1023&e))),r+=9;continue}}t+="�";}}return t})}yc.defaultChars=";/?:@&=+$,#",yc.componentChars="";const vc={};function wc(e,t,n){"string"!=typeof t&&(n=t,t=wc.defaultChars),void 0===n&&(n=true);const r=function(e){let t=vc[e];if(t)return t;t=vc[e]=[];for(let n=0;n<128;n++){const e=String.fromCharCode(n);/^[0-9a-z]$/i.test(e)?t.push(e):t.push("%"+("0"+n.toString(16).toUpperCase()).slice(-2));}for(let n=0;n=55296&&t<=57343){if(t>=55296&&t<=56319&&i+1=56320&&t<=57343){o+=encodeURIComponent(e[i]+e[i+1]),i++;continue}}o+="%EF%BF%BD";}else o+=encodeURIComponent(e[i]);}return o}function xc(e){let t="";return t+=e.protocol||"",t+=e.slashes?"//":"",t+=e.auth?e.auth+"@":"",e.hostname&&-1!==e.hostname.indexOf(":")?t+="["+e.hostname+"]":t+=e.hostname||"",t+=e.port?":"+e.port:"",t+=e.pathname||"",t+=e.search||"",t+=e.hash||"",t}function kc(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null;}wc.defaultChars=";/?:@&=+$,-_.!~*'()#",wc.componentChars="-_.!~*'()";const Sc=/^([a-z0-9.+-]+:)/i,Cc=/:[0-9]*$/,Ac=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,Ec=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),Tc=["'"].concat(Ec),Mc=["%","/","?",";","#"].concat(Tc),_c=["/","?","#"],Ic=/^[+a-z0-9A-Z_-]{0,63}$/,Lc=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Nc={javascript:true,"javascript:":true},Dc={http:true,https:true,ftp:true,gopher:true,file:true,"http:":true,"https:":true,"ftp:":true,"gopher:":true,"file:":true};function qc(e,t){if(e&&e instanceof kc)return e;const n=new kc;return n.parse(e,t),n}kc.prototype.parse=function(e,t){let n,r,o,i=e;if(i=i.trim(),!t&&1===e.split("#").length){const e=Ac.exec(i);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let a=Sc.exec(i);if(a&&(a=a[0],n=a.toLowerCase(),this.protocol=a,i=i.substr(a.length)),(t||a||i.match(/^\/\/[^@\/]+@[^@\/]+/))&&(o="//"===i.substr(0,2),!o||a&&Nc[a]||(i=i.substr(2),this.slashes=true)),!Nc[a]&&(o||a&&!Dc[a])){let e,t,n=-1;for(let s=0;s<_c.length;s++)r=i.indexOf(_c[s]),-1!==r&&(-1===n||r127?r+="x":r+=n[e];if(!r.match(Ic)){const r=e.slice(0,t),o=e.slice(t+1),a=n.match(Lc);a&&(r.push(a[1]),o.unshift(a[2])),o.length&&(i=o.join(".")+i),this.hostname=r.join(".");break}}}}this.hostname.length>255&&(this.hostname=""),a&&(this.hostname=this.hostname.substr(1,this.hostname.length-2));}const s=i.indexOf("#");-1!==s&&(this.hash=i.substr(s),i=i.slice(0,s));const l=i.indexOf("?");return -1!==l&&(this.search=i.substr(l),i=i.slice(0,l)),i&&(this.pathname=i),Dc[n]&&this.hostname&&!this.pathname&&(this.pathname=""),this},kc.prototype.parseHost=function(e){let t=Cc.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e);};const Rc=Object.freeze(Object.defineProperty({__proto__:null,decode:yc,encode:wc,format:xc,parse:qc},Symbol.toStringTag,{value:"Module"})),Pc=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,zc=/[\0-\x1F\x7F-\x9F]/,Bc=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/,Oc=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B97-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBC2\uFD40-\uFD4F\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF76\uDF7B-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC5\uDECE-\uDEDB\uDEE0-\uDEE8\uDEF0-\uDEF8\uDF00-\uDF92\uDF94-\uDFCA]/,Fc=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,$c=Object.freeze(Object.defineProperty({__proto__:null,Any:Pc,Cc:zc,Cf:/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,P:Bc,S:Oc,Z:Fc},Symbol.toStringTag,{value:"Module"})),Uc=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),jc=new Uint16Array("Ȁaglq\tɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(e=>e.charCodeAt(0)));var Hc;const Wc=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),Gc= // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins null!==(Hc=String.fromCodePoint)&&void 0!==Hc?Hc:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|1023&e),t+=String.fromCharCode(e),t};var Qc,Vc;(Vc=Qc||(Qc={}))[Vc.NUM=35]="NUM",Vc[Vc.SEMI=59]="SEMI",Vc[Vc.EQUALS=61]="EQUALS",Vc[Vc.ZERO=48]="ZERO",Vc[Vc.NINE=57]="NINE",Vc[Vc.LOWER_A=97]="LOWER_A",Vc[Vc.LOWER_F=102]="LOWER_F",Vc[Vc.LOWER_X=120]="LOWER_X",Vc[Vc.LOWER_Z=122]="LOWER_Z",Vc[Vc.UPPER_A=65]="UPPER_A",Vc[Vc.UPPER_F=70]="UPPER_F",Vc[Vc.UPPER_Z=90]="UPPER_Z";var Kc,Zc,Yc,Jc,Xc,ed;function td(e){return e>=Qc.ZERO&&e<=Qc.NINE}function nd(e){return e>=Qc.UPPER_A&&e<=Qc.UPPER_F||e>=Qc.LOWER_A&&e<=Qc.LOWER_F}function rd(e){return e===Qc.EQUALS||function(e){return e>=Qc.UPPER_A&&e<=Qc.UPPER_Z||e>=Qc.LOWER_A&&e<=Qc.LOWER_Z||td(e)}(e)}(Zc=Kc||(Kc={}))[Zc.VALUE_LENGTH=49152]="VALUE_LENGTH",Zc[Zc.BRANCH_LENGTH=16256]="BRANCH_LENGTH",Zc[Zc.JUMP_TABLE=127]="JUMP_TABLE",(Jc=Yc||(Yc={}))[Jc.EntityStart=0]="EntityStart",Jc[Jc.NumericStart=1]="NumericStart",Jc[Jc.NumericDecimal=2]="NumericDecimal",Jc[Jc.NumericHex=3]="NumericHex",Jc[Jc.NamedEntity=4]="NamedEntity",(ed=Xc||(Xc={}))[ed.Legacy=0]="Legacy",ed[ed.Strict=1]="Strict",ed[ed.Attribute=2]="Attribute";class od{constructor(e,t,n){this.decodeTree=e,this.emitCodePoint=t,this.errors=n,this.state=Yc.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Xc.Strict;}startEntity(e){this.decodeMode=e,this.state=Yc.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1;} /** * Write an entity to the decoder. This can be called multiple times with partial entities. * If the entity is incomplete, the decoder will return -1. * * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the * entity is incomplete, and resume when the next string is written. * * @param string The string containing the entity (or a continuation of the entity). * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */write(e,t){switch(this.state){case Yc.EntityStart:return e.charCodeAt(t)===Qc.NUM?(this.state=Yc.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=Yc.NamedEntity,this.stateNamedEntity(e,t));case Yc.NumericStart:return this.stateNumericStart(e,t);case Yc.NumericDecimal:return this.stateNumericDecimal(e,t);case Yc.NumericHex:return this.stateNumericHex(e,t);case Yc.NamedEntity:return this.stateNamedEntity(e,t)}} /** * Switches between the numeric decimal and hexadecimal states. * * Equivalent to the `Numeric character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNumericStart(e,t){return t>=e.length?-1:(32|e.charCodeAt(t))===Qc.LOWER_X?(this.state=Yc.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=Yc.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,n,r){if(t!==n){const o=n-t;this.result=this.result*Math.pow(r,o)+parseInt(e.substr(t,o),r),this.consumed+=o;}} /** * Parses a hexadecimal numeric entity. * * Equivalent to the `Hexademical character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNumericHex(e,t){const n=t;for(;t=55296&&e<=57343||e>1114111?65533:null!==(t=Wc.get(e))&&void 0!==t?t:e}(this.result),this.consumed),this.errors&&(e!==Qc.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed} /** * Parses a named entity. * * Equivalent to the `Named character reference state` in the HTML spec. * * @param str The string containing the entity (or a continuation of the entity). * @param offset The current offset. * @returns The number of characters that were consumed, or -1 if the entity is incomplete. */stateNamedEntity(e,t){const{decodeTree:n}=this;let r=n[this.treeIndex],o=(r&Kc.VALUE_LENGTH)>>14;for(;t>14,0!==o){if(i===Qc.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==Xc.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0);}}return -1} /** * Emit a named entity that was not terminated with a semicolon. * * @returns The number of characters consumed. */emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:n}=this,r=(n[t]&Kc.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,r,this.consumed),null===(e=this.errors)||void 0===e||e.missingSemicolonAfterCharacterReference(),this.consumed} /** * Emit a named entity. * * @param result The index of the entity in the decode tree. * @param valueLength The number of bytes in the entity. * @param consumed The number of characters consumed. * * @returns The number of characters consumed. */emitNamedEntityData(e,t,n){const{decodeTree:r}=this;return this.emitCodePoint(1===t?r[e]&~Kc.VALUE_LENGTH:r[e+1],n),3===t&&this.emitCodePoint(r[e+2],n),n} /** * Signal to the parser that the end of the input was reached. * * Remaining data will be emitted and relevant errors will be produced. * * @returns The number of characters consumed. */end(){var e;switch(this.state){case Yc.NamedEntity:return 0===this.result||this.decodeMode===Xc.Attribute&&this.result!==this.treeIndex?0:this.emitNotTerminatedNamedEntity();case Yc.NumericDecimal:return this.emitNumericEntity(0,2);case Yc.NumericHex:return this.emitNumericEntity(0,3);case Yc.NumericStart:return null===(e=this.errors)||void 0===e||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Yc.EntityStart:return 0}}}function id(e){let t="";const n=new od(e,e=>t+=Gc(e));return function(e,r){let o=0,i=0;for(;(i=e.indexOf("&",i))>=0;){t+=e.slice(o,i),n.startEntity(r);const a=n.write(e,i+1);if(a<0){o=i+n.end();break}o=i+a,i=0===a?o+1:o;}const a=t+e.slice(o);return t="",a}}function ad(e,t,n,r){const o=(t&Kc.BRANCH_LENGTH)>>7,i=t&Kc.JUMP_TABLE;if(0===o)return 0!==i&&r===i?n:-1;if(i){const t=r-i;return t<0||t>=o?-1:e[n+t]-1}let a=n,s=a+o-1;for(;a<=s;){const t=a+s>>>1,n=e[t];if(nr))return e[t+o];s=t-1;}}return -1}const sd=id(Uc);function ld(e,t=Xc.Legacy){return sd(e,t)}function cd(e){return "[object String]"===function(e){return Object.prototype.toString.call(e)}(e)}id(jc);const dd=Object.prototype.hasOwnProperty;function ud(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){if(t){if("object"!=typeof t)throw new TypeError(t+"must be object");Object.keys(t).forEach(function(n){e[n]=t[n];});}}),e}function hd(e,t,n){return [].concat(e.slice(0,t),n,e.slice(t+1))}function gd(e){return !(e>=55296&&e<=57343)&&(!(e>=64976&&e<=65007)&&(!!(65535&~e&&65534!=(65535&e))&&(!(e>=0&&e<=8)&&(11!==e&&(!(e>=14&&e<=31)&&(!(e>=127&&e<=159)&&!(e>1114111)))))))}function pd(e){if(e>65535){const t=55296+((e-=65536)>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}const md=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,fd=new RegExp(md.source+"|"+/&([a-z#][a-z0-9]{1,31});/gi.source,"gi"),bd=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function yd(e){return e.indexOf("\\")<0&&e.indexOf("&")<0?e:e.replace(fd,function(e,t,n){return t||function(e,t){if(35===t.charCodeAt(0)&&bd.test(t)){const n="x"===t[1].toLowerCase()?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return gd(n)?pd(n):e}const n=ld(e);return n!==e?n:e}(e,n)})}const vd=/[&<>"]/,wd=/[&<>"]/g,xd={"&":"&","<":"<",">":">",'"':"""};function kd(e){return xd[e]}function Sd(e){return vd.test(e)?e.replace(wd,kd):e}const Cd=/[.?*+^$[\]\\(){}|-]/g;function Ad(e){switch(e){case 9:case 32:return true}return false}function Ed(e){if(e>=8192&&e<=8202)return true;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return true}return false}function Td(e){return Bc.test(e)||Oc.test(e)}function Md(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return true;default:return false}}function _d(e){return e=e.trim().replace(/\s+/g," "),"Ṿ"==="ẞ".toLowerCase()&&(e=e.replace(/ẞ/g,"ß")),e.toLowerCase().toUpperCase()}const Id={mdurl:Rc,ucmicro:$c},Ld=Object.freeze(Object.defineProperty({__proto__:null,arrayReplaceAt:hd,assign:ud,escapeHtml:Sd,escapeRE:function(e){return e.replace(Cd,"\\$&")},fromCodePoint:pd,has:function(e,t){return dd.call(e,t)},isMdAsciiPunct:Md,isPunctChar:Td,isSpace:Ad,isString:cd,isValidEntityCode:gd,isWhiteSpace:Ed,lib:Id,normalizeReference:_d,unescapeAll:yd,unescapeMd:function(e){return e.indexOf("\\")<0?e:e.replace(md,"$1")}},Symbol.toStringTag,{value:"Module"}));const Nd=Object.freeze(Object.defineProperty({__proto__:null,parseLinkDestination:function(e,t,n){let r,o=t;const i={ok:false,pos:0,str:""};if(60===e.charCodeAt(o)){for(o++;o32))return i;if(41===r){if(0===a)break;a--;}o++;}return t===o||0!==a||(i.str=yd(e.slice(t,o)),i.pos=o,i.ok=true),i},parseLinkLabel:function(e,t,n){let r,o,i,a;const s=e.posMax,l=e.pos;for(e.pos=t+1,r=1;e.pos=n)return a;let r=e.charCodeAt(i);if(34!==r&&39!==r&&40!==r)return a;t++,i++,40===r&&(r=41),a.marker=r;}for(;i"+Sd(i.content)+""},Dd.code_block=function(e,t,n,r,o){const i=e[t];return ""+Sd(e[t].content)+"\n"},Dd.fence=function(e,t,n,r,o){const i=e[t],a=i.info?yd(i.info).trim():"";let s,l="",c="";if(a){const e=a.split(/(\s+)/g);l=e[0],c=e.slice(2).join("");}if(s=n.highlight&&n.highlight(i.content,l,c)||Sd(i.content),0===s.indexOf("${s}\n`}return `
${s}
\n`},Dd.image=function(e,t,n,r,o){const i=e[t];return i.attrs[i.attrIndex("alt")][1]=o.renderInlineAsText(i.children,n,r),o.renderToken(e,t,n)},Dd.hardbreak=function(e,t,n){return n.xhtmlOut?"
\n":"
\n"},Dd.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?"
\n":"
\n":"\n"},Dd.text=function(e,t){return Sd(e[t].content)},Dd.html_block=function(e,t){return e[t].content},Dd.html_inline=function(e,t){return e[t].content},qd.prototype.renderAttrs=function(e){let t,n,r;if(!e.attrs)return "";for(r="",t=0,n=e.attrs.length;t\n":">",o},qd.prototype.renderInline=function(e,t,n){let r="";const o=this.rules;for(let i=0,a=e.length;i=0&&(n=this.attrs[t][1]),n},Pd.prototype.attrJoin=function(e,t){const n=this.attrIndex(e);n<0?this.attrPush([e,t]):this.attrs[n][1]=this.attrs[n][1]+" "+t;},zd.prototype.Token=Pd;const Bd=/\r\n?|\n/g,Od=/\0/g;function Fd(e){return /^\s]/i.test(e)}function $d(e){return /^<\/a\s*>/i.test(e)}const Ud=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,jd=/\((c|tm|r)\)/i,Hd=/\((c|tm|r)\)/gi,Wd={c:"©",r:"®",tm:"™"};function Gd(e,t){return Wd[t.toLowerCase()]}function Qd(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||(r.content=r.content.replace(Hd,Gd)),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++;}}function Vd(e){let t=0;for(let n=e.length-1;n>=0;n--){const r=e[n];"text"!==r.type||t||Ud.test(r.content)&&(r.content=r.content.replace(/\+-/g,"±").replace(/\.{2,}/g,"…").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/gm,"$1—").replace(/(^|\s)--(?=\s|$)/gm,"$1–").replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,"$1–")),"link_open"===r.type&&"auto"===r.info&&t--,"link_close"===r.type&&"auto"===r.info&&t++;}}const Kd=/['"]/,Zd=/['"]/g;function Yd(e,t,n){return e.slice(0,t)+n+e.slice(t+1)}function Jd(e,t){let n;const r=[];for(let o=0;o=0&&!(r[n].level<=a);n--);if(r.length=n+1,"text"!==i.type)continue;let s=i.content,l=0,c=s.length;e:for(;l=0)p=s.charCodeAt(d.index-1);else for(n=o-1;n>=0&&("softbreak"!==e[n].type&&"hardbreak"!==e[n].type);n--)if(e[n].content){p=e[n].content.charCodeAt(e[n].content.length-1);break}let m=32;if(l=48&&p<=57&&(h=u=false),u&&h&&(u=f,h=b),u||h){if(h)for(n=r.length-1;n>=0;n--){let u=r[n];if(r[n].level=0;i--){const a=r[i];if("link_close"!==a.type){if("html_inline"===a.type&&(Fd(a.content)&&o>0&&o--,$d(a.content)&&o++),!(o>0)&&"text"===a.type&&e.md.linkify.test(a.content)){const o=a.content;let s=e.md.linkify.match(o);const l=[];let c=a.level,d=0;s.length>0&&0===s[0].index&&i>0&&"text_special"===r[i-1].type&&(s=s.slice(1));for(let t=0;td){const t=new e.Token("text","",0);t.content=o.slice(d,a),t.level=c,l.push(t);}const u=new e.Token("link_open","a",1);u.attrs=[["href",r]],u.level=c++,u.markup="linkify",u.info="auto",l.push(u);const h=new e.Token("text","",0);h.content=i,h.level=c,l.push(h);const g=new e.Token("link_close","a",-1);g.level=--c,g.markup="linkify",g.info="auto",l.push(g),d=s[t].lastIndex;}if(d=0;t--)"inline"===e.tokens[t].type&&(jd.test(e.tokens[t].content)&&Qd(e.tokens[t].children),Ud.test(e.tokens[t].content)&&Vd(e.tokens[t].children));}],["smartquotes",function(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)"inline"===e.tokens[t].type&&Kd.test(e.tokens[t].content)&&Jd(e.tokens[t].children,e);}],["text_join",function(e){let t,n;const r=e.tokens,o=r.length;for(let i=0;i0&&this.level++,this.tokens.push(r),r},tu.prototype.isEmpty=function(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]},tu.prototype.skipEmptyLines=function(e){for(let t=this.lineMax;et;)if(!Ad(this.src.charCodeAt(--e)))return e+1;return e},tu.prototype.skipChars=function(e,t){for(let n=this.src.length;en;)if(t!==this.src.charCodeAt(--e))return e+1;return e},tu.prototype.getLines=function(e,t,n,r){if(e>=t)return "";const o=new Array(t-e);for(let i=0,a=e;an?new Array(e-n+1).join(" ")+this.src.slice(c,l):this.src.slice(c,l);}return o.join("")},tu.prototype.Token=Pd;function nu(e,t){const n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function ru(e){const t=[],n=e.length;let r=0,o=e.charCodeAt(r),i=false,a=0,s="";for(;r=r)return -1;let i=e.src.charCodeAt(o++);if(i<48||i>57)return -1;for(;;){if(o>=r)return -1;if(i=e.src.charCodeAt(o++),!(i>=48&&i<=57)){if(41===i||46===i)break;return -1}if(o-n>=10)return -1}return o`\\x00-\\x20]+|'[^']*'|\"[^\"]*\"))?)*\\s*\\/?>",su="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",lu=new RegExp("^(?:"+au+"|"+su+"|\x3c!---?>|\x3c!--(?:[^-]|-[^-]|--[^>])*--\x3e|<[?][\\s\\S]*?[?]>|]*>|)"),cu=new RegExp("^(?:"+au+"|"+su+")"),du=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,true],[/^/,true],[/^<\?/,/\?>/,true],[/^/,true],[/^/,true],[new RegExp("^|$))","i"),/^$/,true],[new RegExp(cu.source+"\\s*$"),/^$/,false]];const uu=[["table",function(e,t,n,r){if(t+2>n)return false;let o=t+1;if(e.sCount[o]=4)return false;let i=e.bMarks[o]+e.tShift[o];if(i>=e.eMarks[o])return false;const a=e.src.charCodeAt(i++);if(124!==a&&45!==a&&58!==a)return false;if(i>=e.eMarks[o])return false;const s=e.src.charCodeAt(i++);if(124!==s&&45!==s&&58!==s&&!Ad(s))return false;if(45===a&&Ad(s))return false;for(;i=4)return false;c=ru(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop();const u=c.length;if(0===u||u!==d.length)return false;if(r)return true;const h=e.parentType;e.parentType="table";const g=e.md.block.ruler.getRules("blockquote"),p=[t,0];e.push("table_open","table",1).map=p,e.push("thead_open","thead",1).map=[t,t+1],e.push("tr_open","tr",1).map=[t,t+1];for(let b=0;b=4)break;if(c=ru(l),c.length&&""===c[0]&&c.shift(),c.length&&""===c[c.length-1]&&c.pop(),f+=u-c.length,f>65536)break;if(o===t+2){e.push("tbody_open","tbody",1).map=m=[t+2,0];}e.push("tr_open","tr",1).map=[o,o+1];for(let t=0;t=4))break;r++,o=r;}e.line=o;const i=e.push("code_block","code",0);return i.content=e.getLines(t,o,4+e.blkIndent,false)+"\n",i.map=[t,e.line],true}],["fence",function(e,t,n,r){let o=e.bMarks[t]+e.tShift[t],i=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4)return false;if(o+3>i)return false;const a=e.src.charCodeAt(o);if(126!==a&&96!==a)return false;let s=o;o=e.skipChars(o,a);let l=o-s;if(l<3)return false;const c=e.src.slice(s,o),d=e.src.slice(o,i);if(96===a&&d.indexOf(String.fromCharCode(a))>=0)return false;if(r)return true;let u=t,h=false;for(;(u++,!(u>=n))&&(o=s=e.bMarks[u]+e.tShift[u],i=e.eMarks[u],!(o=4||(o=e.skipChars(o,a),o-s=4)return false;if(62!==e.src.charCodeAt(o))return false;if(r)return true;const s=[],l=[],c=[],d=[],u=e.md.block.ruler.getRules("blockquote"),h=e.parentType;e.parentType="blockquote";let g,p=false;for(g=t;g=i)break;if(62===e.src.charCodeAt(o++)&&!t){let t,n,r=e.sCount[g]+1;32===e.src.charCodeAt(o)?(o++,r++,n=false,t=true):9===e.src.charCodeAt(o)?(t=true,(e.bsCount[g]+r)%4==3?(o++,r++,n=false):n=true):t=false;let a=r;for(s.push(e.bMarks[g]),e.bMarks[g]=o;o=i,l.push(e.bsCount[g]),e.bsCount[g]=e.sCount[g]+1+(t?1:0),c.push(e.sCount[g]),e.sCount[g]=a-r,d.push(e.tShift[g]),e.tShift[g]=o-e.bMarks[g];continue}if(p)break;let r=false;for(let o=0,i=u.length;o";const b=[t,0];f.map=b,e.md.block.tokenize(e,t,g),e.push("blockquote_close","blockquote",-1).markup=">",e.lineMax=a,e.parentType=h,b[1]=e.line;for(let y=0;y=4)return false;let i=e.bMarks[t]+e.tShift[t];const a=e.src.charCodeAt(i++);if(42!==a&&45!==a&&95!==a)return false;let s=1;for(;i=4)return false;if(e.listIndent>=0&&e.sCount[l]-e.listIndent>=4&&e.sCount[l]=e.blkIndent&&(g=true),(h=iu(e,l))>=0){if(d=true,a=e.bMarks[l]+e.tShift[l],u=Number(e.src.slice(a,h-1)),g&&1!==u)return false}else {if(!((h=ou(e,l))>=0))return false;d=false;}if(g&&e.skipSpaces(h)>=e.eMarks[l])return false;if(r)return true;const p=e.src.charCodeAt(h-1),m=e.tokens.length;d?(s=e.push("ordered_list_open","ol",1),1!==u&&(s.attrs=[["start",u]])):s=e.push("bullet_list_open","ul",1);const f=[l,0];s.map=f,s.markup=String.fromCharCode(p);let b=false;const y=e.md.block.ruler.getRules("list"),v=e.parentType;for(e.parentType="list";l=o?1:r-t,g>4&&(g=1);const m=t+g;s=e.push("list_item_open","li",1),s.markup=String.fromCharCode(p);const f=[l,0];s.map=f,d&&(s.info=e.src.slice(a,h-1));const v=e.tight,w=e.tShift[l],x=e.sCount[l],k=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=m,e.tight=true,e.tShift[l]=u-e.bMarks[l],e.sCount[l]=r,u>=o&&e.isEmpty(l+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,l,n,true),e.tight&&!b||(c=false),b=e.line-l>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=k,e.tShift[l]=w,e.sCount[l]=x,e.tight=v,s=e.push("list_item_close","li",-1),s.markup=String.fromCharCode(p),l=e.line,f[1]=l,l>=n)break;if(e.sCount[l]=4)break;let S=false;for(let o=0,i=y.length;o=4)return false;if(91!==e.src.charCodeAt(o))return false;function s(t){const n=e.lineMax;if(t>=n||e.isEmpty(t))return null;let r=false;if(e.sCount[t]-e.blkIndent>3&&(r=true),e.sCount[t]<0&&(r=true),!r){const r=e.md.block.ruler.getRules("reference"),o=e.parentType;e.parentType="reference";let i=false;for(let a=0,s=r.length;a=4)return false;if(!e.md.options.html)return false;if(60!==e.src.charCodeAt(o))return false;let a=e.src.slice(o,i),s=0;for(;s=4)return false;let a=e.src.charCodeAt(o);if(35!==a||o>=i)return false;let s=1;for(a=e.src.charCodeAt(++o);35===a&&o6||oo&&Ad(e.src.charCodeAt(l-1))&&(i=l),e.line=t+1;const c=e.push("heading_open","h"+String(s),1);c.markup="########".slice(0,s),c.map=[t,e.line];const d=e.push("inline","",0);return d.content=e.src.slice(o,i).trim(),d.map=[t,e.line],d.children=[],e.push("heading_close","h"+String(s),-1).markup="########".slice(0,s),true},["paragraph","reference","blockquote"]],["lheading",function(e,t,n){const r=e.md.block.ruler.getRules("paragraph");if(e.sCount[t]-e.blkIndent>=4)return false;const o=e.parentType;e.parentType="paragraph";let i,a=0,s=t+1;for(;s3)continue;if(e.sCount[s]>=e.blkIndent){let t=e.bMarks[s]+e.tShift[s];const n=e.eMarks[s];if(t=n))){a=61===i?1:2;break}}if(e.sCount[s]<0)continue;let t=false;for(let o=0,i=r.length;o3)continue;if(e.sCount[i]<0)continue;let t=false;for(let o=0,a=r.length;o=n))&&!(e.sCount[a]=i){e.line=n;break}const t=e.line;let l=false;for(let i=0;i=e.line)throw new Error("block rule didn't increment state.line");break}if(!l)throw new Error("none of the block rules matched");e.tight=!s,e.isEmpty(e.line-1)&&(s=true),a=e.line,a0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],o={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(r),this.tokens_meta.push(o),r},gu.prototype.scanDelims=function(e,t){const n=this.posMax,r=this.src.charCodeAt(e),o=e>0?this.src.charCodeAt(e-1):32;let i=e;for(;i?@[]^_`{|}~-".split("").forEach(function(e){fu[e.charCodeAt(0)]=1;});const yu={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return false;if(126!==r)return false;const o=e.scanDelims(e.pos,true);let i=o.length;const a=String.fromCharCode(r);if(i<2)return false;let s;i%2&&(s=e.push("text","",0),s.content=a,i--);for(let l=0;l=0;n--){const r=t[n];if(95!==r.marker&&42!==r.marker)continue;if(-1===r.end)continue;const o=t[r.end],i=n>0&&t[n-1].end===r.end+1&&t[n-1].marker===r.marker&&t[n-1].token===r.token-1&&t[r.end+1].token===o.token+1,a=String.fromCharCode(r.marker),s=e.tokens[r.token];s.type=i?"strong_open":"em_open",s.tag=i?"strong":"em",s.nesting=1,s.markup=i?a+a:a,s.content="";const l=e.tokens[o.token];l.type=i?"strong_close":"em_close",l.tag=i?"strong":"em",l.nesting=-1,l.markup=i?a+a:a,l.content="",i&&(e.tokens[t[n-1].token].content="",e.tokens[t[r.end+1].token].content="",n--);}}const wu={tokenize:function(e,t){const n=e.pos,r=e.src.charCodeAt(n);if(t)return false;if(95!==r&&42!==r)return false;const o=e.scanDelims(e.pos,42===r);for(let i=0;i\x00-\x20]*)$/;const Su=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,Cu=/^&([a-z][a-z0-9]{1,31});/i;function Au(e){const t={},n=e.length;if(!n)return;let r=0,o=-2;const i=[];for(let a=0;as;l-=i[l]+1){const t=e[l];if(t.marker===n.marker&&(t.open&&t.end<0)){let r=false;if((t.close||n.open)&&(t.length+n.length)%3==0&&(t.length%3==0&&n.length%3==0||(r=true)),!r){const r=l>0&&!e[l-1].open?i[l-1]+1:0;i[a]=a-l+r,i[l]=r,n.open=false,t.end=a,t.close=false,c=-1,o=-2;break}}} -1!==c&&(t[n.marker][(n.open?3:0)+(n.length||0)%3]=c);}}const Eu=[["text",function(e,t){let n=e.pos;for(;n0)return false;const n=e.pos;if(n+3>e.posMax)return false;if(58!==e.src.charCodeAt(n))return false;if(47!==e.src.charCodeAt(n+1))return false;if(47!==e.src.charCodeAt(n+2))return false;const r=e.pending.match(mu);if(!r)return false;const o=r[1],i=e.md.linkify.matchAtStart(e.src.slice(n-o.length));if(!i)return false;let a=i.url;if(a.length<=o.length)return false;a=a.replace(/\*+$/,"");const s=e.md.normalizeLink(a);if(!e.md.validateLink(s))return false;if(!t){e.pending=e.pending.slice(0,-o.length);const t=e.push("link_open","a",1);t.attrs=[["href",s]],t.markup="linkify",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(a);const n=e.push("link_close","a",-1);n.markup="linkify",n.info="auto";}return e.pos+=a.length-o.length,true}],["newline",function(e,t){let n=e.pos;if(10!==e.src.charCodeAt(n))return false;const r=e.pending.length-1,o=e.posMax;if(!t)if(r>=0&&32===e.pending.charCodeAt(r))if(r>=1&&32===e.pending.charCodeAt(r-1)){let t=r-1;for(;t>=1&&32===e.pending.charCodeAt(t-1);)t--;e.pending=e.pending.slice(0,t),e.push("hardbreak","br",0);}else e.pending=e.pending.slice(0,-1),e.push("softbreak","br",0);else e.push("softbreak","br",0);for(n++;n=r)return false;let o=e.src.charCodeAt(n);if(10===o){for(t||e.push("hardbreak","br",0),n++;n=55296&&o<=56319&&n+1=56320&&t<=57343&&(i+=e.src[n+1],n++);}const a="\\"+i;if(!t){const t=e.push("text_special","",0);o<256&&0!==fu[o]?t.content=i:t.content=a,t.markup=a,t.info="escape";}return e.pos=n+1,true}],["backticks",function(e,t){let n=e.pos;if(96!==e.src.charCodeAt(n))return false;const r=n;n++;const o=e.posMax;for(;n=u)return false;if(l=p,o=e.md.helpers.parseLinkDestination(e.src,p,e.posMax),o.ok){for(a=e.md.normalizeLink(o.str),e.md.validateLink(a)?p=o.pos:a="",l=p;p=u||41!==e.src.charCodeAt(p))&&(c=true),p++;}if(c){if(void 0===e.env.references)return false;if(p=0?r=e.src.slice(l,p++):p=g+1):p=g+1,r||(r=e.src.slice(h,g)),i=e.env.references[_d(r)],!i)return e.pos=d,false;a=i.href,s=i.title;}if(!t){e.pos=h,e.posMax=g;const t=[["href",a]];e.push("link_open","a",1).attrs=t,s&&t.push(["title",s]),e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push("link_close","a",-1);}return e.pos=p,e.posMax=u,true}],["image",function(e,t){let n,r,o,i,a,s,l,c,d="";const u=e.pos,h=e.posMax;if(33!==e.src.charCodeAt(e.pos))return false;if(91!==e.src.charCodeAt(e.pos+1))return false;const g=e.pos+2,p=e.md.helpers.parseLinkLabel(e,e.pos+1,false);if(p<0)return false;if(i=p+1,i=h)return false;for(c=i,s=e.md.helpers.parseLinkDestination(e.src,i,e.posMax),s.ok&&(d=e.md.normalizeLink(s.str),e.md.validateLink(d)?i=s.pos:d=""),c=i;i=h||41!==e.src.charCodeAt(i))return e.pos=u,false;i++;}else {if(void 0===e.env.references)return false;if(i=0?o=e.src.slice(c,i++):i=p+1):i=p+1,o||(o=e.src.slice(g,p)),a=e.env.references[_d(o)],!a)return e.pos=u,false;d=a.href,l=a.title;}if(!t){r=e.src.slice(g,p);const t=[];e.md.inline.parse(r,e.md,e.env,t);const n=e.push("image","img",0),o=[["src",d],["alt",""]];n.attrs=o,n.children=t,n.content=r,l&&o.push(["title",l]);}return e.pos=i,e.posMax=h,true}],["autolink",function(e,t){let n=e.pos;if(60!==e.src.charCodeAt(n))return false;const r=e.pos,o=e.posMax;for(;;){if(++n>=o)return false;const t=e.src.charCodeAt(n);if(60===t)return false;if(62===t)break}const i=e.src.slice(r+1,n);if(ku.test(i)){const n=e.md.normalizeLink(i);if(!e.md.validateLink(n))return false;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto";}return e.pos+=i.length+2,true}if(xu.test(i)){const n=e.md.normalizeLink("mailto:"+i);if(!e.md.validateLink(n))return false;if(!t){const t=e.push("link_open","a",1);t.attrs=[["href",n]],t.markup="autolink",t.info="auto";e.push("text","",0).content=e.md.normalizeLinkText(i);const r=e.push("link_close","a",-1);r.markup="autolink",r.info="auto";}return e.pos+=i.length+2,true}return false}],["html_inline",function(e,t){if(!e.md.options.html)return false;const n=e.posMax,r=e.pos;if(60!==e.src.charCodeAt(r)||r+2>=n)return false;const o=e.src.charCodeAt(r+1);if(33!==o&&63!==o&&47!==o&&!function(e){const t=32|e;return t>=97&&t<=122}(o))return false;const i=e.src.slice(r).match(lu);if(!i)return false;if(!t){const t=e.push("html_inline","",0);t.content=i[0],a=t.content,/^\s]/i.test(a)&&e.linkLevel++,function(e){return /^<\/a\s*>/i.test(e)}(t.content)&&e.linkLevel--;}var a;return e.pos+=i[0].length,true}],["entity",function(e,t){const n=e.pos,r=e.posMax;if(38!==e.src.charCodeAt(n))return false;if(n+1>=r)return false;if(35===e.src.charCodeAt(n+1)){const r=e.src.slice(n).match(Su);if(r){if(!t){const t="x"===r[1][0].toLowerCase()?parseInt(r[1].slice(1),16):parseInt(r[1],10),n=e.push("text_special","",0);n.content=gd(t)?pd(t):pd(65533),n.markup=r[0],n.info="entity";}return e.pos+=r[0].length,true}}else {const r=e.src.slice(n).match(Cu);if(r){const n=ld(r[0]);if(n!==r[0]){if(!t){const t=e.push("text_special","",0);t.content=n,t.markup=r[0],t.info="entity";}return e.pos+=r[0].length,true}}}return false}]],Tu=[["balance_pairs",function(e){const t=e.tokens_meta,n=e.tokens_meta.length;Au(e.delimiters);for(let r=0;r0&&r++,"text"===o[t].type&&t+1=e.pos)throw new Error("inline rule didn't increment state.pos");break}}else e.pos=e.posMax;a||e.pos++,i[t]=e.pos;},Mu.prototype.tokenize=function(e){const t=this.ruler.getRules(""),n=t.length,r=e.posMax,o=e.md.options.maxNesting;for(;e.pos=e.pos)throw new Error("inline rule didn't increment state.pos");break}if(a){if(e.pos>=r)break}else e.pending+=e.src[e.pos++];}e.pending&&e.pushPending();},Mu.prototype.parse=function(e,t,n,r){const o=new this.State(e,t,n,r);this.tokenize(o);const i=this.ruler2.getRules(""),a=i.length;for(let s=0;s=3&&":"===e[t-3]||t>=3&&"/"===e[t-3]?0:r.match(n.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,n){const r=e.slice(t);return n.re.mailto||(n.re.mailto=new RegExp("^"+n.re.src_email_name+"@"+n.re.src_host_strict,"i")),n.re.mailto.test(r)?r.match(n.re.mailto)[0].length:0}}},Ru="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");function Pu(e){const t=e.re=function(e){const t={};e=e||{},t.src_Any=Pc.source,t.src_Cc=zc.source,t.src_Z=Fc.source,t.src_P=Bc.source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");const n="[><|]";return t.src_pseudo_letter="(?:(?![><|]|"+t.src_ZPCc+")"+t.src_Any+")",t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/\\[\\]()]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|[><|]|"+t.src_ZPCc+")(?!"+(e["---"]?"-(?!--)|":"-|")+"_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|"+n+"|[()[\\]{}.,\"'?!\\-;]).|\\[(?:(?!"+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+'|["]).)+\\"|\\\'(?:(?!'+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!"+t.src_ZCc+"|[.]|$)|"+(e["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+",(?!"+t.src_ZCc+"|$)|;(?!"+t.src_ZCc+"|$)|\\!+(?!"+t.src_ZCc+"|[!]|$)|\\?(?!"+t.src_ZCc+"|[?]|$))+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy='(^|[><|]|"|\\(|'+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`||]|"+t.src_ZPCc+"))((?![$+<=>^`||])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}(e.__opts__),n=e.__tlds__.slice();function r(e){return e.replace("%TLDS%",t.src_tlds)}e.onCompile(),e.__tlds_replaced__||n.push("a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]"),n.push(t.src_xn),t.src_tlds=n.join("|"),t.email_fuzzy=RegExp(r(t.tpl_email_fuzzy),"i"),t.link_fuzzy=RegExp(r(t.tpl_link_fuzzy),"i"),t.link_no_ip_fuzzy=RegExp(r(t.tpl_link_no_ip_fuzzy),"i"),t.host_fuzzy_test=RegExp(r(t.tpl_host_fuzzy_test),"i");const o=[];function i(e,t){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+t)}e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){const n=e.__schemas__[t];if(null===n)return;const r={validate:null,link:null};if(e.__compiled__[t]=r,"[object Object]"===Iu(n))return !function(e){return "[object RegExp]"===Iu(e)}(n.validate)?Lu(n.validate)?r.validate=n.validate:i(t,n):r.validate=function(e){return function(t,n){const r=t.slice(n);return e.test(r)?r.match(e)[0].length:0}}(n.validate),void(Lu(n.normalize)?r.normalize=n.normalize:n.normalize?i(t,n):r.normalize=function(e,t){t.normalize(e);});!function(e){return "[object String]"===Iu(e)}(n)?i(t,n):o.push(t);}),o.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize);}),e.__compiled__[""]={validate:null,normalize:function(e,t){t.normalize(e);}};const a=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(Nu).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+a+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><|]|"+t.src_ZPCc+"))("+a+")","ig"),e.re.schema_at_start=RegExp("^"+e.re.schema_search.source,"i"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),function(e){e.__index__=-1,e.__text_cache__="";}(e);}function zu(e,t){const n=e.__index__,r=e.__last_index__,o=e.__text_cache__.slice(n,r);this.schema=e.__schema__.toLowerCase(),this.index=n+t,this.lastIndex=r+t,this.raw=o,this.text=o,this.url=o;}function Bu(e,t){const n=new zu(e,t);return e.__compiled__[n.schema].normalize(n,e),n}function Ou(e,t){if(!(this instanceof Ou))return new Ou(e,t);var n;t||(n=e,Object.keys(n||{}).reduce(function(e,t){return e||Du.hasOwnProperty(t)},false)&&(t=e,e={})),this.__opts__=_u({},Du,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=_u({},qu,e),this.__compiled__={},this.__tlds__=Ru,this.__tlds_replaced__=false,this.re={},Pu(this);}Ou.prototype.add=function(e,t){return this.__schemas__[e]=t,Pu(this),this},Ou.prototype.set=function(e){return this.__opts__=_u(this.__opts__,e),this},Ou.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return false;let t,n,r,o,i,a,s,l,c;if(this.re.schema_test.test(e))for(s=this.re.schema_search,s.lastIndex=0;null!==(t=s.exec(e));)if(o=this.testSchemaAt(e,t[2],s.lastIndex),o){this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+o;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(l=e.search(this.re.host_fuzzy_test),l>=0&&(this.__index__<0||l=0&&null!==(r=e.match(this.re.email_fuzzy))&&(i=r.index+r[1].length,a=r.index+r[0].length,(this.__index__<0||ithis.__last_index__)&&(this.__schema__="mailto:",this.__index__=i,this.__last_index__=a))),this.__index__>=0},Ou.prototype.pretest=function(e){return this.re.pretest.test(e)},Ou.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},Ou.prototype.match=function(e){const t=[];let n=0;this.__index__>=0&&this.__text_cache__===e&&(t.push(Bu(this,n)),n=this.__last_index__);let r=n?e.slice(n):e;for(;this.test(r);)t.push(Bu(this,n)),r=r.slice(this.__last_index__),n+=this.__last_index__;return t.length?t:null},Ou.prototype.matchAtStart=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return null;const t=this.re.schema_at_start.exec(e);if(!t)return null;const n=this.testSchemaAt(e,t[2],t[0].length);return n?(this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+n,Bu(this,0)):null},Ou.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,n){return e!==n[t-1]}).reverse(),Pu(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=true,Pu(this),this)},Ou.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url);},Ou.prototype.onCompile=function(){};const Fu=2147483647,$u=36,Uu=/^xn--/,ju=/[^\0-\x7F]/,Hu=/[\x2E\u3002\uFF0E\uFF61]/g,Wu={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},Gu=Math.floor,Qu=String.fromCharCode;function Vu(e){throw new RangeError(Wu[e])}function Ku(e,t){const n=e.split("@");let r="";n.length>1&&(r=n[0]+"@",e=n[1]);const o=function(e,t){const n=[];let r=e.length;for(;r--;)n[r]=t(e[r]);return n}((e=e.replace(Hu,".")).split("."),t).join(".");return r+o}function Zu(e){const t=[];let n=0;const r=e.length;for(;n=55296&&o<=56319&&n=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:$u},Ju=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},Xu=function(e,t,n){let r=0;for(e=n?Gu(e/700):e>>1,e+=Gu(e/t);e>455;r+=$u)e=Gu(e/35);return Gu(r+36*e/(e+38))},eh=function(e){const t=[],n=e.length;let r=0,o=128,i=72,a=e.lastIndexOf("-");a<0&&(a=0);for(let s=0;s=128&&Vu("not-basic"),t.push(e.charCodeAt(s));for(let s=a>0?a+1:0;s=n&&Vu("invalid-input");const a=Yu(e.charCodeAt(s++));a>=$u&&Vu("invalid-input"),a>Gu((Fu-r)/t)&&Vu("overflow"),r+=a*t;const l=o<=i?1:o>=i+26?26:o-i;if(aGu(Fu/c)&&Vu("overflow"),t*=c;}const l=t.length+1;i=Xu(r-a,l,0==a),Gu(r/l)>Fu-o&&Vu("overflow"),o+=Gu(r/l),r%=l,t.splice(r++,0,o);}return String.fromCodePoint(...t)},th=function(e){const t=[],n=(e=Zu(e)).length;let r=128,o=0,i=72;for(const l of e)l<128&&t.push(Qu(l));const a=t.length;let s=a;for(a&&t.push("-");s=r&&tGu((Fu-o)/l)&&Vu("overflow"),o+=(n-r)*l,r=n;for(const c of e)if(cFu&&Vu("overflow"),c===r){let e=o;for(let n=$u;;n+=$u){const r=n<=i?1:n>=i+26?26:n-i;if(e=0))try{t.hostname=nh(t.hostname);}catch(n){}return wc(xc(t))}function dh(e){const t=qc(e,true);if(t.hostname&&(!t.protocol||lh.indexOf(t.protocol)>=0))try{t.hostname=rh(t.hostname);}catch(n){}return yc(xc(t),yc.defaultChars+"%")}function uh(e,t){if(!(this instanceof uh))return new uh(e,t);t||cd(e)||(t=e||{},e="default"),this.inline=new Mu,this.block=new hu,this.core=new eu,this.renderer=new qd,this.linkify=new Ou,this.validateLink=sh,this.normalizeLink=ch,this.normalizeLinkText=dh,this.utils=Ld,this.helpers=ud({},Nd),this.options={},this.configure(e),t&&this.set(t);}uh.prototype.set=function(e){return ud(this.options,e),this},uh.prototype.configure=function(e){const t=this;if(cd(e)){const t=e;if(!(e=oh[t]))throw new Error('Wrong `markdown-it` preset "'+t+'", check name')}if(!e)throw new Error("Wrong `markdown-it` preset, can't be empty");return e.options&&t.set(e.options),e.components&&Object.keys(e.components).forEach(function(n){e.components[n].rules&&t[n].ruler.enableOnly(e.components[n].rules),e.components[n].rules2&&t[n].ruler2.enableOnly(e.components[n].rules2);}),this},uh.prototype.enable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.enable(e,true));},this),n=n.concat(this.inline.ruler2.enable(e,true));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+r);return this},uh.prototype.disable=function(e,t){let n=[];Array.isArray(e)||(e=[e]),["core","block","inline"].forEach(function(t){n=n.concat(this[t].ruler.disable(e,true));},this),n=n.concat(this.inline.ruler2.disable(e,true));const r=e.filter(function(e){return n.indexOf(e)<0});if(r.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+r);return this},uh.prototype.use=function(e){const t=[this].concat(Array.prototype.slice.call(arguments,1));return e.apply(e,t),this},uh.prototype.parse=function(e,t){if("string"!=typeof e)throw new Error("Input data should be a String");const n=new this.core.State(e,this,t);return this.core.process(n),n.tokens},uh.prototype.render=function(e,t){return t=t||{},this.renderer.render(this.parse(e,t),this.options,t)},uh.prototype.parseInline=function(e,t){const n=new this.core.State(e,this,t);return n.inlineMode=true,this.core.process(n),n.tokens},uh.prototype.renderInline=function(e,t){return t=t||{},this.renderer.render(this.parseInline(e,t),this.options,t)};var hh=false,gh={false:"push",true:"unshift",after:"push",before:"unshift"},ph={isPermalinkSymbol:true};function mh(e,t,n,r){var o;if(!hh){var i="Using deprecated markdown-it-anchor permalink option, see https://github.com/valeriangalliat/markdown-it-anchor#permalinks";"object"==typeof process&&process&&process.emitWarning?process.emitWarning(i):console.warn(i),hh=true;}var a=[Object.assign(new n.Token("link_open","a",1),{attrs:[].concat(t.permalinkClass?[["class",t.permalinkClass]]:[],[["href",t.permalinkHref(e,n)]],Object.entries(t.permalinkAttrs(e,n)))}),Object.assign(new n.Token("html_block","",0),{content:t.permalinkSymbol,meta:ph}),new n.Token("link_close","a",-1)];t.permalinkSpace&&n.tokens[r+1].children[gh[t.permalinkBefore]](Object.assign(new n.Token("text","",0),{content:" "})),(o=n.tokens[r+1].children)[gh[t.permalinkBefore]].apply(o,a);}function fh(e){return "#"+e}function bh(e){return {}}var yh={class:"header-anchor",symbol:"#",renderHref:fh,renderAttrs:bh};function vh(e){function t(n){return n=Object.assign({},t.defaults,n),function(t,r,o,i){return e(t,n,r,o,i)}}return t.defaults=Object.assign({},yh),t.renderPermalinkImpl=e,t}function wh(e){var t=[],n=e.filter(function(e){if("class"!==e[0])return true;t.push(e[1]);});return t.length>0&&n.unshift(["class",t.join(" ")]),n}var xh=vh(function(e,t,n,r,o){var i,a=[Object.assign(new r.Token("link_open","a",1),{attrs:wh([].concat(t.class?[["class",t.class]]:[],[["href",t.renderHref(e,r)]],t.ariaHidden?[["aria-hidden","true"]]:[],Object.entries(t.renderAttrs(e,r))))}),Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:ph}),new r.Token("link_close","a",-1)];if(t.space){var s="string"==typeof t.space?t.space:" ";r.tokens[o+1].children[gh[t.placement]](Object.assign(new r.Token("string"==typeof t.space?"html_inline":"text","",0),{content:s}));}(i=r.tokens[o+1].children)[gh[t.placement]].apply(i,a);});Object.assign(xh.defaults,{space:true,placement:"after",ariaHidden:false});var kh=vh(xh.renderPermalinkImpl);kh.defaults=Object.assign({},xh.defaults,{ariaHidden:true});var Sh=vh(function(e,t,n,r,o){var i=[Object.assign(new r.Token("link_open","a",1),{attrs:wh([].concat(t.class?[["class",t.class]]:[],[["href",t.renderHref(e,r)]],Object.entries(t.renderAttrs(e,r))))})].concat(t.safariReaderFix?[new r.Token("span_open","span",1)]:[],r.tokens[o+1].children,t.safariReaderFix?[new r.Token("span_close","span",-1)]:[],[new r.Token("link_close","a",-1)]);r.tokens[o+1]=Object.assign(new r.Token("inline","",0),{children:i});});Object.assign(Sh.defaults,{safariReaderFix:false});var Ch=vh(function(e,t,n,r,o){var i;if(!["visually-hidden","aria-label","aria-describedby","aria-labelledby"].includes(t.style))throw new Error("`permalink.linkAfterHeader` called with unknown style option `"+t.style+"`");if(!["aria-describedby","aria-labelledby"].includes(t.style)&&!t.assistiveText)throw new Error("`permalink.linkAfterHeader` called without the `assistiveText` option in `"+t.style+"` style");if("visually-hidden"===t.style&&!t.visuallyHiddenClass)throw new Error("`permalink.linkAfterHeader` called without the `visuallyHiddenClass` option in `visually-hidden` style");var a=r.tokens[o+1].children.filter(function(e){return "text"===e.type||"code_inline"===e.type}).reduce(function(e,t){return e+t.content},""),s=[],l=[];if(t.class&&l.push(["class",t.class]),l.push(["href",t.renderHref(e,r)]),l.push.apply(l,Object.entries(t.renderAttrs(e,r))),"visually-hidden"===t.style){if(s.push(Object.assign(new r.Token("span_open","span",1),{attrs:[["class",t.visuallyHiddenClass]]}),Object.assign(new r.Token("text","",0),{content:t.assistiveText(a)}),new r.Token("span_close","span",-1)),t.space){var c="string"==typeof t.space?t.space:" ";s[gh[t.placement]](Object.assign(new r.Token("string"==typeof t.space?"html_inline":"text","",0),{content:c}));}s[gh[t.placement]](Object.assign(new r.Token("span_open","span",1),{attrs:[["aria-hidden","true"]]}),Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:ph}),new r.Token("span_close","span",-1));}else s.push(Object.assign(new r.Token("html_inline","",0),{content:t.symbol,meta:ph}));"aria-label"===t.style?l.push(["aria-label",t.assistiveText(a)]):["aria-describedby","aria-labelledby"].includes(t.style)&&l.push([t.style,e]);var d=[Object.assign(new r.Token("link_open","a",1),{attrs:wh(l)})].concat(s,[new r.Token("link_close","a",-1)]);(i=r.tokens).splice.apply(i,[o+3,0].concat(d)),t.wrapper&&(r.tokens.splice(o,0,Object.assign(new r.Token("html_block","",0),{content:t.wrapper[0]+"\n"})),r.tokens.splice(o+3+d.length+1,0,Object.assign(new r.Token("html_block","",0),{content:t.wrapper[1]+"\n"})));});function Ah(e,t,n,r){var o=e,i=r;if(n&&Object.prototype.hasOwnProperty.call(t,o))throw new Error("User defined `id` attribute `"+e+"` is not unique. Please fix it in your Markdown to continue.");for(;Object.prototype.hasOwnProperty.call(t,o);)o=e+"-"+i,i+=1;return t[o]=true,o}function Eh(e,t){t=Object.assign({},Eh.defaults,t),e.core.ruler.push("anchor",function(e){for(var n,r={},o=e.tokens,i=Array.isArray(t.level)?(n=t.level,function(e){return n.includes(e)}):function(e){return function(t){return t>=e}}(t.level),a=0;a=s))&&(u=e.bMarks[f]+e.tShift[f],h=e.eMarks[f],!(u=4)){for(c=u+1;c<=h&&r[(c-u)%i]===e.src[c];c++);if(!(Math.floor((c-u)/i)(e.enabled.indexOf(r)>=0&&(n[r]=t[r]),n),{}));const n=Object.keys(e.shortcuts).reduce((n,r)=>t[r]?Array.isArray(e.shortcuts[r])?(e.shortcuts[r].forEach(e=>{n[e]=r;}),n):(n[e.shortcuts[r]]=r,n):n,{}),r=Object.keys(t);let o;o=0===r.length?"^$":r.map(e=>`:${e}:`).concat(Object.keys(n)).sort().reverse().map(e=>e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")).join("|");const i=RegExp(o),a=RegExp(o,"g");return {defs:t,shortcuts:n,scanRE:i,replaceRE:a}}(e.utils.assign({},{defs:{},shortcuts:{},enabled:[]},t||{}));e.renderer.rules.emoji=Mh,e.core.ruler.after("linkify","emoji",function(e,t,n,r,o){const i=e.utils.arrayReplaceAt,a=e.utils.lib.ucmicro,s=e.utils.has,l=new RegExp([a.Z.source,a.P.source,a.Cc.source].join("|"));function c(e,r,i){let a=0;const c=[];if(e.replace(o,function(r,o,d){let u;if(s(n,r)){if(u=n[r],o>0&&!l.test(d[o-1]))return;if(o+r.lengtha){const t=new i("text","",0);t.content=e.slice(a,o),c.push(t);}const h=new i("emoji","",0);h.markup=u,h.content=t[u],c.push(h),a=o+r.length;}),a=0;l--)t=s[l],"link_open"!==t.type&&"link_close"!==t.type||"auto"===t.info&&(o-=t.nesting),"text"===t.type&&0===o&&r.test(t.content)&&(n[a].children=s=i(s,l,c(t.content,t.level,e.Token)));}}}(e,n.defs,n.shortcuts,n.scanRE,n.replaceRE));}Object.assign(Ch.defaults,{style:"visually-hidden",space:true,placement:"after",wrapper:null}),Eh.permalink={__proto__:null,legacy:mh,renderHref:fh,renderAttrs:bh,makePermalink:vh,linkInsideHeader:xh,ariaHidden:kh,headerLink:Sh,linkAfterHeader:Ch},Eh.defaults={level:1,slugify:function(e){return encodeURIComponent(String(e).trim().toLowerCase().replace(/\s+/g,"-"))},uniqueSlugStartIndex:1,tabIndex:"-1",getTokensText:function(e){return e.filter(function(e){return ["text","code_inline"].includes(e.type)}).map(function(e){return e.content}).join("")},permalink:false,renderPermalink:mh,permalinkClass:kh.defaults.class,permalinkSpace:kh.defaults.space,permalinkSymbol:"¶",permalinkBefore:"before"===kh.defaults.placement,permalinkHref:kh.defaults.renderHref,permalinkAttrs:kh.defaults.renderAttrs},Eh.default=Eh;const Ih={angry:[">:(",">:-("],blush:[':")',':-")'],broken_heart:["=0;r--)if(e[r].level===n)return r;return -1}function i(e,t){return "inline"===e[t].type&&function(e){return "paragraph_open"===e.type}(e[t-1])&&function(e){return "list_item_open"===e.type}(e[t-2])&&function(e){return 0===e.content.indexOf("[ ] ")||0===e.content.indexOf("[x] ")||0===e.content.indexOf("[X] ")}(e[t])}function a(r,o){if(r.children.unshift(function(t,n){var r=new n("html_inline","",0),o=e?' disabled="" ':"";0===t.content.indexOf("[ ] ")?r.content='':0!==t.content.indexOf("[x] ")&&0!==t.content.indexOf("[X] ")||(r.content='');return r}(r,o)),r.children[1].content=r.children[1].content.slice(3),r.content=r.content.slice(3),t)if(n){r.children.pop();var i="task-item-"+Math.ceil(1e7*Math.random()-1e3);r.children[0].content=r.children[0].content.slice(0,-1)+' id="'+i+'">',r.children.push(function(e,t,n){var r=new n("html_inline","",0);return r.content='",r.attrs=[{for:t}],r}(r.content,i,o));}else r.children.unshift(function(e){var t=new e("html_inline","",0);return t.content="",t}(o));}return qh=function(s,l){l&&(e=!l.enabled,t=!!l.label,n=!!l.labelAfter),s.core.ruler.after("inline","github-task-lists",function(t){for(var n=t.tokens,s=2;se.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Oh=()=>{try{const e=GM_getResourceText("ophelKatexCss");return e?(e=>e.replace(/url\((['"]?)(?!data:|https?:|\/)([^)'"]+)\1\)/g,(e,t,n)=>{const r=String(n).replace(/^\.?\//,"");return `url(${t}${r.startsWith("fonts/")?`${zh}/${r.slice(6)}`:`${zh}/${r}`}${t})`}))(e):""}catch(e){return console.warn("[Ophel] Failed to load KaTeX CSS resource:",e),""}},Fh=(e,{displayMode:t})=>{const n=e.replace(/\r\n?/g,"\n").trim(),r=(()=>{const e=globalThis.katex;return e&&"function"==typeof e.renderToString?e:null})();if(!r){const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Bh(n)}">${Bh(e)}`}try{const e=r.renderToString(n,{displayMode:t,output:"htmlAndMathml",throwOnError:!1,strict:"ignore",trust:!1}),o=t?"div":"span";return `<${o} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Bh(n)}">${e}`}catch{const e=t?`$$\n${n}\n$$`:`$${n}$`,r=t?"div":"span";return `<${r} class="${t?"math-block gh-rendered-math":"math-inline gh-rendered-math"}" data-math="${Bh(n)}">${Bh(e)}`}};Ml.registerLanguage("javascript",Yl),Ml.registerLanguage("js",Yl),Ml.registerLanguage("typescript",ac),Ml.registerLanguage("ts",ac),Ml.registerLanguage("python",function(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],o={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},i={className:"meta",begin:/^(>>>|\.\.\.) /},a={className:"subst",begin:/\{/,end:/\}/,keywords:o,illegal:/#/},s={begin:/\{\{/,relevance:0},l={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,i,s,a]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,i,s,a]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,a]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,a]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},c="[0-9](_?[0-9])*",d=`(\\b(${c}))?\\.(${c})|\\b(${c})\\.`,u=`\\b|${r.join("|")}`,h={className:"number",relevance:0,variants:[{begin:`(\\b(${c})|(${d}))[eE][+-]?(${c})[jJ]?(?=${u})`},{begin:`(${d})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${u})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${u})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${u})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${u})`},{begin:`\\b(${c})[jJ](?=${u})`}]},g={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:o,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:true}]},p={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:true},{begin:/\(/,end:/\)/,excludeBegin:true,excludeEnd:true,keywords:o,contains:["self",i,h,l,e.HASH_COMMENT_MODE]}]};return a.contains=[l,h,i],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:true,keywords:o,illegal:/(<\/|\?)|=>/,contains:[i,h,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},l,g,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[p]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[h,p,l]}]}}),Ml.registerLanguage("css",Rl),Ml.registerLanguage("html",sc),Ml.registerLanguage("xml",sc),Ml.registerLanguage("vue",sc),Ml.registerLanguage("json",function(e){const t=["true","false","null"],n={scope:"literal",beginKeywords:t.join(" ")};return {name:"JSON",aliases:["jsonc"],keywords:{literal:t},contains:[{className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},{match:/[{}[\],:]/,className:"punctuation",relevance:0},e.QUOTE_STRING_MODE,n,e.C_NUMBER_MODE,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}),Ml.registerLanguage("java",function(e){const t=e.regex,n="[À-ʸa-zA-Z_$][À-ʸa-zA-Z_$0-9]*",r=n+Ul("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),o={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},i={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},a={className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:true};return {name:"Java",aliases:["jsp"],keywords:o,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{ // eat up @'s in emails to prevent them to be recognized as doctags begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:o,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:o,relevance:0,contains:[i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,$l,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},$l,i]}}),Ml.registerLanguage("go",function(e){const t={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return {name:"Go",aliases:["golang"],keywords:t,illegal:""},i]}}),Ml.registerLanguage("bash",_l),Ml.registerLanguage("shell",_l),Ml.registerLanguage("sh",_l),Ml.registerLanguage("sql",function(e){const t=e.regex,n=e.COMMENT("--","$"),r=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],o=r,i=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year","add","asc","collation","desc","final","first","last","view"].filter(e=>!r.includes(e)),a={match:t.concat(/\b/,t.either(...o),/\s*\(/),relevance:0,keywords:{built_in:o}};function s(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,"\\s+"))),/\b/)}const l={scope:"keyword",match:s(["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"]),relevance:0};return {name:"SQL",case_insensitive:true,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:function(e,{exceptions:t,when:n}={}){const r=n;return t=t||[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}(i,{when:e=>e.length<3}),literal:["true","false","unknown"],type:["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],built_in:["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"]},contains:[{scope:"type",match:s(["double precision","large object","with timezone","without timezone"])},l,a,{scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},{scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},{begin:/"/,end:/"/,contains:[{match:/""/}]},e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,{scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0}]}}),Ml.registerLanguage("yaml",lc),Ml.registerLanguage("yml",lc),Ml.registerLanguage("diff",Pl),Ml.registerLanguage("git",Pl),Ml.registerLanguage("dockerfile",zl),Ml.registerLanguage("docker",zl);const $h=(e=false)=>{const t=new uh({html:false,breaks:true,linkify:true,highlight:(e,t)=>{if(t&&Ml.getLanguage(t))try{return Ml.highlight(e,{language:t}).value}catch{}try{return Ml.highlightAuto(e).value}catch{return ""}}});return t.use(Ph,{enabled:true,label:false}),t.use(Nh),t.use(Dh),t.use(Eh,{permalink:false}),t.use(Th,"info",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),t.use(Th,"warning",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),t.use(Th,"danger",{render:(e,t)=>1===e[t].nesting?'
':"
\n"}),e&&t.use(fc,{delimiters:"all",allowInlineWithSpace:false,render:(e,t)=>Fh(e,{displayMode:t})}),t},Uh=$h(),jh=$h(true),Hh=(e,t=true,n={})=>{if(!e)return "";let r=(n.enableMath?jh:Uh).render(e);return t&&(r=r.replace(/\{\{([^\s{}]+)\}\}/g,'{{$1}}')),r=r.replace(/
/g,"
"),r},Wh=()=>Oh(),Gh="delete_ui_failed",Qh="delete_batch_aborted_after_ui_failure",Vh="delete_api_org_missing",Kh="delete_api_request_failed",Zh="delete_api_not_found_but_visible",Yh=["delete","remove","删除","刪除","削除","삭제","supprimer","eliminar","elimina","löschen","excluir","hapus","हट","मिट"],Jh=["cancel","取消","annuler","abbrechen","annulla","キャンセル","취소","batal","cancelar"],Xh=/^[a-f0-9-]{36}$/i,eg=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],tg=[/((^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$))/,/\\\([^\n]+?\\\)/],ng="document",rg="#wiggle-file-content",og=".standard-markdown, .progressive-markdown",ig=".artifact-block-cell",ag='[data-testid="file-thumbnail"]',sg="button[aria-expanded]",lg='span[role="status"][aria-live="polite"]';function cg(){try{const e=localStorage.getItem("LSS-userThemeMode");if(e){const t=JSON.parse(e);if("string"==typeof t.tabId&&t.tabId.trim())return t.tabId}}catch{}return crypto.randomUUID()}function dg(e){const t=e.trim();if(!t)return false;const n=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(t);return /^#{1,6}\s/m.test(t)||/\*\*[^*]+\*\*/.test(t)||new RegExp("(?e.test(n))||tg.some(e=>e.test(n))}const ug=/\/a\/chat\/s\/([a-z0-9-]+)/i,hg=/\/share\/([a-z0-9-]+)/i,gg="__appKit_@deepseek/chat_themePreference",pg='a[href*="/a/chat/s/"]',mg=".ds-message",fg=`${mg}:has(.ds-markdown)`,bg=".ds-message:not(:has(.ds-markdown))",yg=".ds-think-content",vg=[`${bg} > .gh-inline-bookmark + div`,`${bg} > div:not(.gh-user-query-raw):not(.gh-user-query-markdown):not(.ds-focus-ring)`,`${bg} > div.gh-user-query-markdown`].join(", "),wg="https://chat.deepseek.com/",xg="gh.deepseek.delete.refresh",kg="data-gh-deepseek-export-root",Sg="data-gh-deepseek-export-role",Cg="user",Ag="assistant",Eg=`[${kg}="1"] [${Sg}="${Cg}"]`,Tg=`[${kg}="1"] [${Sg}="${Ag}"]`,Mg="M2 4.88",_g="M8.3125 0.981587C8.66767 1.0545 8.97902 1.20558 9.2627 1.43374C9.48724 1.61438 9.73029 1.85933 9.97949 2.10854L14.707 6.83608L13.293 8.25014L9 3.95717V15.0431H7V3.95717L2.70703 8.25014L1.29297 6.83608L6.02051 2.10854C6.26971 1.85933 6.51277 1.61438 6.7373 1.43374C6.97662 1.24126 7.28445 1.04542 7.6875 0.981587C7.8973 0.94841 8.1031 0.956564 8.3125 0.981587Z",Ig="delete_api_missing_auth_token",Lg="delete_api_request_failed",Ng="delete_api_invalid_response",Dg="delete_api_business_failed";const qg=/^(?:(?:\/code)?\/chat|\/thread)\/([^/?#]+)/,Rg="#flow_chat_sidebar",Pg=`${Rg} [data-history-container="true"]`,zg=`${Rg} a[id^="conversation_"][href*="/chat/"]`,Bg='[class*="overallTitle-"], [class*="title-"]',Og=`${Rg} > div:nth-child(2)`,Fg='[class*="v_list_scroller"]',$g=".v_list_row",Ug='[data-target-id="message-box-target-id"]',jg="[data-message-id].justify-end",Hg=".whitespace-pre-wrap.wrap-anywhere:not(.gh-user-query-markdown)",Wg=`${jg} ${Hg}`,Gg="[data-message-id]:not(.justify-end)",Qg=[".flow-markdown-body",".md-box-root"],Vg=Qg.join(", "),Kg=Qg.map(e=>`${Gg} ${e}`).join(", "),Zg='[data-plugin-identifier="block_type:2074"]',Yg='[class*="image-wrapper"], [class*="image-box-grid-item"], [class*="image-box-grid"]',Jg=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Xg="delete_ui_failed",ep="delete_batch_aborted_after_ui_failure";const tp=function(){const e=globalThis.ReactDOM;if(!e||"function"!=typeof e.createPortal)throw new Error("[Ophel] ReactDOM CDN runtime is missing");return e}(),np=tp.createPortal;tp.flushSync,tp.unstable_batchedUpdates,tp.version;const rp="ophel-global-tooltip-styles",op=8,ip=10;!function(){if("undefined"==typeof window)return;const e=window;"boolean"!=typeof e.__ophelTooltipSuppressFocusFromWindowRestoration__&&(e.__ophelTooltipSuppressFocusFromWindowRestoration__=false),e.__ophelTooltipWindowFocusListenerRegistered__||(e.__ophelTooltipWindowFocusListenerRegistered__=true,window.addEventListener("focus",()=>{window.__ophelTooltipSuppressFocusFromWindowRestoration__=true,requestAnimationFrame(()=>{window.__ophelTooltipSuppressFocusFromWindowRestoration__=false;});}));}();function ap(e){if(!e||"undefined"==typeof document)return null;const t=e.getRootNode?.();return t instanceof ShadowRoot?t:document.body}function sp(e){if("undefined"==typeof document||!e||e instanceof ShadowRoot)return;if(document.getElementById(rp))return;const t=document.createElement("style");t.id=rp,t.textContent="\n .ophel-tooltip {\n background-color: rgba(30, 30, 35, 0.95);\n color: #ffffff;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n line-height: 1.5;\n z-index: 2147483647;\n pointer-events: none;\n white-space: pre-wrap;\n word-wrap: break-word;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);\n border: 1px solid rgba(255, 255, 255, 0.1);\n backdrop-filter: blur(4px);\n animation: tooltip-fade-in 0.15s ease-out;\n }\n\n @keyframes tooltip-fade-in {\n from {\n opacity: 0;\n transform: scale(0.95);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n }\n",document.head.appendChild(t);}function lp(e,t,n={}){const{preferredPlacement:r="bottom",gap:o=op,viewportPadding:i=ip}=n,a="top"===r?e.top-t.height-o:e.bottom+o,s="top"===r?e.bottom+o:e.top-t.height-o;let l=a;(lwindow.innerHeight-i)&&(l=s),lwindow.innerHeight-i&&(l=Math.max(i,window.innerHeight-t.height-i));let c=e.left+e.width/2-t.width/2;return cwindow.innerWidth-i&&(c=window.innerWidth-t.width-i),{top:l,left:c}}const cp=new class{tooltipEl=null;activeTrigger=null;activeContainer=null;positionOptions={};handleWindowChange=()=>{this.positionTooltip();};handleWindowBlur=()=>{this.hide();};handleVisibilityChange=()=>{document.hidden&&this.hide();};show(e,t,n=260,r={}){if(!t||!e.isConnected)return void this.hide(e);const o=ap(e);if(!o)return;sp(o),this.activeTrigger&&this.activeTrigger!==e&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=e,this.activeContainer=o,this.positionOptions=r;const i=this.ensureTooltipElement(o);i.textContent=t,i.style.maxWidth="number"==typeof n?`${n}px`:n,i.style.opacity="0",e.setAttribute("aria-describedby",i.id),this.attachGlobalListeners(),this.positionTooltip();}hide(e){e&&this.activeTrigger&&e!==this.activeTrigger||(this.activeTrigger&&this.activeTrigger.removeAttribute("aria-describedby"),this.activeTrigger=null,this.positionOptions={},this.detachGlobalListeners(),this.tooltipEl?.parentNode&&this.tooltipEl.parentNode.removeChild(this.tooltipEl));}ensureTooltipElement(e){return this.tooltipEl||(this.tooltipEl=document.createElement("div"),this.tooltipEl.className="ophel-tooltip",this.tooltipEl.id=`ophel-tooltip-${Math.random().toString(36).slice(2,9)}`,this.tooltipEl.setAttribute("role","tooltip"),this.tooltipEl.style.position="fixed",this.tooltipEl.style.top="0",this.tooltipEl.style.left="0",this.tooltipEl.style.pointerEvents="none",this.tooltipEl.style.zIndex="2147483647"),this.tooltipEl.parentNode===e&&this.tooltipEl.isConnected||e.appendChild(this.tooltipEl),this.tooltipEl}positionTooltip(){if(!this.tooltipEl||!this.activeTrigger||!this.tooltipEl.isConnected)return;const e=this.activeTrigger.getBoundingClientRect(),t=this.tooltipEl.getBoundingClientRect(),{top:n,left:r}=lp(e,t,this.positionOptions);this.tooltipEl.style.top=`${n}px`,this.tooltipEl.style.left=`${r}px`,this.tooltipEl.style.opacity="1";}attachGlobalListeners(){window.addEventListener("scroll",this.handleWindowChange,true),window.addEventListener("resize",this.handleWindowChange),window.addEventListener("blur",this.handleWindowBlur),document.addEventListener("visibilitychange",this.handleVisibilityChange);}detachGlobalListeners(){window.removeEventListener("scroll",this.handleWindowChange,true),window.removeEventListener("resize",this.handleWindowChange),window.removeEventListener("blur",this.handleWindowBlur),document.removeEventListener("visibilitychange",this.handleVisibilityChange);}};function dp(e,t){let n=null;const r=()=>{n&&(clearTimeout(n),n=null);},o=()=>{r(),cp.hide(e);},i=()=>{var o;(r(),"function"==typeof(o=t.disabled)?o():Boolean(o))||(n=setTimeout(()=>{if(!e.isConnected)return;const n=t.getContent();cp.show(e,n,t.maxWidth??260,t);},t.delay??300));};return e.addEventListener("mouseenter",i),e.addEventListener("mouseleave",o),e.addEventListener("focus",i),e.addEventListener("blur",o),e.addEventListener("pointerdown",o),e.addEventListener("click",o),{hide:o,destroy:()=>{e.removeEventListener("mouseenter",i),e.removeEventListener("mouseleave",o),e.removeEventListener("focus",i),e.removeEventListener("blur",o),e.removeEventListener("pointerdown",o),e.removeEventListener("click",o),o();}}}const up=({content:e,children:t,maxWidth:n=260,delay:r=300,className:o="",triggerClassName:i="",triggerStyle:a={},disabled:s=false})=>{const[l,c]=z(false),[d,u]=z({top:0,left:0}),[h,g]=z(false),[p,m]=z(false),[f,b]=z(null),y=P(null),v=P(null),w=P(null),x=P(false),k=A(()=>{x.current=false,w.current&&(clearTimeout(w.current),w.current=null),c(false),g(false),m(false);},[]),S=A(()=>{x.current=true,s||(w.current&&clearTimeout(w.current),m(true),w.current=setTimeout(()=>{w.current=null,m(false),!document.hidden&&x.current&&(c(true),g(true));},r));},[r,s]),C=A(()=>{ true!==window.__ophelTooltipSuppressFocusFromWindowRestoration__&&S();},[S]),E=A(()=>{const e=y.current?.getBoundingClientRect(),t=v.current?.getBoundingClientRect();e&&t&&u(lp(e,t,{preferredPlacement:"bottom"}));},[]);return _(()=>{if(y.current){const e=ap(y.current);b(e),sp(e);}},[]),_(()=>{(l||h)&&y.current&&(E(),h&&g(false));},[e,h,l,E]),_(()=>{if(!l&&!h)return;const e=()=>{E();};return window.addEventListener("scroll",e,true),window.addEventListener("resize",e),()=>{window.removeEventListener("scroll",e,true),window.removeEventListener("resize",e);}},[h,l,E]),_(()=>{if(!p&&!l&&!h)return;const e=()=>{document.hidden&&k();};return window.addEventListener("blur",k),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",k),document.removeEventListener("visibilitychange",e);}},[p,k,h,l]),_(()=>()=>{w.current&&clearTimeout(w.current);},[]),_(()=>{s?k():x.current&&(w.current&&clearTimeout(w.current),m(true),w.current=setTimeout(()=>{w.current=null,m(false),!document.hidden&&x.current&&(c(true),g(true));},r));},[r,s,k]),Le("div",{ref:y,className:`ophel-tooltip-trigger ${o} ${i}`,onMouseEnter:S,onMouseLeave:k,onFocus:C,onBlur:k,style:{display:"inline-flex",...a},children:[t,l&&e&&f&&np( Ie("div",{ref:v,className:"ophel-tooltip",style:{position:"fixed",top:d.top,left:d.left,maxWidth:n,opacity:h?0:1},children:e}),f)]})},hp="http://www.w3.org/2000/svg";function gp(e,t={}){const n=document.createElementNS(hp,e);for(const[r,o]of Object.entries(t))n.setAttribute(r,o);return n}function pp(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=gp("svg",{xmlns:hp,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=gp("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),a=gp("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"});return o.appendChild(i),o.appendChild(a),o}function mp(e,t={}){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=gp("svg",{xmlns:hp,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2.5","stroke-linecap":"round","stroke-linejoin":"round",...r?{class:r}:{}}),i=gp("polyline",{points:"20 6 9 17 4 12"});return o.appendChild(i),o}({...t,color:"#22c55e"})),setTimeout(()=>{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(pp(t));},1500);}function fp(e,t={}){e.querySelectorAll(".gh-code-copy-btn, .gh-table-copy-btn").forEach(e=>{if(!e.querySelector("svg")){for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(pp(t));}});}const bp="CHECK_PERMISSION",yp="CHECK_PERMISSIONS",vp="REQUEST_PERMISSIONS",wp="CLEAR_ALL_DATA",xp="RESTORE_DATA";function kp(e){return chrome.runtime.sendMessage(e)}const Sp="GH_MONITOR_INIT",Cp="GH_MONITOR_START",Ap="GH_MONITOR_COMPLETE",Ep="OPHEL_GEMINI_MYSTUFF_SYNC_REQUEST",Tp="OPHEL_GEMINI_MYSTUFF_CACHE_SYNC",Mp="OPHEL_EXTENSION_UPDATE_AVAILABLE";let _p=null,Ip=null,Lp=false;function Np(){if("undefined"==typeof window)return null;const e=window.trustedTypes;return e?.createPolicy?e:null}function Dp(e){return `ophel-userscript-${e}-${Math.random().toString(36).slice(2,8)}`}function qp(e){if(_p||function(){if(_p)return true;const e=Np();if(!e)return false;try{return _p=e.createPolicy(Dp("html"),{createHTML:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types policy:",t),false}}(),_p)try{return _p.createHTML(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe HTML:",t);}return e}function Rp(e,t){try{const n=qp(t);return e.innerHTML=n,!0}catch(n){return console.warn("[TrustedTypes] Failed to set innerHTML:",n),false}}function Pp(e){if(Ip||function(){if(Ip)return true;const e=Np();if(!e)return false;try{return Ip=e.createPolicy(Dp("script-url"),{createScriptURL:e=>e}),!0}catch(t){return console.warn("[TrustedTypes] Failed to create Trusted Types script URL policy:",t),false}}(),Ip)try{return Ip.createScriptURL(e)}catch(t){console.warn("[TrustedTypes] Failed to create safe script URL:",t);}return e}function zp(e,t){let n=null;const r=t=>{if(!Reflect.set(e,"src",t))throw new Error("Trusted Types prevented script src assignment")};try{return r(Pp(t)),!0}catch(o){n=o;}if(function(){if(Lp)return true;const e=Np();if(!e)return false;try{return e.createPolicy("default",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}),Lp=!0,!0}catch(o){const t=o instanceof Error?o.message:String(o);return /default/i.test(t)&&/already exists/i.test(t)?(Lp=true,true):(console.warn("[TrustedTypes] Failed to create default Trusted Types policy:",o),false)}}())try{return r(t),!0}catch(o){n=o;}return console.warn("[TrustedTypes] Failed to set script src:",n),false}const Bp="delete_ui_failed",Op="delete_ui_exception",Fp="delete_batch_aborted_after_ui_failure",$p=["delete","remove","删除","删掉","supprimer","eliminar","löschen","삭제","削除","移除","excluir","hapus","удал"],Up=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"],jp="data-ophel-export-image-src",Hp=/([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,})/i,Wp=/(google|account|账号|帳號|conta|compte|cuenta|konto|アカウント|계정|учет)/i,Gp=/(unable|cannot|can't|can not|无法|無法|不可).*(view|preview|download|共享|分享|shared|查看|预览|預覽|下载|下載)|shared.*(file|download|preview)|共享对话中的文件|共享對話中的文件/i,Qp=[".attachment-container.generated-images","response-element","generated-image","single-image.generated-image",".image-container.replace-fife-images-at-export","[data-image-attachment-index]"].join(", "),Vp=["user-query img[data-test-id='uploaded-img']","user-query .preview-image"].join(", "),Kp='[data-test-id="uploaded-file"]',Zp="share-landing-page .share-turn-viewer",Yp="message-content .markdown",Jp='share-landing-page immersive-share-landing-page structured-content-container[data-test-id="deep-research-block"]',Xp='share-landing-page structured-content-container[data-test-id="immersive-artifact-content"]',em=Yp,tm="deep-research-confirmation-widget",nm="immersive-panel deep-research-immersive-panel",rm=[`${nm} #extended-response-markdown-content`,`${nm} message-content .markdown`].join(", "),om=['mat-icon[data-mat-icon-name="travel_explore"]','mat-icon[fonticon="travel_explore"]'].join(", "),im=['mat-icon[fonticon="code_blocks"]','mat-icon[data-mat-icon-name="code_blocks"]'].join(", "),am="immersive-panel code-immersive-panel",sm='xap-code-editor[data-test-id="code-editor"]',lm="gh-gemini-deep-research-panel-actions",cm="gh-gemini-deep-research-panel-action",dm="data-ophel-deep-research-panel-actions",um="document",hm=[".cdk-visually-hidden","model-thoughts","immersive-entry-chip","gem-processing-card",'[data-test-id="gem-processing-card"]','[data-test-id="time-estimation-message"]',".time-estimation-message","source-footnote","sources-carousel-inline","sources-carousel",".gh-inline-bookmark",".gh-table-copy-btn","mat-icon","share-button","copy-button","download-generated-image-button",".generated-image-controls",".loader"].join(", "),gm=["img.katex-svg","img.favicon","img.google-icon",'img[data-test-id="favicon"]','img[data-test-id="file-icon"]','img[data-test-id="luminous-file-icon"]','img[src*="faviconV2"]','img[src*="drive-thirdparty.googleusercontent.com/32/type/"]','img[src*="google_logo_icon"]'].join(", "),pm="ophel-gemini-mystuff-active",mm="ophel-gemini-mystuff-style",fm="ophel-mystuff-open-btn",bm="data-ophel-mystuff-open",ym="data-ophel-mystuff-open-suppress",vm=/^https:\/\/lh\d+\.googleusercontent\.com\//i,wm='expandable-section[data-test-id="chats-expandable-section"]',xm='expandable-section[storagekey="chats"]',km=["source-chip","source-card","source-footnote","citation-source","citation-chip","citation-marker","grounding-chip","grounding-source","web-source","[data-source]","[data-source-id]","[data-citation]","[data-citation-id]","[data-ved]","[decode-data-ved]","[cdkoverlayorigin]","[mattooltip]","[data-mdc-tooltip]","mat-icon[fonticon]","mat-icon[data-mat-icon-name]","[fonticon*='link' i]","[data-mat-icon-name*='link' i]","sup a","sup button","sup [role='button']",...["source","sources","citation","citations","reference","references","grounding","footnote","link","fonte","fontes","fuente","fuentes","quelle","quellen","referencia","referencias","referência","referências","riferimento","riferimenti","来源","引用","链接","出典","参照","출처","참조","источник","источники","ссылка","ссылки"].flatMap(e=>[`[aria-label*='${e}' i]`,`[title*='${e}' i]`,`[data-test-id*='${e}' i]`])].join(",");class Sm{constructor(e){this.options=e;}started=false;mediaWatchStop=null;tooltipBindings=new WeakMap;pendingRequests=new Map;recordsByKind={media:new Map,document:new Map};mediaByTimestamp=new Map;mediaByThumbnail=new Map;documentByTimestamp=new Map;documentByTitle=new Map;start(){this.started||(this.started=true,this.injectStyles(),this.mediaWatchStop=os.each(".library-item-card",e=>this.enhanceMediaCard(e),{shadow:true}),document.addEventListener("click",this.handleDocumentClick,true),window.addEventListener("message",this.handleWindowMessage),window.addEventListener("gh-url-change",this.handleRouteChange),this.refreshForCurrentRoute(false),setTimeout(()=>this.refreshForCurrentRoute(false),600),setTimeout(()=>this.refreshForCurrentRoute(false),1500));}handleRouteChange=()=>{this.refreshForCurrentRoute(false);};handleWindowMessage=e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==Tp||t===Tp&&this.handleCachePayload(n);};handleDocumentClick=e=>{if(!this.isMyStuffPath()||e.defaultPrevented||0!==e.button)return;const t=e.target instanceof Element?e.target:null;if(!t)return;const n=t.closest(`[${bm}="1"]`);if(n){const t=n.closest("library-item-card");if(!t)return;return this.preventNativeNavigation(e),this.dismissActionButtonVisualState(n),void this.openHostInNewTab(t,"media",this.preparePendingTab())}if(t.closest("library-item-card"))return;const r=t.closest("library-list-item");r&&(this.preventNativeNavigation(e),this.openHostInNewTab(r,"document",this.preparePendingTab()));};preventNativeNavigation(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();}refreshForCurrentRoute(e){const t=this.isMyStuffPath();document.documentElement.classList.toggle(pm,t),t&&(this.enhanceExistingMediaCards(),this.requestSync(e,this.getKindsForCurrentPath()).catch(()=>{}));}injectStyles(){if(document.getElementById(mm))return;const e=document.createElement("style");e.id=mm,e.textContent=`\n .${pm} library-item-card .library-item-card,\n .${pm} .library-item-card-container {\n position: relative;\n }\n\n .${pm} .${fm} {\n position: absolute;\n top: 4px;\n right: 42px;\n width: 36px;\n height: 36px;\n border: none;\n border-radius: 999px;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n background: rgba(15, 23, 42, 0.45);\n color: #ffffff;\n box-shadow: 0 4px 14px rgba(15, 23, 42, 0.12);\n backdrop-filter: blur(6px);\n cursor: pointer;\n opacity: 0;\n pointer-events: none;\n transform: translateY(-2px);\n transition:\n opacity 0.18s ease,\n transform 0.18s ease,\n background-color 0.18s ease,\n color 0.18s ease;\n z-index: 3;\n }\n\n .${pm} library-item-card:hover .${fm},\n .${pm} library-item-card:focus-within .${fm},\n .${pm} .library-item-card:hover .${fm},\n .${pm} .library-item-card:focus-within .${fm},\n .${pm} .library-item-card-container:hover .${fm},\n .${pm} .library-item-card-container:focus-within .${fm} {\n opacity: 1;\n pointer-events: auto;\n transform: translateY(0);\n }\n\n .${pm} .${fm}:hover {\n background: rgba(15, 23, 42, 0.60);\n color: #ffffff;\n }\n\n .${pm} .${fm}[${ym}="1"] {\n opacity: 0 !important;\n pointer-events: none !important;\n transform: translateY(-2px) !important;\n }\n\n .${pm} .${fm} svg {\n width: 16px;\n height: 16px;\n stroke: currentColor;\n fill: none;\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n }\n\n body.dark-theme .${fm},\n html[dark-theme] .${fm},\n html.dark .${fm} {\n background: rgba(15, 23, 42, 0.45);\n color: #f9fafb;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.32);\n }\n\n body.dark-theme .${fm}:hover,\n html[dark-theme] .${fm}:hover,\n html.dark .${fm}:hover {\n background: rgba(15, 23, 42, 0.60);\n color: #ffffff;\n }\n\n `,document.head.appendChild(e);}enhanceExistingMediaCards(){document.querySelectorAll(".library-item-card").forEach(e=>this.enhanceMediaCard(e));}enhanceMediaCard(e){if(!this.isMyStuffPath())return;const t=e.closest("library-item-card"),n=e.matches(".library-item-card")?e:e.querySelector(".library-item-card");if(!t||!n)return;if(n.querySelector(`[${bm}="1"]`))return;const r=document.createElement("button");r.type="button",r.className=`${fm} ophel-tooltip-trigger`,r.setAttribute(bm,"1"),r.setAttribute("aria-label",this.getOpenInNewTabLabel()),r.appendChild(function(e={}){const{size:t=16,color:n="currentColor",className:r=""}=e,o=gp("svg",{xmlns:hp,width:t.toString(),height:t.toString(),viewBox:"0 0 24 24",fill:"none",stroke:n,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",...r?{class:r}:{}}),i=gp("path",{d:"M14 5h5v5"}),a=gp("path",{d:"M10 14 19 5"}),s=gp("path",{d:"M19 14v4a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h4"});return o.appendChild(i),o.appendChild(a),o.appendChild(s),o}()),n.appendChild(r),this.tooltipBindings.set(r,dp(r,{getContent:()=>this.getOpenInNewTabLabel(),delay:300,maxWidth:260,preferredPlacement:"top"}));}isMyStuffPath(){const e=this.getNormalizedPath();return "/mystuff"===e||"/mystuff/"===e||e.startsWith("/mystuff/")||"/library"===e||"/library/"===e||e.startsWith("/library/")}getKindsForCurrentPath(){const e=this.getNormalizedPath();return e.startsWith("/mystuff/documents")||e.startsWith("/library/documents")?["document"]:["media","document"]}getNormalizedPath(){return window.location.pathname.replace(/^\/u\/\d+/,"")}handleCachePayload(e){if(!e||!Array.isArray(e.items)||!Array.isArray(e.kinds))return;this.replaceRecords(e.kinds,e.items);const t=e.requestId?this.pendingRequests.get(e.requestId):null;t&&e.requestId&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e));}replaceRecords(e,t){for(const n of e)this.recordsByKind[n].clear(),t.filter(e=>e.kind===n).forEach(e=>this.recordsByKind[n].set(this.getRecordKey(e),e));this.rebuildIndexes();}rebuildIndexes(){this.mediaByTimestamp.clear(),this.mediaByThumbnail.clear(),this.documentByTimestamp.clear(),this.documentByTitle.clear(),this.recordsByKind.media.forEach(e=>{this.pushIndex(this.mediaByTimestamp,e.timestamp,e);const t=this.normalizeThumbnailUrl(e.thumbnailUrl);t&&this.pushIndex(this.mediaByThumbnail,t,e);}),this.recordsByKind.document.forEach(e=>{this.pushIndex(this.documentByTimestamp,e.timestamp,e);const t=this.normalizeTitle(e.title);t&&this.pushIndex(this.documentByTitle,t,e);});}pushIndex(e,t,n){if(null==t||""===t||0===t)return;const r=e.get(t)||[];r.push(n),e.set(t,r);}async requestSync(e,t){const n=`ophel-mystuff-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r={requestId:n,force:e,kinds:t},o=new Promise((e,t)=>{const r=setTimeout(()=>{this.pendingRequests.delete(n),t(new Error("mystuff-sync-timeout"));},12e3);this.pendingRequests.set(n,{resolve:e,reject:t,timeoutId:r});});return window.postMessage({type:Ep,payload:r},"*"),o}preparePendingTab(){return "userscript"!==qi.type?null:window.open("about:blank","_blank")}async openHostInNewTab(e,t,n){const r=await this.resolveRecord(e,t);if(!r)return n&&!n.closed&&n.close(),console.warn("[GeminiAdapter][MyStuff] record not found for host",{kind:t,locator:this.extractLocator(e,t)}),void Li(se("geminiMystuffLocateFailed"),2500);const o=this.buildRecordUrl(r);!n||n.closed?qi.openTab(o):n.location.href=o;}async resolveRecord(e,t){const n=this.extractLocator(e,t);let r=this.findRecord(n);if(r)return r;try{await this.requestSync(!0,[t]);}catch(o){console.warn("[GeminiAdapter][MyStuff] sync failed before open",{kind:t,error:o});}return r=this.findRecord(n),r}extractLocator(e,t){const n=e.closest("[jslog]")||e.querySelector("[jslog]"),r=n?.getAttribute("jslog")||"",o=this.extractJslogMeta(r);return {kind:t,status:o?.status,timestamp:o?.timestamp,timestampNano:o?.timestampNano,title:"document"===t?this.extractTitle(e):void 0,thumbnailUrl:"media"===t?this.extractThumbnailUrl(e):void 0}}extractJslogMeta(e){if(!e)return null;const t=Array.from(e.matchAll(/\[(\d+),\[(\d+)(?:,(\d+))?\]\]/g)),n=t[t.length-1];return n?{status:Number(n[1]),timestamp:Number(n[2]),timestampNano:n[3]?Number(n[3]):void 0}:null}extractTitle(e){const t=e.querySelector(".title, .gds-title-m, .text-content .title");return t?.textContent?.trim()||""}extractThumbnailUrl(e){const t=e.querySelector("img");return t instanceof HTMLImageElement?this.normalizeThumbnailUrl(t.currentSrc||t.src||""):""}normalizeTitle(e){return (e||"").trim().replace(/\s+/g," ").toLowerCase()}normalizeThumbnailUrl(e){if(!e)return "";let t=e;try{t=new URL(e,window.location.href).toString();}catch{t=e;}return vm.test(t)?t.replace(/=[^/?#]+$/,""):t}findRecord(e){return "media"===e.kind?this.findMediaRecord(e):this.findDocumentRecord(e)}findMediaRecord(e){const t=new Map,n=this.normalizeThumbnailUrl(e.thumbnailUrl);if(n)for(const r of this.mediaByThumbnail.get(n)||[])t.set(this.getRecordKey(r),r);if(e.timestamp)for(const r of this.mediaByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}findDocumentRecord(e){const t=new Map,n=this.normalizeTitle(e.title);if(e.timestamp)for(const r of this.documentByTimestamp.get(e.timestamp)||[])t.set(this.getRecordKey(r),r);if(n)for(const r of this.documentByTitle.get(n)||[])t.set(this.getRecordKey(r),r);return this.pickBestRecord(Array.from(t.values()),e)}pickBestRecord(e,t){if(0===e.length)return null;const n=this.normalizeThumbnailUrl(t.thumbnailUrl),r=this.normalizeTitle(t.title),o=e.map(e=>{let o=0;return void 0!==t.status&&e.status===t.status&&(o+=20),void 0!==t.timestamp&&e.timestamp===t.timestamp&&(o+=80),n&&this.normalizeThumbnailUrl(e.thumbnailUrl)===n&&(o+=200),r&&this.normalizeTitle(e.title)===r&&(o+=120),void 0!==t.timestampNano&&(o-=Math.min(Math.abs((e.timestampNano||0)-t.timestampNano)/1e6,20)),{record:e,score:o}}).sort((e,t)=>t.score-e.score);return o[0]?.record||null}buildRecordUrl(e){const t=e.conversationId.replace(/^c_/,""),n=e.responseId.replace(/^r_/,""),r=new URL(`${window.location.origin}${this.options.getUserPathPrefix()}/app/${t}`);return r.searchParams.set(Ho,"1"),r.hash=n,r.toString()}getRecordKey(e){return `${e.conversationId}:${e.responseId}`}getOpenInNewTabLabel(){return se("geminiMystuffOpenInNewTab")}dismissActionButtonVisualState(e){this.tooltipBindings.get(e)?.hide(),e.blur(),e.setAttribute(ym,"1");const t=()=>{e.removeAttribute(ym),window.removeEventListener("pointermove",t,true),window.removeEventListener("pointerdown",t,true),window.removeEventListener("keydown",t,true),window.removeEventListener("wheel",t,true),window.removeEventListener("touchstart",t,true),e.removeEventListener("focus",t,true);};window.addEventListener("pointermove",t,true),window.addEventListener("pointerdown",t,true),window.addEventListener("keydown",t,true),window.addEventListener("wheel",t,true),window.addEventListener("touchstart",t,true),e.addEventListener("focus",t,true);}}const Cm="delete_ui_failed",Am="delete_batch_aborted_after_ui_failure",Em=["delete","remove","删除","删掉","移除","supprimer","eliminar","löschen","삭제","削除","hapus","удал"],Tm=["cancel","取消","annuler","abbrechen","취소","キャンセル","batal","отмен"];const Mm=["M13 21L12 23L11 21V16H4.5V13.7129L4.65234 13.4697L6.95801 9.78027L6.41797 5.99512C6.11675 3.8866 7.75289 2 9.88281 2H14.1172C16.2471 2 17.8832 3.8866 17.582 5.99512L17.041 9.78027L19.5 13.7129V16H13V21Z"].map(e=>e.replace(/\s+/g,"")),_m="delete_ui_failed",Im="delete_batch_aborted_after_ui_failure",Lm="delete_api_request_failed",Nm="delete_api_not_found_but_visible",Dm=["delete","remove","删除","刪除","supprimer","eliminar","löschen","削除","삭제","удал","excluir"],qm=["confirm","ok","yes","确定","確認","确认","確定","check"];const Rm="ima.qq.com",Pm=/^\/chat\/([a-z0-9]+)(?:\/|$)/i,zm="#scrollContainer",Bm=`${zm} [class*="scrollWrap"]`,Om='div[class*="userBubbleContainer"]',Fm='div[class*="userBubbleWrap"]',$m=[Om,Fm].join(", "),Um=`${Om} [class*="userBubble"]`,jm='[class*="chatMainBubble"]',Hm=[Um,`${Fm} ${jm}`].join(", "),Wm=[`${Um} [class*="content"]`,jm].join(", "),Gm='div[class*="aiContainer"]',Qm=`${Gm} [class*="bubble"]`,Vm='[class*="markdown"]',Km=`${Qm} ${Vm}`,Zm='[class*="thinking"]',Ym='.system-copy-exclude, [x-noteelement="excluded"], [x-copyelement="copy-exclude"]',Jm=[".gh-root",".gh-user-query-markdown",".gh-inline-bookmark",Ym,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Xm=':is([class*="attachmentContainer"], [class*="attachmentWrap"])',ef=[`${Xm} img`,'[class*="imgWrap"] img'].join(", "),tf=[`${Xm} [class*="itemWrap"]`,`${Xm} [class*="file"]`,`${Xm} [class*="doc"]`,`${Xm} a[href]`,`${Xm} [data-file-id]`,`${Xm} [data-doc-id]`,`${Xm} [data-resource-id]`].join(", "),nf=[`${Qm} [class*="imagesWrapper"] img`,`${Qm} [id^="image-toolkit-"] img`,`${Qm} [class*="bigImg"] img`,`${Qm} ${Vm} img`].join(", "),rf=['[class*="imagesWrapper"]','[id^="image-toolkit-"]',".t-image__wrapper","picture","img"].join(", "),of=["href","src","data-src","data-url","data-card-url","data-download-url","data-file-url","data-resource-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],af='[class*="sendBtnWrap"]',sf=['div[class*="stopButton"] > div','[class*="stopButton"][role="button"]','button[class*="stopButton"]','[class*="stopButton"]'].join(", "),lf='[class*="currentChoiceWrap"], [class*="modelSelectionWrap"], [class*="modelSelectionText"]',cf='[class*="modelSelectionText"]';const df=/^\/chat\/([a-z0-9-]+)(?:\/|$)/i,uf=/^\/(?:share|kimiplus)\/([a-z0-9-]+)(?:\/|$)/i,hf=["/docs/","/website/","/table/"],gf="__tea_cache_tokens_",pf="kimi-auth",mf=[pf,"kimi_auth","access_token","accessToken","token","auth","authorization"],ff=["value","token","access_token","accessToken","auth","authorization","id_token","idToken","jwt"],bf=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,yf=/(token|auth|jwt|tea)/i,vf="a.chat-info-item",wf=`${vf}, a.history-link`,xf=".history-part",kf="span.chat-name",Sf=".history-chat .title-wrapper .title",Cf=".chat-content-list",Af=`${Cf}, .share-content-list`,Ef=[Cf,`${Cf}${Cf}`,`${Cf}${Cf}${Cf}`,`.chat-detail-content ${Cf}`,`.chat-detail-content ${Cf}${Cf}`].join(", "),Tf=".chat-content-item",Mf=".chat-content-item-user",_f=".chat-content-item-assistant",If=".segment.segment-user",Lf=".segment.segment-assistant",Nf=[".segment-user .segment-content",`${Mf} .segment-content`,".segment-container:has(.user-content) > .segment-content"].join(", "),Df=[".segment-user .segment-content-box",`${Mf} .segment-content-box`,".segment-content-box:has(> .user-content)"].join(", "),qf=[".segment-user .user-content",`${Mf} .user-content`,".segment-content-box > .user-content"].join(", "),Rf=[".segment-assistant .segment-content-box > .markdown-container > .markdown",`${_f} .segment-content-box > .markdown-container > .markdown`].join(", "),Pf=".toolcall-container, .container-block",zf="button, [role='button'], svg, canvas, [aria-hidden='true'], .segment-avatar, .okc-cards-container",Bf="CUSTOM_THEME",Of="delete_api_missing_auth_token",Ff="delete_api_request_failed",$f="delete_api_invalid_response",Uf="delete_api_business_failed";const jf=/\/chat\/([a-f0-9]+)/i,Hf=/\/group\/([a-f0-9]+)/i,Wf="tongyi-theme-preference",Gf="model-select-expanded",Qf='[class*="questionItem"], .chat-question-wrap, [class*="message-select-wrapper-question"]',Vf="[data-chat-question-wrap]",Kf='[class*="answerItem"], [data-chat-answers-wrap], .chat-answers-card-wrap',Zf='[class*="bubble"]',Yf=[`${Vf} .message-card-wrap.question`,`${Vf} .question-text-card`].join(", "),Jf=".message-card-wrap.question",Xf=`${Jf}[data-mt*="image"]`,eb=[`${Jf}[data-mt*="doc"]`,`${Jf}[data-mt*="file"]`,`${Jf}[data-mt*="office"]`,`${Jf}:has([class*="office-card"])`].join(", "),tb=[".answer-common-card .qk-markdown",".markdown-pc-special-class .qk-markdown","#qk-markdown-react",".answer-common-card"].join(", "),nb=['[data-card-type="ai_generate_image_list"] img',".card_card_ai_generate_image img",'[data-tpl*="card_ai_generate_image"] img','img[data-image-menu-items*="download"]','img[class*="image-"][data-image-resource-id]'].join(", "),rb=['[data-card-type="ai_generate_image_list"]',".card_card_ai_generate_image",'[data-tpl*="card_ai_generate_image"]'].join(", "),ob=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']",".qk-md-table-action",".qk-md-copy-icon","[class*='answerToolsContent']","[class*='functionArea']","[class*='recommend-query']",".q-item",".qs-bottom","style","script"].join(", "),ib=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],ab='[class*="chatInput"]',sb=".message-list-scroll-container, #message-list-scroller",lb="#qwen-message-list-area",cb="aside#new-nav-tab-wrapper",db='.qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], [class*="thinkingHeader"], [class*="thinkingTitle"]',ub='[class*="stop-"], [class*="stopBtn"], div[class*="stop"]',hb='[role="dialog"], [data-radix-popper-content-wrapper]',gb=['[role="dialog"] [id="tongyi-for-guide-model"]','[role="dialog"] .group.rounded-8','[data-radix-popper-content-wrapper] [id="tongyi-for-guide-model"]',"[data-radix-popper-content-wrapper] .group.rounded-8"].join(", ");const pb=/\/c\/([a-f0-9-]+)/i,mb="theme",fb="#sidebar",bb=".session-list-wrapper",yb=".chat-item-drag",vb=".chat-item-drag-link-content-tip-text",wb="#chat-messages-scroll-container",xb="#chat-message-container",kb=".qwen-chat-message-user, .chat-user-message-wrapper",Sb=".qwen-chat-message-assistant",Cb=".user-message-content",Ab=".response-message-content",Eb="button.send-button",Tb=["button.stop-button",'button[class*="stop-button"]',".stop-button"],Mb="pre.qwen-markdown-code",_b=".artifacts-body-header-switch",Ib=".artifacts-body-header-switch-active, .artifacts-body-header-switch-unactive, .header-switch-status-small",Lb="data-ophel-qwenai-mermaid-export-switched",Nb=".qwen-chat-thinking-tool-status-card-wraper, .qwen-chat-thinking-status-card",Db=".qwen-chat-thinking-status-card-title-text",qb=[".splitter-container-right-panel .qwen-chat-thinking-and-sources",".share-layout-right-panel .qwen-chat-thinking-and-sources",".qwen-chat-thinking-and-sources-share"].join(", "),Rb=".response-message-footer, .copy-response-button, .message-hoc-container",Pb=[".gh-root",".gh-user-query-markdown",Nb,Rb,"button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),zb=[".user-image-item",".user-image-list .qwen-image","[class*='file-message-image'] .qwen-image",".qwen-markdown-image:has(img)"].join(", "),Bb=[".chat-response-media-render img",".qwen-chat-response-control-card img",".response-message-content img",".qwen-markdown-image img","img.qwen-image"].join(", "),Ob=[".chat-response-media-render",".qwen-chat-response-control-card",".qwen-markdown-image","picture","img"].join(", "),Fb=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],$b='#qwen-chat-header-left .ant-dropdown-trigger:has([class*="model-selector-text"])',Ub='#qwen-chat-header-left [class*="model-selector-text"]',jb='[class*="model-selector-popup"]',Hb=[`${jb} [class*="model-list"] > [class*="model-item___"]`,`${jb} [class*="model-list"] > [class*="model-item-selected___"]`].join(", "),Wb=[`${jb} .ant-dropdown-trigger:has([class*="view-more-text"])`,`${jb} .ant-dropdown-trigger:has([class*="view-more-icon"])`].join(", "),Gb=[Hb,Wb,'.ant-dropdown [role="menuitem"]',".ant-dropdown .ant-dropdown-menu-item",".ant-dropdown .ant-dropdown-menu-title-content",'.ant-select-dropdown [role="option"]',".ant-select-dropdown .ant-select-item-option"].join(", "),Qb=".qwen-markdown-latex";const Vb="yuanbao.tencent.com",Kb=/^\/chat\/([^/?#]+)(?:\/([^/?#]+))?/,Zb="yb_web_theme_mode",Yb="#yuanbao-send-btn, a.style__send-btn___RwTm5",Jb="a.style__send-btn___RwTm5",Xb=".yb-recent-conv-list__item",ey=".yb-recent-conv-list__item.active",ty=".yb-recent-conv-list__item-name[data-item-name], .yb-recent-conv-list__item-name, [data-item-id][data-item-name]",ny="#chat-content .agent-chat__list__content, .agent-chat__list__content",ry=".agent-chat__list__item--human",oy=".agent-chat__list__item--ai",iy=".agent-chat__list__item--ai .hyc-common-markdown-style, .agent-chat__list__item--ai .hyc-content-md-done",ay=".agent-chat__toolbar, .agent-chat__toolbar_new, .agent-chat__question-toolbar, .hyc-common-markdown__code__hd__r",sy=".hyc-card-box-process-list, .hyc-common-markdown__replace-appCard",ly=[".hyc-component-multi-modal__image img",".agent-chat__bubble--human .hyc-content-img img"].join(", "),cy=[".hyc-component-multi-modal__file",".hyc-component-multi-modal__doc",".hyc-component-multi-modal__document",".hyc-content-file",".hyc-content-doc",".hyc-file-card",".hyc-doc-card","[data-file-id]","[data-doc-id]","[data-resource-id]","a[href*='/api/resource/download']",".agent-chat__bubble--human [class*='file']",".agent-chat__bubble--human [class*='doc']"].join(", "),dy=['[data-card-type="image"] img','[data-box-type="loadingImage"] img',".hyc-media-box--loadingImage img",".loading-image-box img"].join(", "),uy=['[data-card-type="image"]','[data-box-type="loadingImage"]',".hyc-media-box--loadingImage",".loading-image-box"].join(", "),hy=["href","src","data-src","data-url","data-card-url","data-download-url","data-file-url","data-resource-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],gy=".ybc-model-select-button .t-button__text",py=[".hyc-component-reasoner__think-content .hyc-common-markdown-style",".hyc-component-deepsearch-cot__think__content__item .hyc-common-markdown-style",".hyc-common-markdown-style-cot"].join(", "),my=[".hyc-component-reasoner__think",".hyc-component-deepsearch-cot__think",".hyc-common-markdown-style-cot"].join(", "),fy=[".hyc-component-reasoner__text .hyc-common-markdown-style",".hyc-component-reasoner__text .hyc-content-md-done",".hyc-component-reasoner__text"],by=[".t-dropdown__menu",".t-dropdown__submenu",".t-dropdown",".t-popup",".t-popup__content",".t-popup__content__inner",'[role="menu"]','[role="listbox"]'].join(", "),yy=[".t-dropdown__item",".yb-dropdown__item",'[role="menuitem"]','[role="option"]'].join(", "),vy=['[aria-haspopup="menu"]','[aria-haspopup="listbox"]',".icon-yb-ic_ellipsis",".icon-yb-ic_more_vert",".icon-yb-ic_more_vert_16",".icon-yb-ic_delete",".icon-yb-ic_delete_16",".icon-yb-ic_delete_20",".icon-more",".icon-del",".icon-delete",".icon-menu","button",'[role="button"]'].join(", "),wy='.t-dialog, [role="dialog"]',xy="--hunyuan-chat-list-max-width",ky=/删除|delete/i,Sy=/删除|确认|确定|delete|confirm/i,Cy=/取消|cancel/i,Ay="ui_failed",Ey="ui_exception",Ty="batch_aborted_after_ui_failure";const My="chat.z.ai",_y=/\/(?:c|s)\/([a-z0-9-]+)(?:\/|$)/i,Iy=/\/s\/([a-z0-9-]+)(?:\/|$)/i,Ly=["#chat-input","textarea#chat-input"],Ny="#send-message-button",Dy=["#sidebar-new-chat-button","#new-chat-button"],qy=["button.modelSelectorButton",'button[id^="model-selector-"][id$="-button"]',"#model-selector-glm-5-button","button[data-melt-dropdown-menu-trigger][data-menu-trigger].modelSelectorButton"],Ry="#chat-container",Py=[`${Ry} .flex.overflow-y-scroll.flex-col.w-full.h-full`,`${Ry} .scrollbar-none.flex.flex-col`,`${Ry} [data-pane-id] .overflow-y-scroll`,`${Ry} [data-pane-id] .scrollbar-none`].join(", "),zy=['[id^="message-"].user-message',".user-message .chat-user.markdown-prose",".user-message .chat-user",`${Ry} .chat-user.markdown-prose`,`${Ry} .chat-user`,`${Ry} [data-message-author-role="user"]`,`${Ry} [data-role="user"]`,`${Ry} .message-user`,`${Ry} .user-message`,`${Ry} .chat-message-user`,`${Ry} .message.user`].join(", "),By=[`${Ry} .markdown-prose:not(.chat-user)`,`${Ry} [data-message-author-role="assistant"]`,`${Ry} [data-role="assistant"]`,`${Ry} .message-assistant`,`${Ry} .assistant-message`,`${Ry} .chat-message-assistant`,`${Ry} .markdown`,`${Ry} .markdown-body`,`${Ry} .prose`,`${Ry} article`,`${Ry} [data-markdown]`,'[id^="message-"]:not(.user-message) .markdown-prose:not(.chat-user)','[id^="message-"]:not(.user-message) .markdown-body','[id^="message-"]:not(.user-message) [data-markdown]'].join(", "),Oy=['[id^="message-"]:not(.user-message)',By].join(", "),Fy="data-gh-export-role",$y=`[${Fy}="user"]`,Uy=`[${Fy}="assistant"]`,jy=".thinking-chain-container, .thinking-block",Hy=[".gh-user-query-raw",".rounded-xl.whitespace-pre-wrap",".rounded-xl",".whitespace-pre-wrap","[data-user-content]",".message-content",".chat-message-content",".user-message-content",".content",'div[dir="auto"]',"p"],Wy=[".gh-root",".gh-user-query-markdown","button","[role='button']","svg","[aria-hidden='true']","style","script"].join(", "),Gy=["href","src","data-src","data-url","data-download-url","data-file-url","data-source-url","data-origin-url","data-original-url","data-thumbnail-url","data-image-url","data-image-src"],Qy=['div[aria-label="停止"] button',"button:has(span.rounded-xs):has(span.size-3)","button:has(span.rounded-xs):has(span.block)"].join(", "),Vy="#sidebar .w-full.mb-1.relative.group",Ky='div[dir="auto"]',Zy="theme",Yy={light:"#F4F6F8",dark:"#141618"},Jy=/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,Xy=/^message-([a-f0-9-]{36})$/i;const ev=[new class extends gs{clearOnInit=false;cloneWithoutSrOnly(e){const t=e.cloneNode(true);return t.querySelectorAll(".sr-only").forEach(e=>e.remove()),t}match(){return window.location.hostname.includes("business.gemini.google")}getSiteId(){return ho}getName(){return "Gemini Enterprise"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNewTabUrl(){return "https://business.gemini.google"}isNewConversation(){return !window.location.pathname.includes("/session/")}isSharePage(){return window.location.pathname.includes("/r/share/")}isUserConversationPage(){return !this.isSharePage()&&/\/session\/[^/?#]+(?:\/|$)/i.test(window.location.pathname)}supportsTabRename(){return true}getCurrentCid(){const e=window.location.pathname.match(/\/home\/cid\/([^/]+)/);return e?e[1]:""}getSessionName(){const e=os.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(!e)continue;if(e.classList.contains("selected")||e.classList.contains("active")||"true"===e.getAttribute("aria-selected")){const t=e.querySelector(".conversation-title");if(t){const e=t.textContent?.trim();if(e)return e}}}return super.getSessionName()}getConversationTitle(){const e=os.query(".conversation",{all:true,shadow:true});for(const t of e){const e=t.querySelector("button.list-item")||t.querySelector("button");if(e&&(e.classList.contains("selected")||e.classList.contains("active")))return e.querySelector(".conversation-title")?.textContent?.trim()||null}return null}getConversationList(){const e=os.query(".conversation",{all:true,shadow:true}),t=this.getCurrentCid();return Array.from(e).map(e=>{const n=e.querySelector("button.list-item")||e.querySelector("button");if(!n)return null;const r=n.querySelector(".conversation-action-menu-button");let o="";if(r&&r.id&&r.id.startsWith("menu-")&&(o=r.id.replace("menu-","")),!o||!/^\d+$/.test(o))return null;const i=n.querySelector(".conversation-title"),a=i&&i.textContent?.trim()||"",s=n.classList.contains("selected")||n.classList.contains("active")||"true"===n.getAttribute("aria-selected");let l=`https://business.gemini.google/session/${o}`;return t&&(l=`https://business.gemini.google/home/cid/${t}/r/session/${o}`),{id:o,cid:t,title:a,url:l,isActive:s}}).filter(e=>null!==e)}getLatestReplyText(){const e=os.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return null;const t=e.shadowRoot.querySelector(".main");if(!t)return null;const n=t.querySelectorAll(".turn");if(0===n.length)return null;const r=n[n.length-1].querySelector("ucs-summary");if(!r)return null;const o=this.extractSummaryContent(r);if(!o)return this.extractTextWithLineBreaks(r);const i=this.cloneWithoutSrOnly(o),a=Fi(i).trim();return a||this.extractTextWithLineBreaks(i)}getSidebarScrollContainer(){return os.query(".conversation-list",{shadow:true})||os.query("mat-sidenav",{shadow:true})}getConversationObserverConfig(){return {selector:".conversation",shadow:true,extractInfo:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");if(!t)return null;const n=t.querySelector(".conversation-action-menu-button");if(!n||!n.id?.startsWith("menu-"))return null;const r=n.id.replace("menu-","");if(!/^\d+$/.test(r))return null;const o=t.querySelector(".conversation-title"),i=o?.textContent?.trim()||"",a=this.getCurrentCid();return {id:r,cid:a,title:i,url:`https://business.gemini.google/home/cid/${a}/r/session/${r}`}},getTitleElement:e=>{const t=e.querySelector("button.list-item")||e.querySelector("button");return t?.querySelector(".conversation-title")||e}}}navigateToConversation(e,t){const n=os.query(".conversation",{all:true,shadow:true});if(n)for(const r of Array.from(n)){if(r.querySelector(`#menu-${e}`)||r.querySelector(`.conversation-action-menu-button[id="menu-${e}"]`)){const e=r.querySelector("button.list-item")||r.querySelector("button");return e?e.click():r.click(),true}}return super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Cm}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);const n=await this.findConversationMenuButton(t);if(!n)return false;const r=await this.openConversationMenu(t,n);if(!r)return false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o),this.removeConversationRowElement(t,e);const i=await this.waitForConversationRemoved(e,5200),a=await this.waitForMenuClosed(1200),s=i||a;return s&&this.syncConversationListAfterDelete(e),s}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){if(n){const e=o.find(e=>e.id===`menu-${n}`);if(e)return e}const e=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"], md-icon'));if(e)return e;const t=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(t)return t}await this.sleep(90);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}revealConversationActions(e){const t=["mouseenter","mouseover","mousemove"];for(const n of t)e.dispatchEvent(new MouseEvent(n,{bubbles:true,cancelable:true,view:window}));}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,Tm))return e}return null}getMenuActionCandidates(e,t){const n='md-menu-item, [role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=this.getMenuContainerFromTrigger(e);o&&r.push(...Array.from(o.querySelectorAll(n)));const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(t):t;return os.query(`#${n}`,{shadow:true})||null}findVisibleMenuContainer(){const e=this.findAllElementsBySelector('md-menu-surface, .menu[popover], .mat-mdc-menu-panel, [role="menu"]').filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForMenuClosed(e=1200){const t=Date.now();for(;Date.now()-te instanceof HTMLElement),r=new Set;for(const o of n)r.has(o)||(r.add(o),o.isConnected&&o.remove());}async waitForConversationRemoved(e,t=5200){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getNewChatButtonSelectors(){return [".chat-button.list-item",'button[aria-label="New chat"]','button[aria-label="新对话"]']}getWidthSelectors(){const e=(e,t,n,r=false)=>({selector:e,globalSelector:`mat-sidenav-content ${e}`,property:"max-width",value:t,extraCss:n,noCenter:r});return [e("mat-sidenav-content","100%",void 0,true),e(".main.chat-mode","100%",void 0,true),e("ucs-summary"),e("ucs-conversation"),e("ucs-search-bar"),e(".summary-container.expanded"),e(".conversation-container"),e(".input-area-container",void 0,"left: 0 !important; right: 0 !important;",true)]}getUserQueryWidthSelectors(){return [{selector:".question-block .question-wrapper",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["ucs-nav-panel"]}}getCleanModeConfig(){return {hide:[".disclaimer"]}}getTextareaSelectors(){return ["div.ProseMirror",".ProseMirror",'[contenteditable="true"]:not([type="search"])','[role="textbox"]','textarea:not([type="search"])']}getSubmitButtonSelectors(){return ['button[aria-label*="Submit"]','button[aria-label*="提交"]','button[aria-label*="发送"]','button[aria-label*="Send"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if("search"===e.type)return false;if(e.classList.contains("main-input"))return false;if(e.getAttribute("aria-label")?.includes("搜索"))return false;if(e.placeholder?.includes("搜索"))return false;if(e.classList.contains("prompt-search-input"))return false;if("prompt-search"===e.id)return false;if(e.closest(".gh-main-panel"))return false;if(e.closest(".gh-queue-panel"))return false;if(Array.from(e.classList).some(e=>e.startsWith("gh-queue-")||e.startsWith("gh-")))return false;const t=null!==e.offsetParent,n="true"===e.getAttribute("contenteditable"),r=e.classList.contains("ProseMirror");return t&&(n||r||"TEXTAREA"===e.tagName)}findTextarea(){const e=os.query(this.getTextareaSelectors(),{shadow:true,filter:e=>this.isValidTextarea(e)});return e?(this.textarea=e,e):super.findTextarea()}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("insertText",false,"​")):this.textarea=null);}clearTextareaNormal(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)):this.textarea=null);}insertPrompt(e){const t=this.textarea||this.findTextarea();if(!t)return console.warn("[GeminiEnterpriseAdapter] Editor not found during insert."),false;if(!t.isConnected)return this.textarea=null,false;this.textarea=t,t.click(),t.focus();const n=()=>(t.textContent?.replace(/[\u200B\u200C\u200D\uFEFF]/g,"")||"").includes(e);try{const r=new DataTransfer;r.setData("text/plain",e);const o=new ClipboardEvent("paste",{bubbles:!0,cancelable:!0,clipboardData:r});if(t.dispatchEvent(o),n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),!0}catch{}try{document.execCommand("selectAll",!1,void 0);if(document.execCommand("insertText",!1,e)&&n())return t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),!0}catch{}try{t.focus();const r=t.ownerDocument.getSelection();r&&(r.selectAllChildren(t),r.collapseToEnd());const o=new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});t.dispatchEvent(o);const i=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e});if(t.dispatchEvent(i),n())return !0}catch{}try{let r=t.querySelector("p"),o=!1;if(r||(r=document.createElement("p"),t.appendChild(r),o=!0),r.textContent=e,(o||e)&&(t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))),t.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e})),t.dispatchEvent(new KeyboardEvent("keydown",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:" ",code:"Space"})),t.dispatchEvent(new Event("change",{bubbles:!0})),n())return !0}catch{}return console.warn("[GeminiEnterpriseAdapter] All insert strategies failed for content insertion."),false}getScrollContainer(){const e=os.query(".chat-mode-scroller",{shadow:true});return e&&e.scrollHeight>e.clientHeight?e:super.getScrollContainer()}scrollToOutlineTarget(e){const t=this.getScrollContainer();if(t){const n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),o=t.scrollTop+(r.top-n.top);t.scrollTo({top:o,behavior:"instant",__bypassLock:true});}else super.scrollToOutlineTarget(e);}getResponseContainerSelector(){return ".conversation-container"}getChatContentSelectors(){return [".model-response-container",".message-content","[data-message-id]","ucs-conversation-message",".conversation-message"]}getUserQuerySelector(){return ".question-block"}extractUserQueryText(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return this.extractTextWithLineBreaks(e);const n=t.shadowRoot.querySelector(".markdown-document");return n?this.extractTextWithLineBreaks(n):this.extractTextWithLineBreaks(e)}extractAssistantResponseText(e){const t=this.extractSummaryContent(e);if(!t)return this.extractTextWithLineBreaks(e);const n=this.cloneWithoutSrOnly(t),r=Fi(n).trim();return r||this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=e.querySelector("ucs-fast-markdown");if(!t||!t.shadowRoot)return e.textContent?.trimEnd()||"";const n=t.shadowRoot.querySelector(".markdown-document");if(!n)return e.textContent?.trimEnd()||"";const r=n.querySelectorAll("p");if(0===r.length)return n.textContent?.trimEnd()||"";return Array.from(r).map(e=>e.textContent||"").join("\n").trimEnd()}replaceUserQueryContent(e,t){const n=e.querySelector("ucs-fast-markdown");if(!n||!n.shadowRoot)return false;const r=n.shadowRoot.querySelector(".markdown-document");if(!r)return false;if(r.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const o=document.createElement("div");return o.className="gh-user-query-markdown gh-markdown-preview",!!Rp(o,t)&&(r.style.display="none",r.after(o),true)}usesShadowDOM(){return true}extractSummaryContent(e){const t=(e,n=0)=>{if(n>10||!e)return null;const r=e.shadowRoot||(11===e.nodeType?e:null)||e;if("querySelector"in r){const e=r.querySelector(".markdown-document");if(e)return e}const o="querySelectorAll"in r?r.querySelectorAll("*"):[];for(const i of Array.from(o))if(i.shadowRoot){const e=t(i.shadowRoot,n+1);if(e)return e}return null};return t(e)}findHeadingsInShadowDOM(e,t,n,r,o,i={}){if(!(r>15))if("shadowRoot"in e&&e.shadowRoot)this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);else {if(e!==document&&"querySelectorAll"in e){const r=Array.from({length:n},(e,t)=>`h${t+1}`).join(", ");try{e.querySelectorAll(r).forEach(e=>{if(this.isInRenderedMarkdownContainer(e))return;const n=e.querySelectorAll("span[data-markdown-start-index]");if(n.length>0){const r=parseInt(e.tagName[1],10),a=Array.from(n).map(e=>e.textContent?.trim()).join("");if(a){const n={level:r,text:a,element:e};if(o){const t=`${e.tagName.toLowerCase()}-${a}`,r=i[t]||0;i[t]=r+1,n.id=`${o}::${t}::${r}`;}t.push(n);}}});}catch{}}if("querySelectorAll"in e){const a=e.querySelectorAll("*");for(const e of Array.from(a))e.shadowRoot&&this.findHeadingsInShadowDOM(e.shadowRoot,t,n,r+1,o,i);}}}extractOutline(e=6,t=false,n=false){const r=[],o=e=>{const t=this.extractSummaryContent(e);return t?t.textContent?.trim().length||0:e.textContent?.trim().length||0};if(!t)return this.findHeadingsInShadowDOM(document,r,e,0),n&&r.forEach((e,t)=>{if(!e.element)return;const n=e.element.closest(".markdown-document");if(n){let o=null;for(let n=t+1;n{const i=(t.getAttribute("jslog")||"").match(/(\d+_\d+)/),a=i?i[1]:void 0,s=t.querySelector(".question-block"),l=t.querySelector("ucs-summary");if(s){let e=this.extractUserQueryText(s),t=false;e.length>200&&(e=e.substring(0,200),t=true);const i={level:0,text:e,element:s,isUserQuery:true,isTruncated:t,id:a};n&&l&&(i.wordCount=o(l)),r.push(i);}if(l){const t=[];if(this.findHeadingsInShadowDOM(l,t,e,0,a),n){const e=this.extractSummaryContent(l);t.forEach((n,r)=>{if(!n.element)return;let o=null;for(let e=r+1;er.push(e));}}),r}findElementByHeading(e,t){const n=os.query(`h${e}`,{all:true,shadow:true});for(const r of n)if(r.textContent?.trim()===t)return r;return null}getExportConfig(){return {userQuerySelector:".question-block",assistantResponseSelector:"ucs-summary",turnSelector:".turn",useShadowDOM:true}}getAssistantMermaidSupportMode(){return "fallback"}getAssistantMermaidBlocks(e){const t=e instanceof Element?e.matches("ucs-summary")?e:e.closest("ucs-summary")||os.query("ucs-summary",{parent:e,shadow:true}):os.query("ucs-summary",{parent:e,shadow:true})||null;if(!t)return [];const n=this.extractSummaryContent(t);return hs(n||t)}isGenerating(){const e=(t,n=0)=>{if(n>10)return false;const r=t.querySelector('button[aria-label*="Stop"], button[aria-label*="停止"], [data-test-id="stop-button"], .stop-button, md-icon-button[aria-label*="Stop"]');if(r&&null!==r.offsetParent)return true;const o=t.querySelector('mat-spinner, md-spinner, .loading-spinner, [role="progressbar"], .generating-indicator, .response-loading');if(o&&null!==o.offsetParent)return true;const i=t.querySelectorAll("*");for(const a of Array.from(i))if(a.shadowRoot&&e(a.shadowRoot,n+1))return true;return false};return e(document)}getStopButtonSelectors(){return ['button[aria-label*="Stop"]','button[aria-label*="停止"]','[data-test-id="stop-button"]',".stop-button",'md-icon-button[aria-label*="Stop"]']}requiresDomConfirmationForNetworkGeneration(){return true}getModelName(){const e=(t,n=0)=>{if(n>10)return null;const r=["#model-selector-menu-anchor",".action-model-selector",".model-selector",'[data-test-id="model-selector"]',".current-model"];for(const e of r){const n=t.querySelector(e);if(n&&n.textContent){const e=n.textContent.trim(),t=e.match(/(\d+\.?\d*\s*)?(Pro|Flash|Ultra|Nano|Gemini|auto|自动)/i);if(t)return t[0].trim();if(e.length<=20&&e.length>0)return e}}const o=t.querySelectorAll("*");for(const i of Array.from(o))if(i.shadowRoot){const t=e(i.shadowRoot,n+1);if(t)return t}return null};return e(document)}getNetworkMonitorConfig(){return {urlPatterns:["widgetStreamAssist"],silenceThreshold:3e3}}afterPropertiesSet(e={}){this.clearOnInit=e.clearOnInit||false,super.afterPropertiesSet(e),this.clearOnInit&&this.clearTextarea();}lockModel(e,t=null){super.lockModel(e,t??void 0);}shouldInjectIntoShadow(e){return !(e.closest("mat-sidenav")||e.closest("mat-drawer")||e.closest('[class*="bg-sidebar"]'))}async loadAllConversations(){for(let e=0;e<20;e++){const e=(os.query("button.show-more",{all:true,shadow:true})||[]).filter(e=>{const t=e.querySelector(".show-more-icon");return t&&!t.classList.contains("more-visible")});if(0===e.length)break;for(const t of e)t.click();await new Promise(e=>setTimeout(e,300));}}getDefaultLockSettings(){return {enabled:true,keyword:"3 Pro"}}getModelSwitcherConfig(e){return {targetModelKeyword:e||"3 Pro",selectorButtonSelectors:["#model-selector-menu-anchor",".action-model-selector"],menuItemSelector:"md-menu-item",checkInterval:1500,maxAttempts:20,menuRenderDelay:500}} /** * 模拟点击原生设置切换主题 (针对 Gemini Enterprise) * @param targetMode 目标主题模式 */ async toggleTheme(e){let t=false;const n=()=>{if(!t){try{os.query('.menu[popover], md-menu-surface, .mat-menu-panel, [role="menu"]',{all:!0,shadow:!0}).forEach(e=>{const t=e;"0"!==t.style.opacity&&(t.style.setProperty("opacity","0","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("pointer-events","none","important"));});}catch{}requestAnimationFrame(n);}};n(),document.body.classList.add("gh-stealth-mode");try{let t=os.query(".settings-button",{shadow:!0});if(!t)return console.error("[GeminiEnterpriseAdapter] Settings button not found (.settings-button)"),!1;"function"==typeof t.click?t.click():t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}));let n=0;const r=()=>{const t="system"===e?"computer":"dark"===e?"dark_mode":"light_mode",n=os.query("md-primary-tab",{all:!0,shadow:!0});for(const e of n){const n=e.querySelector("md-icon")||os.query("md-icon",{parent:e,shadow:!0});if(n&&n.textContent?.trim()===t)return e.click(),!0}return !1};return await new Promise(e=>{const o=setInterval(()=>{n++,r()?(clearInterval(o),e(!0)):n>20&&(clearInterval(o),console.error("[GeminiEnterpriseAdapter] Target theme option not found"),e(!1),t&&"function"==typeof t.click&&t.click());},100);})}finally{t=true,setTimeout(()=>{document.body.classList.remove("gh-stealth-mode");},200);}}},new class extends gs{cachedAccountEmail=null;accountEmailLastDetectAt=0;myStuffEnhancer=null;deepResearchPanelWatchStop=null;deepResearchPanelObservers=new WeakMap;deepResearchPanelTooltipBindings=new WeakMap;exportOpenedCanvasPanel=false;getUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);if(!e)return "";return `/u/${e[1]}`}getCurrentCid(){const e=this.getCurrentAccountEmail();if(e)return e;const t=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return t?t[1]:"0"}getCurrentAccountEmail(){const e=Date.now();if(e-this.accountEmailLastDetectAt<2e3)return this.cachedAccountEmail;this.accountEmailLastDetectAt=e;const t=["aria-label","title","data-email","data-identifier"],n=new Set;["[data-email]",'[data-identifier*="@"]','[aria-label*="@"]','[title*="@"]'].forEach(e=>{document.querySelectorAll(e).forEach(e=>n.add(e));});for(const r of n)for(const e of t){const t=r.getAttribute(e),n=this.extractEmailFromAttr(e,t);if(n)return this.cachedAccountEmail=n,n}return this.cachedAccountEmail}startDeepResearchPanelActions(){this.deepResearchPanelWatchStop||(this.injectDeepResearchPanelActionStyles(),this.deepResearchPanelWatchStop=os.each(nm,e=>this.watchDeepResearchPanel(e),{shadow:true}));}watchDeepResearchPanel(e){if(this.syncDeepResearchPanelActions(e),this.deepResearchPanelObservers.has(e))return;let t=null;t=os.watch(e,()=>{if(!e.isConnected)return t?.(),void this.deepResearchPanelObservers.delete(e);this.syncDeepResearchPanelActions(e);},{childList:true,subtree:true,attributes:true,attributeFilter:["aria-busy"],debounce:100}),this.deepResearchPanelObservers.set(e,t);}injectDeepResearchPanelActionStyles(){os.css(`\n .${lm} {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n margin-inline-end: 4px;\n }\n\n .${cm} {\n width: 40px;\n height: 40px;\n border: 0;\n border-radius: 999px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 0;\n background: transparent;\n color: var(--bard-color-on-surface-variant, #5f6368);\n cursor: pointer;\n transition:\n background-color 0.16s ease,\n color 0.16s ease,\n opacity 0.16s ease;\n }\n\n .${cm}:hover:not(:disabled),\n .${cm}:focus-visible:not(:disabled) {\n background: rgba(60, 64, 67, 0.08);\n color: var(--bard-color-on-surface, #202124);\n outline: none;\n }\n\n .${cm}:disabled {\n cursor: default;\n opacity: 0.38;\n }\n\n .${cm} svg {\n width: 18px;\n height: 18px;\n stroke: currentColor;\n }\n\n body.dark-theme .${cm},\n html.dark .${cm},\n html[dark-theme] .${cm} {\n color: rgba(232, 234, 237, 0.86);\n }\n\n body.dark-theme .${cm}:hover:not(:disabled),\n body.dark-theme .${cm}:focus-visible:not(:disabled),\n html.dark .${cm}:hover:not(:disabled),\n html.dark .${cm}:focus-visible:not(:disabled),\n html[dark-theme] .${cm}:hover:not(:disabled),\n html[dark-theme] .${cm}:focus-visible:not(:disabled) {\n background: rgba(232, 234, 237, 0.12);\n color: #ffffff;\n }\n `,"gh-gemini-deep-research-panel-actions-style");}syncDeepResearchPanelActions(e){const t=this.getDeepResearchPanelMarkdownElement(e),n=e.querySelector("toolbar .action-buttons");if(!(n instanceof HTMLElement&&t))return void this.removeDeepResearchPanelActions(e);if(e.querySelector(`[${dm}="1"]`))return void this.updateDeepResearchPanelActionDisabledState(e);const r=this.createDeepResearchPanelActions(e),o=n.querySelector('[data-test-id="export-menu-button"]');o?.parentElement===n?n.insertBefore(r,o):n.prepend(r),this.updateDeepResearchPanelActionDisabledState(e);}removeDeepResearchPanelActions(e){e.querySelectorAll(`[${dm}="1"]`).forEach(e=>{e.querySelectorAll(`.${cm}`).forEach(e=>{e instanceof HTMLElement&&this.deepResearchPanelTooltipBindings.get(e)?.destroy();}),e.remove();});}createDeepResearchPanelActions(e){const t=document.createElement("div");t.className=lm,t.setAttribute(dm,"1");const n=this.createDeepResearchPanelActionButton("copy"),r=this.createDeepResearchPanelActionButton("download");return n.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.copyDeepResearchPanelMarkdown(e,n);}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.downloadDeepResearchPanelMarkdown(e);}),t.append(n,r),t}createDeepResearchPanelActionButton(e){const t=document.createElement("button");t.type="button",t.className=cm,t.setAttribute("aria-label",this.getDeepResearchPanelActionLabel(e)),t.title=this.getDeepResearchPanelActionLabel(e),t.appendChild("copy"===e?pp({size:18}):this.createDeepResearchPanelDownloadIcon());const n=dp(t,{getContent:()=>this.getDeepResearchPanelActionLabel(e),preferredPlacement:"bottom"});return this.deepResearchPanelTooltipBindings.set(t,n),t}createDeepResearchPanelDownloadIcon(){const e=gp("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"});return [Ke,Ze,Ye].forEach(t=>{e.appendChild(gp("path",{d:t}));}),e}getDeepResearchPanelActionLabel(e){return "copy"===e?se("exportToClipboard"):`${se("webdavDownloadBtn")} ${se("exportToMarkdown")}`}updateDeepResearchPanelActionDisabledState(e){const t=this.hasDeepResearchPanelContent(e);e.querySelectorAll(`.${cm}`).forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}async copyDeepResearchPanelMarkdown(e,t){const n=this.getDeepResearchPanelMarkdown(e);if(!n)return void Li(se("exportNoContent"));const r=await async function(e){try{return await navigator.clipboard.writeText(e),!0}catch(t){return console.error("[Exporter] Failed to copy:",t),false}}(n);r?(mp(t,{size:18}),Li(se("copySuccess"))):Li(se("copyFailed"));}async downloadDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdown(e);if(!t)return void Li(se("exportNoContent"));const n=await ra(function(e){return e?e.startsWith("\ufeff")?e:`\ufeff${e}`:"\ufeff"}(t),ma(this.getDeepResearchPanelTitle(e)||pa(t,"deep-research-report"),"deep-research-report"),"text/markdown;charset=utf-8");n&&Li(se("exportSuccess"));}getDeepResearchPanelMarkdown(e){const t=this.getDeepResearchPanelMarkdownElement(e);return t?this.extractAssistantResponseTextWithAssets(t).trim():""}hasDeepResearchPanelContent(e){const t=this.getDeepResearchPanelMarkdownElement(e);return Boolean(t?.textContent?.trim())}getDeepResearchPanelMarkdownElement(e){return Array.from(e.querySelectorAll("#extended-response-markdown-content, message-content .markdown")).find(e=>null===e.closest("thinking-panel"))||null}getDeepResearchPanelTitle(e){const t=this.getNormalizedText(e.querySelector("toolbar h2.title-text"));if(t)return t;return this.getNormalizedText(this.getDeepResearchPanelMarkdownElement(e)?.querySelector("h1"))||null}extractEmailFromAttr(e,t){return t&&("data-email"===e||"data-identifier"===e||Wp.test(t))?this.extractEmail(t):null}extractEmail(e){if(!e)return null;const t=e.match(Hp);return t?t[1].toLowerCase():null}match(){return window.location.hostname.includes("gemini.google")&&!window.location.hostname.includes("business.gemini.google")}getSiteId(){return lo}getName(){return "Gemini"}getThemeColors(){return {primary:"#4285f4",secondary:"#34a853"}}getNativeThemeCss(){return "\n/* =============================================\n * Gemini 站点原生主题适配器 (Gemini Theme Adapter)\n * ============================================= */\n:root body.light-theme, :root body.dark-theme, :root {\n /* 1. 核心页面背景层 */\n --bard-color-lm-surface: var(--gh-bg) !important;\n --bard-color-lm-surface-bright: var(--gh-bg) !important;\n --bard-color-lm-surface-dim: var(--gh-bg-secondary) !important;\n --bard-color-footer-background: var(--gh-bg-secondary) !important;\n --bard-color-inverse-primary-background: var(--gh-bg-tertiary) !important;\n\n /* 2. 侧边栏与浮动层:使用极其微弱的主色调混合背景,避免大面积色块导致“太亮”或“太腻” */\n --bard-color-sidenav-background-desktop: color-mix(in srgb, var(--gh-primary) 5%, var(--gh-bg)) !important;\n\n --bard-color-icon-container-background: color-mix(in srgb, var(--gh-primary) 6%, var(--gh-bg)) !important;\n\n /* 3. 全局核心文字 */\n --bard-color-lm-on-surface: var(--gh-text) !important;\n --bard-color-sentence-prefix-color: var(--gh-text) !important;\n --bard-color-lm-on-surface-variant: var(--gh-text-secondary) !important;\n --bard-color-sentence-words-color: var(--gh-text-secondary) !important;\n --bard-color-image-lightbox-text: var(--gh-text-tertiary) !important;\n --bard-color-code-comment: var(--gh-text-tertiary) !important;\n\n /* 4. 品牌高亮与强调色(绑定我们插件的主题色段) */\n --bard-color-surface-tint: var(--gh-primary) !important;\n --bard-color-form-field-outline-active: var(--gh-primary) !important;\n --bard-color-brand-text-gradient-stop-1: var(--gh-primary) !important;\n --bard-color-chrome-experiment-badge: var(--gh-primary) !important;\n --bard-color-share-link: var(--gh-primary) !important;\n\n /* 5. 分叉对话、状态卡片相关 */\n --bard-color-zero-state-card-selected: var(--gh-active-bg) !important;\n --bard-color-zero-state-prompt-chip-background: var(--gh-hover) !important;\n\n /* 6. 其他元素 */\n --gem-sys-color--primary: var(--gh-primary) !important;\n /* 图标颜色 */\n --mat-icon-color: var(--gh-primary) !important;\n}\n\n/* 仅在 AI 回复容器内覆盖 surface-container-high(用于代码块背景),\n * 不在 :root 全局设置,以免影响用户气泡等其他使用该变量的元素 */\nmodel-response, .model-response-container {\n --gem-sys-color--surface-container-high: var(--gh-bg-tertiary) !important;\n}"}getNewTabUrl(){return `https://gemini.google.com${this.getUserPathPrefix()}/app`}isNewConversation(){const e=window.location.pathname.replace(/^\/u\/\d+/,"");if("/app"===e||"/app/"===e)return true;if("/gems/create"===e||"/gems/create/"===e)return true;if(e.startsWith("/gems/edit/"))return true;if(e.startsWith("/gem/")){return e.split("/").filter(Boolean).length<=2}return false}isUserConversationPage(){const e=window.location.pathname.replace(/^\/u\/\d+(?=\/)/,"");return !this.isSharePage()&&(/^\/app\/[^/?#]+(?:\/|$)/i.test(e)||/^\/gem\/[^/?#]+\/[^/?#]+(?:\/|$)/i.test(e))}getConversationList(){const e=os.query('gem-nav-list-item[data-test-id="conversation"]',{all:true})||[],t=this.getCurrentCid(),n=this.getUserPathPrefix();return Array.from(e).map(e=>{const r=e.querySelector("a"),o=(r?.getAttribute("jslog")||e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),i=o?o[1]:"",a=e.querySelector(".title-text")?.textContent?.trim()||"",s=!!e.querySelector('mat-icon[fonticon="push_pin"]'),l=r?.classList.contains("mdc-list-item--activated")||false;return {id:i,cid:t,title:a,url:i?`https://gemini.google.com${n}/app/${i}`:"",isActive:l,isPinned:s}}).filter(e=>e.id)}getSidebarScrollContainer(){return os.query('infinite-scroller[scrollable="true"]')||os.query("infinite-scroller")||this.getChatsScrollableContainer()}async loadAllConversations(){if(!(await this.ensureChatsExpandableSectionOpen()))return false;const e=this.getSidebarScrollContainer();if(!e)return false;let t=0,n=0,r=0;for(let o=0;o<40;o++){e.scrollTop=e.scrollHeight,await this.sleep(900);const o=(os.query('gem-nav-list-item[data-test-id="conversation"]',{all:true,shadow:true})||[]).length;if(o===t?n++:(t=o,n=0),this.isConversationHistoryLoading()?r=0:r++,n>=4&&r>=2)return o>0}return false}async ensureChatsExpandableSectionOpen(e=2500){if(this.getConversationList().length>0)return true;const t=this.getChatsExpandableSection();if(!t)return false;t.click();const n=Date.now();for(;Date.now()-n0)return true;await this.sleep(100);}return this.getConversationList().length>0}getChatsExpandableSection(){const e=[wm,xm];for(const o of e){const e=document.querySelector(o);if(e instanceof HTMLElement)return e}const t=document.querySelector('conversations-list[data-test-id="all-conversations"]'),n=t?.closest("expandable-section");if(n instanceof HTMLElement)return n;const r=document.getElementsByTagName("expandable-section")[0];return r instanceof HTMLElement?r:null}isConversationHistoryLoading(){const e=document.querySelector('[data-test-id="loading-history-spinner"]');return e instanceof HTMLElement&&this.isVisible(e)}getChatsScrollableContainer(){const e=document.querySelector(['conversations-list[data-test-id="all-conversations"]',wm,xm,'gem-nav-list-item[data-test-id="conversation"]'].join(","));if(!(e instanceof HTMLElement))return null;let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if((/(auto|scroll|overlay)/i.test(e.overflowY)||t.classList.contains("chat-history"))&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}getConversationObserverConfig(){return {selector:'gem-nav-list-item[data-test-id="conversation"]',shadow:false,extractInfo:e=>{const t=e.querySelector("a"),n=(t?.getAttribute("jslog")||e.getAttribute("jslog")||"").match(/\["c_([^"]+)"/),r=n?n[1]:"";if(!r)return null;const o=e.querySelector(".title-text")?.textContent?.trim()||"",i=!!e.querySelector('mat-icon[fonticon="push_pin"]');return {id:r,cid:this.getCurrentCid(),title:o,url:`https://gemini.google.com${this.getUserPathPrefix()}/app/${r}`,isPinned:i}},getTitleElement:e=>e.querySelector(".title-text")||e}}navigateToConversation(e,t){const n=document.querySelector(`gem-nav-list-item[data-test-id="conversation"] a[jslog*="${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Bp}}catch(t){return console.error(`[GeminiAdapter] deleteConversationOnSiteInternal error for "${e.id}":`,t),{id:e.id,success:false,method:"none",reason:Op}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let n=await this.findConversationMenuButton(t);if(!n)return false;const r=await this.openConversationMenu(t,n);if(!r)return false;const o=await this.waitForDeleteMenuItem(n,2500,r);if(!o)return document.body.click(),false;this.simulateClick(o);if(!(await this.waitForDialogOpen(2200)))return false;const i=await this.waitForDeleteConfirmButton(2800);if(!i)return false;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4500),s=await this.waitForDialogClosed(1200),l=a||s;return l&&this.syncConversationListAfterDelete(e),l}async openConversationMenu(e,t){let n=t;for(let r=0;r<4;r++){if(document.body.click(),await this.sleep(60),this.revealConversationActions(e),n&&n.isConnected||(n=await this.findConversationMenuButton(e)),!n)return null;this.simulateClick(n);const t=await this.waitForMenuOpen(n,900);if(t)return t}return null}async waitForMenuOpen(e,t=900){const n=Date.now();for(;Date.now()-nthis.revealConversationActions(e));const o=r.flatMap(e=>Array.from(e.querySelectorAll(t))).filter(e=>!(e instanceof HTMLButtonElement&&e.disabled));if(o.length>0){const t=o.find(e=>null!==e.querySelector('mat-icon[fonticon="more_vert"], mat-icon[fonticon="more_horiz"]'));if(t)return t;const r=o.find(t=>this.isLikelyMenuButton(t,e));if(r)return r;const i=o.filter(e=>this.isVisible(e)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(i)return i;if(n>=8){const e=o[o.length-1];if(e)return e}}await this.sleep(100);}return null}getMenuSearchScopes(e){const t=[e,e.parentElement,e.parentElement?.parentElement,e.closest("li")].filter(e=>e instanceof HTMLElement),n=new Set,r=[];for(const o of t)n.has(o)||(n.add(o),r.push(o));return r}isLikelyMenuButton(e,t){if(!t.contains(e))return false;if("menu"===e.getAttribute("aria-haspopup"))return true;const n=this.getSignalText(e);return n.includes("more")||n.includes("更多")||n.includes("选项")||n.includes("menu")||n.includes("菜单")}async waitForDeleteMenuItem(e,t=2500,n){const r=Date.now();let o=[];for(;Date.now()-rthis.isVisible(e));r.length>0&&(o=r),await this.sleep(80);}if(o.length>0){const e=o[o.length-1],t=this.getSignalText(e);if(!this.hasKeyword(t,Up))return e}return null}getMenuActionCandidates(e,t){const n='[role="menuitem"], [role="menu"] button, .mat-mdc-menu-panel button',r=[];t&&r.push(...Array.from(t.querySelectorAll(n)));const o=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(o){const e=document.getElementById(o);e&&r.push(...Array.from(e.querySelectorAll(n)));}const i=this.findVisibleMenuContainer();i&&r.push(...Array.from(i.querySelectorAll(n))),r.push(...this.findAllElementsBySelector(n));const a=new Set,s=[];for(const l of r)a.has(l)||(a.add(l),s.push(l));return s}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(!t)return null;const n=document.getElementById(t);return n instanceof HTMLElement?n:null}findVisibleMenuContainer(){const e=Array.from(document.querySelectorAll('[role="menu"], .mat-mdc-menu-panel, .mat-menu-panel')).filter(e=>this.isVisible(e));return 0===e.length?null:e[e.length-1]}async waitForDialogOpen(e=2200){const t=Date.now();for(;Date.now()-tthis.isVisible(e));for(const o of n){const e=this.getSignalText(o);if(this.hasKeyword(e,$p)&&!this.hasKeyword(e,Up))return o}const r=n.filter(e=>!this.hasKeyword(this.getSignalText(e),Up)).sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];if(r)return r;await this.sleep(80);}return null}async waitForDialogClosed(e=1200){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=4500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}getSessionName(){const e=document.querySelector("a.mdc-list-item--activated .title-text");if(e){const t=e.textContent?.trim();if(t)return t}const t=this.getDeepResearchDocumentShareTitle();if(t)return t;const n=document.querySelector("h1.headline, h1[class*='headline']");if(n){const e=n.textContent?.trim();if(e)return e}const r=this.getDeepResearchArtifactShareTitle();return r||super.getSessionName()}getConversationTitle(){const e=document.querySelector("a.mdc-list-item--activated .title-text");if(e){const t=e.textContent?.trim();if(t)return t}return this.getSessionName()}getNewChatButtonSelectors(){return ['gem-nav-list-item[data-test-id="new-chat-button"] a','[aria-label="New chat"]','[aria-label="新对话"]','[aria-label="发起新对话"]','[data-testid="new-chat-button"]','[data-test-id="new-chat-button"]','[data-test-id="expanded-button"]','[data-test-id="temp-chat-button"]','button[aria-label="临时对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll("model-response");if(0===t.length)return null;const n=t[t.length-1];return this.extractAssistantResponseText(n)||null}getWidthSelectors(){return [{selector:".conversation-container",property:"max-width"},{selector:".input-area-container",property:"max-width"},{selector:".table-block.new-table-style",property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important;"},{selector:"user-query",property:"max-width",value:"100%",noCenter:true,extraCss:"display: flex !important; justify-content: flex-end !important;"},{selector:".user-query-container",property:"max-width",value:"100%",noCenter:true,extraCss:"justify-content: flex-end !important;"}]}getUserQueryWidthSelectors(){return [{selector:".user-query-bubble-with-background:not(.edit-mode)",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["bard-sidenav","div.sidenav-with-history-container"]}}getCleanModeConfig(){return {hide:["hallucination-disclaimer","g1-dynamic-upsell-button",".share-viewer_footer_disclaimer",".share-landing-page_footer",'share-landing-page immersive-share-landing-page .page:has(structured-content-container[data-test-id="deep-research-block"]) > .footer']}}getMarkdownFixerConfig(){return {selector:"message-content p",fixSpanContent:false,shouldIgnore:e=>this.shouldIgnoreMarkdownFixElement(e)}}shouldIgnoreMarkdownFixElement(e){return null!==e.querySelector(km)}getAssistantMermaidSupportMode(){return "fallback"}getTextareaSelectors(){return ['div[contenteditable="true"].ql-editor','div[contenteditable="true"]','[role="textbox"]','[aria-label*="Enter a prompt"]']}getSubmitButtonSelectors(){return ['button[aria-label*="Send"]','button[aria-label*="发送"]',".send-button",'[data-testid*="send"]']}isValidTextarea(e){if(null===e.offsetParent)return false;const t="true"===e.getAttribute("contenteditable"),n="textbox"===e.getAttribute("role");return !e.closest(".gh-main-panel")&&(t||n||e.classList.contains("ql-editor"))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}));}return true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),(document.activeElement===this.textarea||this.textarea.contains(document.activeElement))&&(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0))):this.textarea=null);}getScrollContainer(){return this.isSharePage()?document.querySelector("div.content-container"):document.querySelector("infinite-scroller.chat-history")}getResponseContainerSelector(){return this.isSharePage()?"div.content-container":"infinite-scroller.chat-history"}getChatContentSelectors(){return [".model-response-container","model-response",".response-container","[data-message-id]","message-content"]}getUserQuerySelector(){return "user-query"}getOutlineSources(){const e=[{id:"conversation",kind:"conversation",label:"对话",available:true}],t=this.extractDeepResearchDocumentOutline(6,false);return t.length>0&&e.push({id:um,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=null!==this.getDeepResearchDocumentOutlineRoot();return `conversation:1|${um}:${e?1:0}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===um?this.extractDeepResearchDocumentOutline(t,r):this.extractOutline(t,n,r)}sanitizeUserQueryElement(e){const t=e.cloneNode(true);return t.querySelectorAll(".cdk-visually-hidden").forEach(e=>e.remove()),t}extractUserQueryText(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelector(".query-text")||t;return this.extractTextWithLineBreaks(n)}extractUserQueryMarkdown(e){const t=this.sanitizeUserQueryElement(e),n=t.querySelectorAll(".query-text-line");if(0===n.length)return this.extractUserQueryText(t);const r=Array.from(n).map(e=>e.querySelector("br")&&""===e.textContent?.trim()?"":e.textContent?.trimEnd()??""),o=r.filter(e=>""!==e.trim());if(o.length>0){const e=o.reduce((e,t)=>{const n=t.match(/^(\s*)/);return Math.min(e,n?n[1].length:0)},1/0);if(e>0&&isFinite(e))return r.map(t=>""===t?"":t.slice(e)).join("\n")}return r.join("\n")}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}extractUserQueryExportContentWithAssets(e,t){const n=this.sanitizeUserQueryElement(e),r=this.extractUserQueryImageMarkdown(n,t),o=this.extractUserQueryFileMarkdown(n,t),i=this.extractUserQueryMarkdown(n).trim()||this.extractUserQueryText(n).trim();if(0===r.length&&0===o.length)return i;const a=o.length>0?`${se("exportAttachmentsLabel")}:\n${o.join("\n")}`:"";return [r.join("\n\n"),a,i].filter(Boolean).join("\n\n")}async extractUserQueryExportContentWithResolvedAssets(e,t){const n=this.sanitizeUserQueryElement(e),r=this.extractUserQueryImageMarkdown(n,t),o=await this.extractUserQueryFileMarkdownWithResolvedAssets(e,n,t),i=this.extractUserQueryMarkdown(n).trim()||this.extractUserQueryText(n).trim();if(0===r.length&&0===o.length)return i;const a=o.length>0?`${se("exportAttachmentsLabel")}:\n${o.join("\n")}`:"";return [r.join("\n\n"),a,i].filter(Boolean).join("\n\n")}async prepareConversationExport(e){this.exportOpenedCanvasPanel=false,await this.prepareImagesForExport(e);const t={openedDeepResearchPanel:false};return this.isDeepResearchAppPage()&&!this.getDeepResearchAppDocumentElement()&&(t.openedDeepResearchPanel=await this.openDeepResearchAppDocumentPanel()),t}async restoreConversationAfterExport(e,t){this.clearPreparedExportImageMetadata(),this.isGeminiExportLifecycleState(t)&&t.openedDeepResearchPanel&&await this.closeDeepResearchAppDocumentPanel(),this.exportOpenedCanvasPanel&&(await this.closeGeminiCanvasPanel(),this.exportOpenedCanvasPanel=false);}async prepareImagesForExport(e){this.clearPreparedExportImageMetadata();const t=Array.from(document.querySelectorAll(`model-response ${Qp} img, ${Vp}`)).filter(e=>e instanceof HTMLImageElement);for(const r of t)try{const t=await this.resolvePreparedExportImageSrc(r,e);if(!t)continue;r.setAttribute(jp,t);}catch(n){console.warn("[GeminiAdapter] Failed to prepare export image source",n);}}clearPreparedExportImageMetadata(){document.querySelectorAll(`[${jp}]`).forEach(e=>{e.removeAttribute(jp);});}extractUserQueryImageMarkdown(e,t){const n=Array.from(e.querySelectorAll("img[data-test-id='uploaded-img'], .preview-image")).filter(e=>e instanceof HTMLImageElement),r=[],o=new Set;for(const i of n){const e=this.getPreparedExportImageSrc(i);if(!e||o.has(e))continue;o.add(e);const n=(i.alt||"uploaded image").replace(/\s+/g," ").trim().replace(/[[\]]/g,"\\$&"),a=t?this.addImageExportAsset(t,e,n||"uploaded image"):e;r.push(`![${n||"uploaded image"}](${a})`);}return r}addImageExportAsset(e,t,n){const r=e.imagePathsBySource.get(t);if(r)return r;const o=e.imagePathsBySource.size+1,i=this.getImageExportExtension(t),a=`gemini-image-${String(o).padStart(3,"0")}.${i}`,s=this.createUniqueGeminiExportPath(`assets/images/${a}`,e),l=s.split("/").pop()||a;return e.imagePathsBySource.set(t,s),e.assets.push({id:`gemini-image-${o}`,name:l,relativePath:s,mimeType:this.getImageExportMimeType(t,i),kind:"image",content:t.startsWith("data:image/")?this.dataUrlToExportBlob(t):void 0,sourceUrl:t.startsWith("data:image/")?void 0:t,description:n}),s}getImageExportExtension(e){if(e.startsWith("data:image/")){const t=e.match(/^data:image\/([a-zA-Z0-9.+-]+)[;,]/);return this.normalizeImageExtension(t?.[1]||"png")}try{const t=new URL(e,window.location.href).pathname,n=t.match(/\.([a-zA-Z0-9]+)$/)?.[1];return this.normalizeImageExtension(n||"png")}catch{return "png"}}normalizeImageExtension(e){const t=e.toLowerCase().replace(/^jpg$/,"jpeg").replace(/^svg\+xml$/,"svg");return ["png","jpeg","webp","gif","avif","svg"].includes(t)?"jpeg"===t?"jpg":t:"png"}getImageExportMimeType(e,t){return e.startsWith("data:image/")?e.slice(5,e.indexOf(";")):"svg"===t?"image/svg+xml":"jpg"===t?"image/jpeg":`image/${t}`}dataUrlToExportBlob(e){const[t,n=""]=e.split(",",2),r=t.match(/^data:([^;]+)/)?.[1]||"application/octet-stream";if(!/;base64/i.test(t))return new Blob([decodeURIComponent(n)],{type:r});const o=atob(n),i=new Uint8Array(o.length);for(let a=0;a"document"===e.kind&&e.name===o&&e.content===t);if(i?.relativePath)return i.relativePath;const a=this.createUniqueGeminiExportPath(`assets/documents/${o}`,e),s=a.split("/").pop()||o;return e.assets.push({id:`gemini-document-${e.assets.length+1}`,name:s,relativePath:a,mimeType:r||this.getExportAssetMimeType("",s,"document"),kind:"document",content:t,description:n||void 0}),a}async extractUserQueryViewerDocument(e,t){const n=this.getUserQueryFilePreviewTrigger(e);if(!n)return null;const r=document.querySelector("immersive-panel .drive-viewer");n.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),this.simulateClick(n);const o=await this.waitForDriveViewer(r)||r;if(!o)return null;try{const e=await this.waitForDriveViewerDocument(o,t);return e||console.warn("[GeminiAdapter] Failed to extract uploaded file viewer document",{name:t,viewerTextContainers:document.querySelectorAll("immersive-panel .drive-viewer-text-content").length,visibleViewers:Array.from(document.querySelectorAll("immersive-panel .drive-viewer")).filter(e=>this.isVisible(e)).length}),e?{name:e.name||t,mimeType:e.mimeType,content:e.content}:null}finally{await this.closeDriveViewer(o);}}getUserQueryFilePreviewTrigger(e){return [e.matches("button, [role='button']")?e:null,e.querySelector("button"),e.querySelector("[role='button']")].find(e=>e instanceof HTMLElement)||null}async waitForDriveViewer(e,t=3e3){const n=Date.now();for(;Date.now()-nt!==e);if(n)return n;if(!e&&t[0])return t[0];await new Promise(e=>setTimeout(e,100));}return null}async waitForDriveViewerDocument(e,t,n=5e3){const r=Date.now();for(;Date.now()-rthis.isVisible(e)))return null;await new Promise(e=>setTimeout(e,100));}return null}findActiveDriveViewerTextContent(e){const t=Array.from(document.querySelectorAll("immersive-panel .drive-viewer")),n=e.replace(/\.[A-Za-z0-9]{1,10}$/,""),r=t.find(t=>{const r=this.extractDriveViewerDocumentName(t);return r===e||r===n||r.startsWith(`${n}.`)||e.startsWith(`${r}.`)})||t[t.length-1],o=Array.from((r||document).querySelectorAll(".drive-viewer-text-content pre, .drive-viewer-text-content"));return o.find(e=>this.isVisible(e))||o.find(e=>this.decodeDriveViewerText(e.textContent||""))||null}decodeDriveViewerText(e){return e.replace(/\r\n/g,"\n").trim()}extractDriveViewerDocumentName(e){const t=this.parseDriveActiveItemInfo(e),n=this.getNormalizedText(e.querySelector(".drive-viewer-toolstrip-name"));return t?.title||n||""}extractDriveViewerDocumentMimeType(e){return this.parseDriveActiveItemInfo(e)?.mimeType}parseDriveActiveItemInfo(e){const t=Array.from(e.querySelectorAll('[id="drive-active-item-info"], div[style*="display:none"]')).map(e=>e.textContent?.trim()||"").find(e=>e.startsWith("{")&&e.includes('"title"'));if(!t)return null;try{const e=JSON.parse(t);return e&&"object"==typeof e?e:null}catch{return null}}async closeDriveViewer(e){const t=e.querySelector(".drive-viewer-close-button");t instanceof HTMLElement&&(this.simulateClick(t),await new Promise(e=>setTimeout(e,150)));}addFileExportAsset(e,t,n,r,o="file"){const i=e.filePathsBySource.get(t);if(i)return i;const a=this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(n||"gemini-file"),t,r),s=this.createUniqueGeminiExportPath(`assets/files/${a}`,e),l=s.split("/").pop()||a,c=this.getExportAssetMimeType(t,r||l,o);return e.filePathsBySource.set(t,s),e.assets.push({id:`gemini-${o||"file"}-${e.filePathsBySource.size}`,name:l,relativePath:s,mimeType:c,kind:o,content:t.startsWith("data:")?this.dataUrlToExportBlob(t):void 0,sourceUrl:t.startsWith("data:")?void 0:t,description:n||void 0}),s}sanitizeGeminiExportFilename(e){return e.replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/\s+/g," ").trim().substring(0,120)}ensureExportFilenameExtension(e,t,n){const r=e||"gemini-file";if(/\.[A-Za-z0-9]{1,10}$/.test(r))return r;const o=this.getExportAssetExtension(t)||this.getExtensionFromMimeType(n||"");return o?`${r}.${o}`:r}getExportAssetExtension(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;,]+)/)?.[1]||"";return this.getExtensionFromMimeType(t)}try{const t=new URL(e,window.location.href).pathname;return t.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toLowerCase()||""}catch{return ""}}getExportAssetMimeType(e,t,n){if(e.startsWith("data:"))return e.match(/^data:([^;,]+)/)?.[1]||void 0;const r=t.toLowerCase(),o=r.match(/\.([a-z0-9]{1,10})$/)?.[1]||r,i=o?this.getMimeTypeFromExtension(o):"";return i||("audio"===n?"audio/mpeg":"video"===n?"video/mp4":void 0)}getMimeTypeFromExtension(e){return {avif:"image/avif",csv:"text/csv",gif:"image/gif",htm:"text/html",html:"text/html",jpeg:"image/jpeg",jpg:"image/jpeg",json:"application/json",m4a:"audio/mp4",md:"text/markdown;charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",ogg:"audio/ogg",pdf:"application/pdf",png:"image/png",txt:"text/plain;charset=utf-8",wav:"audio/wav",webm:"video/webm",webp:"image/webp"}[e.toLowerCase()]||""}getExtensionFromMimeType(e){return {"application/json":"json","application/pdf":"pdf","audio/mpeg":"mp3","audio/mp4":"m4a","audio/ogg":"ogg","audio/wav":"wav","image/avif":"avif","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/svg+xml":"svg","image/webp":"webp","text/csv":"csv","text/html":"html","text/markdown":"md","text/plain":"txt","video/mp4":"mp4","video/webm":"webm"}[e.toLowerCase().split(";")[0].trim()]||""}extractUserQueryFileName(e){const t=this.extractUserQueryFileAriaName(e);if(t)return t;return [this.getNormalizedText(e.querySelector('[data-test-id="filename-label"]')),this.getNormalizedText(e.querySelector(".filename-label")),this.getNormalizedText(e.querySelector(".new-file-name"))].find(Boolean)||""}extractUserQueryFileAriaName(e){return Array.from(e.querySelectorAll("a[aria-label], button[aria-label]")).map(e=>e.getAttribute("aria-label")||"").map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).find(e=>!Gp.test(e))||""}extractUserQueryFileType(e){const t=this.getNormalizedText(e.querySelector(".new-file-type"));if(t)return t;const n=e.querySelector('[data-test-id="luminous-file-icon"]')?.getAttribute("alt");return (n||"").replace(/icon|图标|圖標|アイコン|아이콘|símbolo|ícone|symbol|значок/gi,"").replace(/\s+/g," ").trim()}fileNameEndsWithType(e,t){const n=e.toLowerCase(),r=t.replace(/^\./,"").toLowerCase();return !!r&&n.endsWith(`.${r}`)}extractUserQueryFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=this.normalizeExportAssetUrl(n.href||n.getAttribute("href")||"");if(this.isDownloadableExportAssetUrl(e))return e}return ""}escapeMarkdownLinkText(e){return e.replace(/[[\]]/g,"\\$&")}getPreparedExportImageSrc(e){const t=[e.getAttribute(jp)||"",e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=this.normalizeExportImageUrl(n);if(this.isStablePreparedExportImageUrl(e))return e}return ""}async resolvePreparedExportImageSrc(e,t){const n=[this.getPreparedExportImageSrc(e)],r=[e.getAttribute(jp)||"",e.getAttribute("data-ophel-wm-source")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const i of n){const n=this.normalizeExportImageUrl(i);if(n){if(this.shouldInlineUserQueryImageForExport(e,t))return this.resolveExportImageDataUrl(n);if(this.isStablePreparedExportImageUrl(n))return n}}const o=r.map(e=>this.normalizeExportImageUrl(e)).find(e=>e.startsWith("blob:"));return o?this.convertBlobUrlToDataUrl(o):""}shouldInlineUserQueryImageForExport(e,t){return "markdown"===t.format&&"markdown"===t.packaging&&null!==e.closest("user-query")}async resolveExportImageDataUrl(e){if(e.startsWith("data:image/"))return e;if(e.startsWith("blob:"))return this.convertBlobUrlToDataUrl(e);if(!/^https?:\/\//i.test(e))return "";try{const t=await qi.fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.blob();return this.convertBlobToDataUrl(n)}catch(t){return console.warn("[GeminiAdapter] Failed to inline user query image for Markdown export",t),e}}normalizeExportImageUrl(e){if(!e)return "";if(e.startsWith("blob:")||e.startsWith("data:image/"))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}normalizeExportAssetUrl(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}isDownloadableExportAssetUrl(e){if(!e)return false;if(/^(blob:|data:)/i.test(e))return true;if(!/^https?:\/\//i.test(e))return false;try{const t=new URL(e);return (t.hostname!==window.location.hostname||!/^\/?(app|share)(\/|$)/.test(t.pathname))&&!/faviconV2|google_logo_icon|\/32\/type\//i.test(t.href)}catch{return false}}isStablePreparedExportImageUrl(e){return !!e&&(!!e.startsWith("data:image/")||(!!vm.test(e)||/^https?:\/\//i.test(e)))}async convertBlobUrlToDataUrl(e){const t=await fetch(e),n=await t.blob();return this.convertBlobToDataUrl(n)}async convertBlobToDataUrl(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{"string"!=typeof r.result?n(new Error("Failed to convert blob image to data URL")):t(r.result);},r.onerror=()=>n(r.error||new Error("Failed to read blob image")),r.readAsDataURL(e);})}sanitizeAssistantExportElement(e){const t=e.cloneNode(true);return t.querySelectorAll(hm).forEach(e=>e.remove()),this.normalizeDeepResearchConfirmationWidgetsForExport(t),this.normalizeAssistantGeneratedImagesForExport(t),t}normalizeDeepResearchConfirmationWidgetsForExport(e){e.querySelectorAll(tm).forEach(e=>{const t=document.createElement("div");t.className="ophel-gemini-deep-research-plan";const n=this.getNormalizedText(e.querySelector('[data-test-id="title"]'));if(n){const e=document.createElement("h3");e.textContent=n,t.appendChild(e);}Array.from(e.querySelectorAll('[data-test-id="research-steps"] .research-step')).forEach((e,n)=>{const r=this.extractDeepResearchStepTitle(e);if(r){const e=document.createElement("h4");e.textContent=`${n+1}. ${r}`,t.appendChild(e);}const o=this.normalizeExportMultilineText(e.querySelector(".research-step-description")?.textContent||"");if(o){const e=document.createElement("p");e.textContent=o,t.appendChild(e);}}),t.childNodes.length>0&&e.replaceWith(t);});}extractDeepResearchStepTitle(e){const t=e.querySelector(".research-step-title"),n=Array.from(t?.children||[]).find(e=>"mat-icon"!==e.tagName.toLowerCase());return this.getNormalizedText(n||t)}getNormalizedText(e){return (e?.textContent||"").replace(/\s+/g," ").trim()}normalizeExportMultilineText(e){return e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.trimEnd()).join("\n").replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}normalizeAssistantGeneratedImagesForExport(e){e.querySelectorAll(gm).forEach(e=>e.remove()),e.querySelectorAll(`img[${jp}]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=e.getAttribute(jp)||"";t&&(e.setAttribute("src",t),e.removeAttribute("srcset"),e.removeAttribute(jp));}),e.querySelectorAll(`${Qp} button.image-button`).forEach(e=>{if(!(e instanceof HTMLButtonElement&&e.parentNode))return;const t=e.querySelector("img");if(!(t instanceof HTMLImageElement))return;const n=t.cloneNode(true),r=n.getAttribute(jp)||"";r&&(n.setAttribute("src",r),n.removeAttribute("srcset"),n.removeAttribute(jp)),e.replaceWith(n);}),e.querySelectorAll("share-button, copy-button, download-generated-image-button, .generated-image-controls, .loader").forEach(e=>e.remove());}shouldSkipOutlineHeading(e){return !!this.isInRenderedMarkdownContainer(e)||!!e.classList.contains("cdk-visually-hidden")}getDeepResearchDocumentOutlineRoot(){const e=this.getDeepResearchAppDocumentElement();return e||(this.isDeepResearchDocumentSharePage()?document.querySelector(`${Jp} ${em}`):this.isDeepResearchConversationSharePage()?document.querySelector(`${Xp} ${em}`):null)}extractDeepResearchDocumentOutline(e=6,t=false){const n=this.getDeepResearchDocumentOutlineRoot();return n?vl(n,{maxLevel:e,showWordCount:t,idPrefix:"gemini-document",shouldSkipHeading:e=>this.shouldSkipOutlineHeading(e),calculateWordCount:(e,t,n)=>this.calculateRangeWordCount(e,t,n)}):[]}findDeepResearchDocumentHeading(e,t){const n=this.getDeepResearchDocumentOutlineRoot();return n?wl(n,e,t,e=>this.shouldSkipOutlineHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===um){return xl(this.getDeepResearchDocumentOutlineRoot())||null}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===um?this.findDeepResearchDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===um){if(kl(e,xl(e)||this.getOutlineScrollContainer(t)))return}this.scrollToOutlineTarget(e);}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantResponseTextWithAssets(e,t){const n=this.sanitizeAssistantExportElement(e);return t&&(this.replaceAssistantImageSourcesWithExportAssets(n,t),this.replaceAssistantMediaSourcesWithExportAssets(n,t),this.replaceAssistantDownloadLinksWithExportAssets(n,t)),this.extractMarkdownExportContent(n)}async extractExportMessages(e){return this.isDeepResearchDocumentSharePage()?this.extractDeepResearchDocumentShareMessages():this.isDeepResearchConversationSharePage()?this.extractDeepResearchConversationShareMessages():this.isGeminiConversationSharePage()?this.extractGeminiConversationShareMessages():this.isDeepResearchAppPage()?this.extractDeepResearchAppMessages():this.hasGeminiCanvasAppArtifacts()?this.extractGeminiConversationMessages():null}async extractExportBundle(e){const t={assets:[],imagePathsBySource:new Map,filePathsBySource:new Map,usedPaths:new Set},n=await this.extractExportMessagesWithAssets(e,t);return n?{messages:n,assets:t.assets}:null}async extractExportMessagesWithAssets(e,t){return this.isDeepResearchDocumentSharePage()?this.extractDeepResearchDocumentShareMessages(t):this.isDeepResearchConversationSharePage()?this.extractDeepResearchConversationShareMessages(t):this.isGeminiConversationSharePage()?this.extractGeminiConversationShareMessages(t):this.isDeepResearchAppPage()?this.extractDeepResearchAppMessages(t):this.extractGeminiConversationMessages(t)}async extractGeminiConversationMessages(e){const t=document.querySelector(this.getResponseContainerSelector())||this.getScrollContainer();if(!t)return null;const n=Array.from(t.querySelectorAll("user-query, model-response")).sort((e,t)=>this.compareDomOrder(e,t));if(0===n.length)return null;const r=[];for(const i of n){if(i.closest("immersive-panel"))continue;const t="user-query"===i.tagName.toLowerCase()?"user":"assistant",n="user"===t?(e?await this.extractUserQueryExportContentWithResolvedAssets(i,e):this.extractUserQueryExportContentWithAssets(i)).trim():this.joinExportSections(this.extractAssistantResponseTextWithAssets(i,e),await this.extractGeminiCanvasAppArtifactsFromResponse(i));n&&r.push({role:t,content:n});}const o=this.dedupeAdjacentExportMessages(r);return o.length>0?o:null}replaceAssistantImageSourcesWithExportAssets(e,t){Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement).forEach(e=>{if(this.isDecorativeExportImage(e))return;const n=this.getPreparedExportImageSrc(e);if(!n)return;const r=(e.alt||"image").replace(/\s+/g," ").trim(),o=this.addImageExportAsset(t,n,r);e.setAttribute("src",o),e.removeAttribute("srcset");});}replaceAssistantMediaSourcesWithExportAssets(e,t){Array.from(e.querySelectorAll("audio, video")).filter(e=>e instanceof HTMLMediaElement).forEach(e=>{const n=this.extractAssistantMediaSource(e);if(!n)return;const r="video"===e.tagName.toLowerCase()?"video":"audio",o=this.buildAssistantMediaAssetName(e,r,n.source),i=this.addFileExportAsset(t,n.source,o,n.mimeType,r);e.replaceWith(this.createExportAssetLinkElement(o,i));});}replaceAssistantDownloadLinksWithExportAssets(e,t){Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement).forEach(e=>{if(!this.isAssistantExportDownloadLink(e))return;const n=this.normalizeExportAssetUrl(e.getAttribute("href")||e.href||"");if(!this.isDownloadableExportAssetUrl(n))return;const r=this.buildAssistantDownloadAssetName(e,n),o=this.inferExportAssetKind(n,r),i=this.addFileExportAsset(t,n,r,void 0,o);e.setAttribute("href",i),e.setAttribute(Oi,i),e.removeAttribute("target"),e.removeAttribute("rel");});}extractAssistantMediaSource(e){const t=[e.currentSrc||"",e.getAttribute("src")||"","src"in e?String(e.src||""):""],n=Array.from(e.querySelectorAll("source[src]")).filter(e=>e instanceof HTMLSourceElement),r=[...t.map(t=>({source:t,mimeType:e.getAttribute("type")||""})),...n.map(e=>({source:e.getAttribute("src")||e.src||"",mimeType:e.type||""}))];for(const o of r){const e=this.normalizeExportAssetUrl(o.source);if(this.isDownloadableExportAssetUrl(e))return {source:e,mimeType:o.mimeType||void 0}}return null}buildAssistantMediaAssetName(e,t,n){const r=e.getAttribute("aria-label")||e.getAttribute("title")||("video"===t?"gemini-video":"gemini-audio");return this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(r),n)}buildAssistantDownloadAssetName(e,t){const n=e.getAttribute("download")||e.getAttribute("aria-label")||e.getAttribute("title")||e.textContent||"gemini-file";return this.ensureExportFilenameExtension(this.sanitizeGeminiExportFilename(n),t)}createExportAssetLinkElement(e,t){const n=document.createElement("p"),r=document.createElement("a");return r.setAttribute("href",t),r.setAttribute(Oi,t),r.textContent=e,n.appendChild(r),n}isAssistantExportDownloadLink(e){if(e.getAttribute("href")?.startsWith("assets/"))return false;if(e.hasAttribute("download"))return true;const t=[e.getAttribute("data-test-id")||"",e.getAttribute("data-testid")||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.className||""].join(" ").toLowerCase();if(!/(download|attachment|file|document|audio|video|下载|下載)/i.test(t))return false;const n=this.normalizeExportAssetUrl(e.getAttribute("href")||e.href||"");return this.isDownloadableExportAssetUrl(n)}inferExportAssetKind(e,t){const n=(this.getExportAssetExtension(e)||t.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"").toLowerCase();return ["mp3","m4a","ogg","wav"].includes(n)?"audio":["mp4","webm"].includes(n)?"video":["md","pdf","txt","csv","json","html","htm"].includes(n)?"document":"file"}isDecorativeExportImage(e){if(e.matches(gm))return true;const t=this.getPreparedExportImageSrc(e);if(!t)return true;const n=e.className||"",r=e.getAttribute("data-test-id")||"";if("presentation"===(e.getAttribute("role")||"")&&/(^|\s)(favicon|icon|google-icon)(\s|$)/.test(String(n))&&/favicon|icon|file/i.test(r))return true;return !("image/svg+xml"!==(t.startsWith("data:image/")?t.slice(5,t.indexOf(";")).toLowerCase():"")||!e.classList.contains("katex-svg"))}hasGeminiCanvasAppArtifacts(){if(this.isSharePage())return false;const e=document.querySelector(this.getResponseContainerSelector())||this.getScrollContainer();return !!e&&this.getGeminiCanvasCardsFromResponse(e).length>0}getGeminiCanvasCardsFromResponse(e){return Array.from(e.querySelectorAll('[data-test-id="gem-processing-card"]')).filter(e=>e instanceof HTMLElement&&null!==e.querySelector(im))}getGeminiCanvasShareArtifactElements(e){const t=new Set;return e instanceof Element&&e.classList.contains("immersive-artifact-container")&&t.add(e),e.querySelectorAll("share-landing-page .immersive-artifact-container, .immersive-artifact-container").forEach(e=>t.add(e)),Array.from(t).filter(e=>e instanceof HTMLElement&&null!==e.querySelector(im))}async extractGeminiCanvasAppArtifactsFromResponse(e){const t=this.getGeminiCanvasCardsFromResponse(e);if(0===t.length)return "";const n=[];for(const o of t){const e=this.extractGeminiCanvasTitle(o);try{const t=await this.openGeminiCanvasCardForExport(o);if(!t)continue;await this.selectGeminiCanvasCodeTab(t);const r=await this.extractGeminiCanvasCodeArtifact(t,e);r&&n.push(r);}catch(r){console.warn("[GeminiAdapter] Failed to export Gemini Canvas artifact",r);}}return n.length>0?this.formatGeminiCanvasCodeArtifacts(n):this.formatGeminiCanvasFallbackTitles(t.map(e=>this.extractGeminiCanvasTitle(e)))}async extractGeminiCanvasShareArtifactsFromTurn(e){const t=this.getGeminiCanvasShareArtifactElements(e);if(0===t.length)return "";const n=[];for(const o of t)try{await this.selectGeminiCanvasCodeTab(o);const e=await this.extractGeminiCanvasCodeArtifact(o,this.extractGeminiCanvasTitle(o));e&&n.push(e);}catch(r){console.warn("[GeminiAdapter] Failed to export Gemini Canvas share artifact",r);}return n.length>0?this.formatGeminiCanvasCodeArtifacts(n):this.formatGeminiCanvasFallbackTitles(t.map(e=>this.extractGeminiCanvasTitle(e)))}getGeminiCanvasPanelElement(){const e=document.querySelector(am);return e instanceof HTMLElement?e:null}async openGeminiCanvasCardForExport(e){const t=null!==this.getGeminiCanvasPanelElement(),n=this.extractGeminiCanvasTitle(e),r=this.getGeminiCanvasPanelElement();if(r&&this.isGeminiCanvasPanelForTitle(r,n))return r;e.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await this.sleep(60);for(const o of this.getGeminiCanvasCardClickTargets(e)){this.simulateClick(o);const e=await this.waitForGeminiCanvasPanel(n);if(e)return t||(this.exportOpenedCanvasPanel=true),e}return null}getGeminiCanvasCardClickTargets(e){const t=e.closest("immersive-entry-chip"),n=[e,t].filter(e=>e instanceof HTMLElement),r=new Set;return n.filter(e=>!r.has(e)&&(r.add(e),true))}async waitForGeminiCanvasPanel(e,t=3e3){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement);if(e.length>=2)return e[0]}return null}isGeminiCanvasCodeTabSelected(e){if(e.classList.contains("mat-button-toggle-checked"))return true;const t=e.querySelector("button[role='radio']");return "true"===t?.getAttribute("aria-checked")}hasGeminiCanvasCodeSurface(e){return null!==this.findGeminiCanvasCodeBlock(e)||null!==this.findGeminiCanvasCodeEditor(e)}async extractGeminiCanvasCodeArtifact(e,t){const n=this.findGeminiCanvasCodeBlock(e);if(n)return this.extractGeminiCanvasCodeBlockArtifact(n,t);const r=this.findGeminiCanvasCodeEditor(e);return r?this.extractGeminiCanvasCodeEditorArtifact(r,t):null}findGeminiCanvasCodeBlock(e){if(e instanceof HTMLElement&&e.matches("code-block"))return e;const t=e.querySelector("code-block");return t instanceof HTMLElement?t:null}findGeminiCanvasCodeEditor(e){if(e instanceof HTMLElement&&e.matches(sm))return e.classList.contains("hidden")?null:e;const t=e.querySelector(sm);return t instanceof HTMLElement&&!t.classList.contains("hidden")?t:null}extractGeminiCanvasCodeBlockArtifact(e,t){const n=e.querySelector('[data-test-id="code-content"], pre code, code'),r=this.normalizeGeminiCanvasCode(this.extractTextWithLineBreaks(n||e));return r?{title:this.extractGeminiCanvasTitle(e,t),language:this.extractGeminiCanvasCodeLanguage(e)||"text",code:r}:null}async extractGeminiCanvasCodeEditorArtifact(e,t){const n=await this.extractGeminiCanvasMainWorldMonacoCode(e)||this.extractGeminiCanvasMonacoModelCode(e)||await this.extractGeminiCanvasRenderedMonacoCode(e);return n?{title:this.extractGeminiCanvasTitle(e,t),language:this.extractGeminiCanvasCodeLanguage(e)||"text",code:n}:null}async extractGeminiCanvasMainWorldMonacoCode(e){if(!document.documentElement.hasAttribute("data-ophel-gemini-canvas-main"))return "";const t=e.querySelector(".monaco-editor")?.getAttribute("data-uri")||"";if(!t)return "";const n=`ophel-gemini-canvas-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(e=>{let r=false,o=0;const i=t=>{r||(r=true,window.clearTimeout(o),window.removeEventListener("message",a),e(this.normalizeGeminiCanvasCode(t)));},a=e=>{if(e.origin&&e.origin!==window.location.origin)return;const t=e.data;t?.type===Q&&t.requestId===n&&i("string"==typeof t.code?t.code:"");};o=window.setTimeout(()=>i(""),900),window.addEventListener("message",a),window.postMessage({type:G,requestId:n,editorUri:t},"*");})}extractGeminiCanvasMonacoModelCode(e){const t=window,n=t.monaco?.editor?.getModels?.();if(!n?.length)return "";const r=e.querySelector(".monaco-editor")?.getAttribute("data-uri")||"",o=n.find(e=>{const t=e;return r&&t.uri?.toString?.()===r})||(1===n.length?n[0]:null),i=o?.getValue;return "function"!=typeof i?"":this.normalizeGeminiCanvasCode(i.call(o))}async extractGeminiCanvasRenderedMonacoCode(e){const t=e.querySelector("textarea.inputarea");if(t instanceof HTMLTextAreaElement&&t.value.trim())return this.normalizeGeminiCanvasCode(t.value);const n=e.querySelector(".monaco-scrollable-element");if(!(n instanceof HTMLElement))return this.normalizeGeminiCanvasCode(this.extractGeminiCanvasVisibleMonacoLines(e).join("\n"));const r=n.scrollTop,o=Math.max(n.clientHeight,1),i=this.getGeminiCanvasMonacoContentHeight(e),a=Math.max(i-o,n.scrollHeight,0),s=Math.max(Math.floor(.8*o),120),l=[];for(let c=0;c<=a;c+=s){n.scrollTop=c,n.dispatchEvent(new Event("scroll",{bubbles:true})),await this.sleep(40);const t=this.extractGeminiCanvasVisibleMonacoLines(e);t.length>0&&l.push(t.join("\n"));}return n.scrollTop=r,n.dispatchEvent(new Event("scroll",{bubbles:true})),this.normalizeGeminiCanvasCode(this.mergeGeminiCanvasRenderedCodeChunks(l))}extractGeminiCanvasVisibleMonacoLines(e){return Array.from(e.querySelectorAll(".view-lines .view-line")).filter(e=>e instanceof HTMLElement).sort((e,t)=>this.getElementTop(e)-this.getElementTop(t)).map(e=>this.normalizeGeminiCanvasCodeLine(e.textContent||""))}getGeminiCanvasMonacoContentHeight(e){const t=Array.from(e.querySelectorAll(".view-lines, .margin, .lines-content")).flatMap(e=>e instanceof HTMLElement?[e.scrollHeight,e.offsetHeight,this.parseCssPixelValue(e.style.height)]:[]);return Math.max(...t,0)}mergeGeminiCanvasRenderedCodeChunks(e){const t=[];for(const n of e){const e=n.split("\n");let r=0;for(let n=Math.min(t.length,e.length);n>0;n-=1){if(t.slice(t.length-n).join("\n")===e.slice(0,n).join("\n")){r=n;break}}t.push(...e.slice(r));}return t.join("\n")}getElementTop(e){return this.parseCssPixelValue(e.style.top)}parseCssPixelValue(e){const t=e.match(/-?\d+(?:\.\d+)?/);return t?Number(t[0]):0}extractGeminiCanvasTitle(e,t="Gemini Canvas"){return (e.querySelector(".title-text, .card-title")?.textContent?.trim()||e.closest(".immersive-artifact-container")?.querySelector(".title-text")?.textContent?.trim()||e.closest(am)?.querySelector(".title-text")?.textContent?.trim()||t).replace(/\s+/g," ").trim()||t}extractGeminiCanvasCodeLanguage(e){const t=e.querySelector(".code-block-decoration span")?.textContent||e.closest("[data-mode-id]")?.getAttribute("data-mode-id")||e.querySelector("[data-mode-id]")?.getAttribute("data-mode-id")||"";return (t.split(/\r?\n/)[0]?.trim().toLowerCase()||"").replace(/[^a-z0-9_#+.-]/g,"")}formatGeminiCanvasCodeArtifacts(e){const t=[],n=new Set;for(const r of e){const e=`${r.title}\n${r.language}\n${r.code}`;n.has(e)||(n.add(e),t.push(r));}return t.map(e=>`${e.title?`### Gemini Canvas: ${e.title}`:"### Gemini Canvas"}\n\n${this.formatGeminiCanvasCodeFence(e.code,e.language)}`).join("\n\n")}formatGeminiCanvasFallbackTitles(e){return e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).filter((e,t,n)=>n.indexOf(e)===t).map(e=>`### Gemini Canvas: ${e}`).join("\n\n")}formatGeminiCanvasCodeFence(e,t){let n="```";for(;e.includes(n);)n+="`";return `${n}${t||""}\n${e}\n${n}`}normalizeGeminiCanvasCode(e){return e.replace(/\r\n?/g,"\n").replace(/\u00a0/g," ").replace(/^\n+/g,"").replace(/\n+$/g,"")}normalizeGeminiCanvasCodeLine(e){return e.replace(/\u00a0/g," ").replace(/\s+$/g,"")}joinExportSections(...e){return e.map(e=>e.trim()).filter(Boolean).join("\n\n")}isDeepResearchAppPage(){return !this.isSharePage()&&(null!==this.getDeepResearchAppDocumentElement()||null!==this.getDeepResearchAppDocumentTrigger()||null!==document.querySelector(`model-response ${tm}`))}getDeepResearchAppDocumentElement(){return document.querySelector(rm)}hasDeepResearchAppDocumentTrigger(){return null!==this.getDeepResearchAppDocumentTrigger()}getDeepResearchAppDocumentTrigger(){return Array.from(document.querySelectorAll('model-response [data-test-id="gem-processing-card"], model-response immersive-entry-chip')).filter(e=>e instanceof HTMLElement).find(e=>{const t=e.matches('[data-test-id="gem-processing-card"]')?e:e.querySelector('[data-test-id="gem-processing-card"]');return !!t?.querySelector(om)&&null!==e.closest("model-response")})||null}async openDeepResearchAppDocumentPanel(){const e=this.getDeepResearchAppDocumentTrigger();if(!e)return false;if(e.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),e.click(),await this.waitForDeepResearchAppDocumentElement())return true;const t=e.matches('[data-test-id="gem-processing-card"]')?e:e.querySelector('[data-test-id="gem-processing-card"]');return t instanceof HTMLElement&&t!==e&&(t.click(),this.waitForDeepResearchAppDocumentElement())}async closeDeepResearchAppDocumentPanel(){const e=document.querySelector(`${nm} [data-test-id="close-button"], immersive-panel [data-test-id="close-button"]`);e instanceof HTMLElement&&(e.click(),await new Promise(e=>setTimeout(e,150)));}async waitForDeepResearchAppDocumentElement(e=3e3){const t=Date.now();for(;Date.now()-tsetTimeout(e,100));}return null!==this.getDeepResearchAppDocumentElement()}isGeminiExportLifecycleState(e){return "object"==typeof e&&null!==e&&"openedDeepResearchPanel"in e&&"boolean"==typeof e.openedDeepResearchPanel}isDeepResearchDocumentSharePage(){return this.isSharePage()&&null!==document.querySelector(Jp)}isDeepResearchConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(Xp)}isGeminiConversationSharePage(){return this.isSharePage()&&null!==document.querySelector(Zp)}extractDeepResearchDocumentShareMessages(e){const t=document.querySelector(`${Jp} ${em}`),n=t?this.extractAssistantResponseTextWithAssets(t,e):"",r=n&&e?this.appendDeepResearchReportAssetLink(e,n,this.getDeepResearchDocumentShareTitle()):n;return r?[{role:"assistant",content:r}]:[]}async extractDeepResearchAppMessages(e){const t=this.getDeepResearchAppDocumentElement();if(this.hasDeepResearchAppDocumentTrigger()&&!t)return console.warn("[GeminiAdapter] Deep Research report panel is not available for export"),[];const n=[],r=new Set,o=this.getScrollContainer()||document,i=Array.from(o.querySelectorAll("user-query, model-response")).sort((e,t)=>this.compareDomOrder(e,t));for(const a of i){if(a.closest("immersive-panel"))continue;const t="user-query"===a.tagName.toLowerCase()?"user":"assistant",o="user"===t?(e?await this.extractUserQueryExportContentWithResolvedAssets(a,e):this.extractUserQueryExportContentWithAssets(a)).trim():this.extractDeepResearchAppAssistantResponseContent(a,e).trim();o&&(r.add(a),n.push({role:t,content:o}));}if(t&&!r.has(t)){const r=this.extractAssistantResponseTextWithAssets(t,e).trim();r&&n.push({role:"assistant",content:e?this.appendDeepResearchReportAssetLink(e,r):r});}return this.dedupeAdjacentExportMessages(n)}extractDeepResearchAppAssistantResponseContent(e,t){const n=e.querySelector(em);return this.extractAssistantResponseTextWithAssets(n||e,t)}async extractDeepResearchConversationShareMessages(e){const{messages:t,collectedElements:n}=await this.collectGeminiShareTurnMessages(e);return this.collectDetachedDeepResearchArtifactMessages(n,e).forEach(e=>{t.push(e);}),this.dedupeAdjacentExportMessages(t)}async extractGeminiConversationShareMessages(e){return (await this.collectGeminiShareTurnMessages(e)).messages}async collectGeminiShareTurnMessages(e){const t=[],n=new Set,r=Array.from(document.querySelectorAll(Zp));for(const o of r){let r=false;const i=[...Array.from(o.querySelectorAll("user-query")).map(e=>({role:"user",element:e})),...Array.from(o.querySelectorAll(Yp)).map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element));for(const{role:a,element:s}of i){const i="user"===a?(e?await this.extractUserQueryExportContentWithResolvedAssets(s,e):this.extractUserQueryExportContentWithAssets(s)).trim():this.joinExportSections(this.extractAssistantResponseTextWithAssets(s,e),r?"":await this.extractGeminiCanvasShareArtifactsFromTurn(o));i&&("assistant"===a&&(r=true),n.add(s),t.push({role:a,content:i}));}if(!r){const e=await this.extractGeminiCanvasShareArtifactsFromTurn(o);e&&t.push({role:"assistant",content:e});}}return {messages:this.dedupeAdjacentExportMessages(t),collectedElements:n}}collectDetachedDeepResearchArtifactMessages(e,t){return Array.from(document.querySelectorAll(`${Xp} ${em}`)).flatMap(n=>{if(e.has(n))return [];const r=this.extractAssistantResponseTextWithAssets(n,t).trim(),o=r&&t?this.appendDeepResearchReportAssetLink(t,r,this.getDeepResearchArtifactShareTitle()):r;return o?[{role:"assistant",content:o}]:[]})}appendDeepResearchReportAssetLink(e,t,n){return La(e,t,{title:n,fallbackTitle:"deep-research-report",directory:"assets/documents",idPrefix:"gemini-deep-research-report"})}createUniqueGeminiExportPath(e,t){return Ji(e,t.usedPaths)}extractMarkdownExportContent(e){return (Fi(e)||this.extractTextWithLineBreaks(e)).trim()}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}dedupeAdjacentExportMessages(e){const t=[];return e.forEach(e=>{const n=t[t.length-1];n?.role===e.role&&n.content===e.content||t.push(e);}),t}getDeepResearchDocumentShareTitle(){const e=document.querySelector(`${Jp} h1`);return e?.textContent?.trim()||null}getDeepResearchArtifactShareTitle(){const e=document.querySelector(`${Xp} h1`);return e?.textContent?.trim()||null}replaceUserQueryContent(e,t){const n=e.querySelector(".query-text");if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const r=document.createElement("div");return r.className="gh-user-query-markdown gh-user-query-markdown-gemini gh-markdown-preview",!!Rp(r,t)&&(r.querySelectorAll("pre").forEach(e=>{const t=e;t.style.setProperty("background","var(--gh-user-query-code-bg)","important"),t.style.setProperty("background-color","var(--gh-user-query-code-bg)","important"),t.style.setProperty("color","var(--gh-user-query-code-fg)","important"),t.querySelectorAll("code").forEach(e=>{const t=e;t.style.setProperty("background","transparent","important"),t.style.setProperty("background-color","transparent","important"),t.style.setProperty("color","var(--gh-user-query-code-fg)","important");});}),n.style.display="none",n.after(r),true)}getExportConfig(){return {userQuerySelector:"user-query",assistantResponseSelector:"model-response, .model-response-container .markdown",turnSelector:".conversation-turn",useShadowDOM:false}}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest("message-content");if(t&&t.id){const e=t.id.match(/(r_[a-f0-9]+)/);if(e)return e[1]}return null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector(),c=(e,t,n)=>{if(!e)return 0;try{if(n){let t=e.nextElementSibling,n=0;for(;t;){const e=t.tagName.toLowerCase();if("user-query"===e)break;if("model-response"===e){const e=t.querySelector(".model-response-text, message-content");if(e){const r=t.querySelector("model-thoughts"),o=r?.textContent?.trim().length||0,i=e.textContent?.trim().length||0;n+=Math.max(0,i-o);}}t=t.nextElementSibling;}return n}const r=e.closest("message-content");return this.calculateRangeWordCount(e,t,r||o)}catch{return 0}};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,o)=>{if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(t.tagName.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=o+1;e{const a=t.tagName.toLowerCase();if("user-query"===a){let e=this.extractUserQueryText(t),o=false;e.length>200&&(e=e.substring(0,200),o=true);const i={level:0,text:e,element:t,isUserQuery:true,isTruncated:o},a=(e=>{const t=e.querySelector('button[jslog*="BardVeMetadataKey"]');if(t){const e=(t.getAttribute("jslog")||"").match(/BardVeMetadataKey.*?["'](r_[a-f0-9]+)["']/);if(e)return e[1]}return null})(t);a&&(i.id=a),n&&(i.wordCount=c(t,null,true)),r.push(i);}else if(/^h[1-6]$/.test(a)){if(this.shouldSkipOutlineHeading(t))return;const l=parseInt(a.charAt(1),10);if(l<=e){const e={level:l,text:t.textContent?.trim()||"",element:t},a=i(t);if(a){const n=t.tagName.toLowerCase();e.id=s(a,n,e.text);}if(n){let n=null;for(let t=o+1;t0&&e.length<=20)return e}}return null}getNetworkMonitorConfig(){return {urlPatterns:["BardFrontendService","StreamGenerate"],silenceThreshold:3e3}}afterPropertiesSet(e={}){super.afterPropertiesSet(e),this.myStuffEnhancer||(this.myStuffEnhancer=new Sm({getUserPathPrefix:()=>this.getUserPathPrefix()}),this.myStuffEnhancer.start()),this.startDeepResearchPanelActions();}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".input-area-switch-label",".model-selector",'[data-test-id="model-selector"]','[aria-label*="model"]','button[aria-haspopup="menu"]'],menuItemSelector:'.mode-title, [role="menuitem"], [role="option"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:300}} /** * 切换 Gemini 主题 * 直接修改 localStorage + body.className 实现即时无感切换 * @param targetMode 目标主题模式 */ async toggleTheme(e){try{const t="dark"===e?"Bard-Dark-Theme":"Bard-Light-Theme";return localStorage.setItem("Bard-Color-Theme",t),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:t,storageArea:localStorage})),!0}catch(t){return console.error("[GeminiAdapter] toggleTheme error:",t),false}}},new class extends gs{sessionAccessToken=null;sessionAccessTokenExpiresAt=0;lastModelLockAttemptAt=0;lastModelLockAttemptKeyword="";cachedModelDisplayNamesBySlug=new Map;lastKnownModelSlug=null;lastKnownModelSlugContextKey="";lastKnownModelSlugObservedAt=0;outlineCacheSessionKey="";outlineItemCache=new Map;outlineTurnFirstSeenIndex=new Map;outlineTurnFirstSeenCounter=0;outlineCacheTransitionEndAt=0;exportSnapshotRoot=null;exportSnapshotActive=false;exportIncludeThoughtsOverride=null;exportBundle=null;match(){return window.location.hostname.includes("chatgpt.com")}getSiteId(){return co}getName(){return "ChatGPT"}getThemeColors(){return {primary:"#10a37f",secondary:"#1a7f64"}}getNativeThemeCss(){return "\n/* =============================================\n * ChatGPT 站点原生主题适配器 (ChatGPT Theme Adapter)\n * ============================================= */\n:root, .dark, .light {\n /* 1. 侧边栏容器 */\n --sidebar-surface-primary: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n\n /* 悬浮层、气泡和弹窗 */\n --bg-elevated-primary: var(--gh-bg-secondary) !important;\n --bg-elevated-secondary: var(--gh-bg-tertiary) !important;\n\n /* 底层遮罩 */\n --bg-scrim: var(--gh-overlay-bg) !important;\n\n /* 2. 文本与图标层级 */\n --icon-primary: var(--gh-text) !important;\n --icon-secondary: var(--gh-text-secondary) !important;\n --icon-tertiary: var(--gh-text-tertiary) !important;\n\n /* 3. 边框 (使用极其微弱的透明度保持原生通透感) */\n --border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n --border-heavy: color-mix(in srgb, var(--gh-primary) 25%, transparent) !important;\n --border-light: color-mix(in srgb, var(--gh-primary) 8%, transparent) !important;\n\n /* 4. 品牌高亮/突出显示(绑定 Ophel 主题色) */\n --bg-accent-static: var(--gh-primary) !important;\n --text-accent: var(--gh-primary) !important;\n --icon-accent: var(--gh-primary) !important;\n --interactive-label-accent-default: var(--gh-primary) !important;\n --interactive-label-accent-hover: var(--gh-primary) !important;\n --interactive-label-accent-press: var(--gh-primary) !important;\n --interactive-label-accent-inactive: var(--gh-primary) !important;\n --interactive-label-accent-selected: var(--gh-primary) !important;\n --interactive-icon-accent-default: var(--gh-primary) !important;\n\n /* 5. 交互状态 (按钮 Hover 等) */\n /* - 次级交互(普通按钮/Icon Hover) */\n --interactive-bg-secondary-hover: var(--gh-hover) !important;\n --interactive-bg-secondary-press: var(--gh-active-bg) !important;\n --interactive-bg-secondary-selected: var(--gh-active-bg) !important;\n\n /* - 第三级交互(如模型选择器等) */\n --interactive-bg-tertiary-default: var(--gh-bg-secondary) !important;\n --interactive-bg-tertiary-hover: var(--gh-hover) !important;\n --interactive-bg-tertiary-press: var(--gh-active-bg) !important;\n\n /* 6. 其他小细节 */\n --utility-scrollbar: var(--gh-border) !important;\n /* 行内代码块背景 */\n --gray-100: var(--gh-bg-tertiary) !important;\n}\n\n/* 按钮颜色 */\n.composer-btn {\n color: var(--gh-primary) !important;\n}\n\n/* 链接颜色 */\na.decorated-link:where(:not(.not-markdown *)) {\n color: var(--gh-primary) !important;\n}\n"}getNewTabUrl(){return "https://chatgpt.com"}getSessionId(){const e=window.location.pathname.match(/\/c\/([a-z0-9-]+)(?:\/|$)/i);return e?.[1]?e[1]:super.getSessionId()}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/c\/[a-z0-9-]+(?:\/|$)/i.test(window.location.pathname)}getCurrentCid(){try{const e=localStorage.getItem("_account");if(e)return JSON.parse(e)}catch{}return null}getConversationList(){const e=document.querySelectorAll('#history a[data-sidebar-item="true"]')||[],t=this.getCurrentCid()||void 0;return Array.from(e).map(e=>{const n=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span"),i=o?.textContent?.trim()||"",a=e.hasAttribute("data-active"),s=e.querySelector(".trailing-pair"),l=(s?.querySelectorAll(".trailing svg")||[]).length>1;return {id:r,cid:t,title:i,url:r?`https://chatgpt.com/c/${r}`:"",isActive:a,isPinned:l}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("#history");if(e){const t=e.closest("nav");if(t)return t}return null}getConversationObserverConfig(){return {selector:'#history a[data-sidebar-item="true"]',shadow:false,extractInfo:e=>{const t=(e.getAttribute("href")||"").match(/\/c\/([a-f0-9-]+)/),n=t?t[1]:"";if(!n)return null;const r=e.querySelector("span"),o=r?.textContent?.trim()||"",i=e.hasAttribute("data-active"),a=this.getCurrentCid()||void 0,s=e.querySelector(".trailing-pair");return {id:n,cid:a,title:o,url:`https://chatgpt.com/c/${n}`,isActive:i,isPinned:(s?.querySelectorAll(".trailing svg")||[]).length>1}},getTitleElement:e=>e.querySelector("span")||e}}navigateToConversation(e,t){const n=document.querySelector(`#history a[href="/c/${e}"], a[data-sidebar-item][href="/c/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t)}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.sessionAccessToken;try{const e=await fetch("/api/auth/session",{method:"GET",credentials:"include"});if(!e.ok)return this.clearSessionAccessToken(),null;const n=await e.json(),r=[n?.accessToken,n?.access_token,n?.token,n?.user?.accessToken].find(e=>"string"==typeof e&&e.length>0)||null;return "string"==typeof r&&r.length>0?(this.sessionAccessToken=r,this.sessionAccessTokenExpiresAt=t+3e5,r):(this.clearSessionAccessToken(),null)}catch{return this.clearSessionAccessToken(),null}}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}getChatgptAccountId(){try{const e=localStorage.getItem("_account");if(!e)return null;const t=JSON.parse(e);return "string"==typeof t&&t&&"personal"!==t?t:null}catch{return null}}buildNativeDeleteHeaders(e,t){const n={accept:"*/*",authorization:`Bearer ${e}`};"PATCH"===t&&(n["content-type"]="application/json");const r=this.getChatgptAccountId();r&&(n["chatgpt-account-id"]=r);const o=this.getCookieValue("oai-did");o&&(n["oai-device-id"]=o);const i=document.documentElement.lang||navigator.language;return i&&(n["oai-language"]=i),n}async performNativeDeleteRequest(e,t,n="PATCH"){const r=this.buildNativeDeleteHeaders(t,n);return fetch(e,{method:n,headers:r,body:"PATCH"===n?JSON.stringify({is_visible:false}):void 0,credentials:"include"})}async isConversationAlreadyGone(e){return !(await this.findConversationRowWithRetry(e))}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}async tryDeleteViaNativeApi(e){let t=await this.getSessionAccessToken();if(!t)return {id:e,success:false,method:"none",reason:nl};const n=async(e,n="PATCH")=>{let r=await this.performNativeDeleteRequest(e,t,n);if(401===r.status||403===r.status){if(t=await this.getSessionAccessToken(true),!t)return this.clearSessionAccessToken(),r;r=await this.performNativeDeleteRequest(e,t,n);}return r},r=encodeURIComponent(e),o=[`/backend-api/conversation/${r}`,`/backend-api/conversations/${r}`];try{let t=null;for(const r of o){let o=await n(r,"PATCH");if(t=o.status,o.ok)return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(405===o.status&&(o=await n(r,"DELETE"),t=o.status,o.ok))return this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status)return 401!==o.status&&403!==o.status||this.clearSessionAccessToken(),{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}return 404===t&&await this.isConversationAlreadyGone(e)?(this.syncSidebarAfterRemoteDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:404===t?ol:this.toDeleteApiHttpReason(t??0)}}catch(i){return i instanceof Error&&"AbortError"===i.name?{id:e,success:false,method:"api",reason:"delete_api_timeout"}:{id:e,success:false,method:"api",reason:rl}}}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;const n=await this.findConversationMenuButton(t,e);if(!n)return false;document.body.click(),await this.sleep(50),this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,4e3)}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#history a[data-sidebar-item="true"][href="/c/${e}"]`)}async findConversationMenuButton(e,t){const n=['button[aria-haspopup="menu"]','button[aria-label*="More"]','button[aria-label*="more"]','button[aria-label*="更多"]','button[data-testid*="menu"]',".trailing button"].join(", "),r=this.findConversationItemContainer(e,t),o=[r,e.closest("li"),e.parentElement,e].filter((e,t,n)=>!!e&&n.indexOf(e)===t);for(let i=0;i<8;i++){o.forEach(e=>{e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));});for(const e of o){const o=this.findFirstInScope(e,n,n=>this.isMenuButtonForConversation(n,t,r||e));if(o)return o}await this.sleep(100);}return null}findConversationItemContainer(e,t){const n=`/c/${t}`;let r=e,o=null;for(let i=0;i<8&&r;i++){const e=Array.from(r.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(e.some(e=>e.getAttribute("href")===n)){o||1!==e.length||(o=r);const t=!!r.querySelector('button[aria-haspopup="menu"], .trailing button');if(1===e.length&&t)return r}if("history"===r.id)break;r=r.parentElement;}return o||e.closest("li")||e.parentElement||e}findFirstInScope(e,t,n){const r=Array.from(e.querySelectorAll(t));for(const o of r)if(this.isVisible(o)&&(!n||n(o)))return o;return null}isMenuButtonForConversation(e,t,n){if(!n.contains(e))return false;const r=`/c/${t}`,o=e.closest("li");if(o){const e=Array.from(o.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));if(1===e.length&&e[0].getAttribute("href")===r&&o.contains(n.querySelector(`a[data-sidebar-item="true"][href="${r}"]`)))return true}const i=Array.from(n.querySelectorAll('a[data-sidebar-item="true"][href^="/c/"]'));return 1===i.length&&i[0].getAttribute("href")===r}getMenuContainerFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"]'));let r=null,o=Number.POSITIVE_INFINITY;const i=e.getBoundingClientRect(),a=i.left+i.width/2,s=i.top+i.height/2;for(const l of n){if(!this.isVisible(l))continue;const e=l.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,i=Math.hypot(t-a,n-s);i0?n:r;for(const e of o){if(!this.isVisible(e))continue;const t=(e.textContent||"").trim().toLowerCase();if(Xs.some(e=>t.includes(e.toLowerCase())))return e}await this.sleep(80);}return null}async waitForDeleteConfirmButton(e=2500){const t=Date.now();for(;Date.now()-te.includes(t.toLowerCase())))return t}await this.sleep(80);}return null}async waitForConversationRemoved(e,t=3e3){const n=Date.now();for(;Date.now()-n0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getSessionName(){const e=this.getDocumentConversationTitle(Js);return e&&e!==Js?e.replace(` | ${Js}`,"").replace(` - ${Js}`,"").trim():super.getSessionName()}getConversationTitle(){const e=document.querySelector("#history a[data-active] span"),t=e?.textContent?.trim();return t||this.getSessionName()}getNewChatButtonSelectors(){return ['[data-testid="create-new-chat-button"]','a[href="/"]','button[aria-label="New chat"]','button[aria-label="新对话"]']}getLatestReplyText(){const e=document.querySelector(this.getResponseContainerSelector());if(!e)return null;const t=e.querySelectorAll('[data-message-author-role="assistant"]');if(0===t.length)return null;const n=t[t.length-1],r=(n.querySelector(".markdown, .prose, [class*='prose']")||n).cloneNode(true);r.querySelectorAll('.sr-only, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=Fi(r).trim();return o||this.extractTextWithLineBreaks(r)}getWidthSelectors(){return [{selector:'[class*="thread-content-max-width"]',property:"max-width"},{selector:'[style*="--thread-content-max-width"]',property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:":root",property:"--user-chat-width",noCenter:true}]}getZenModeConfig(){return {hide:["#stage-slideover-sidebar","div.select-none:has(> .pointer-events-auto)"]}}getCleanModeConfig(){return {hide:["div.select-none:has(> .pointer-events-auto)",'div.border-token-border-default.border-t.py-4.text-sm:has(button[aria-label="Ad options"]):has([role="link"][tabindex="0"])']}}getMarkdownFixerConfig(){return {selector:'[data-message-author-role="assistant"] p',fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest('[data-message-author-role="assistant"]');if(!t)return false;const n=document.querySelectorAll(this.getChatContentSelectors().find(e=>e.includes("assistant"))||'[data-message-author-role="assistant"]');return t===n[n.length-1]}}}getTextareaSelectors(){return ["#prompt-textarea",'textarea[data-id="root"]','[contenteditable="true"]']}getSubmitButtonSelectors(){return ['[data-testid="send-button"]','button[aria-label="Send prompt"]','button[aria-label="发送"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&("prompt-textarea"===e.id||"true"===e.getAttribute("contenteditable")))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return console.warn("[Ophel] insertPrompt: focus failed"),false;try{document.execCommand("selectAll",!1,void 0);if(!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false")}catch{"TEXTAREA"===t.tagName?t.value=e:t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return true}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"TEXTAREA"===this.textarea.tagName?this.textarea.value="":(document.execCommand("selectAll",false,void 0),document.execCommand("delete",false,void 0)),this.textarea.dispatchEvent(new Event("input",{bubbles:true}))):this.textarea=null);}getScrollContainer(){const e=document.querySelector('[class*="scrollbar-gutter"], [class*="@container/main"] > div');if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelectorAll("div");let n=null,r=0;for(const o of Array.from(t)){const e=getComputedStyle(o);("auto"===e.overflowY||"scroll"===e.overflowY)&&o.scrollHeight>o.clientHeight&&o.scrollHeight>r&&(o.closest("nav")||(r=o.scrollHeight,n=o));}return n}getResponseContainerSelector(){return "#thread, main#main"}getChatContentSelectors(){return ['[data-message-author-role="assistant"]','[data-message-author-role="user"]',".markdown"]}getUserQuerySelector(){return '[data-message-author-role="user"]'}extractUserQueryText(e){const t=e.matches(".whitespace-pre-wrap")?e:e.querySelector(".whitespace-pre-wrap");return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=e.querySelector(".whitespace-pre-wrap");if(!t)return this.extractUserQueryText(e).trim();const n=t.cloneNode(true);n.querySelectorAll(".sr-only").forEach(e=>e.remove()),n.querySelectorAll("pre code").forEach(e=>{if(e.className.includes("language-"))return;const t=(e.textContent||"").split("\n");if(t.length>1){const n=t[0].trim().toLowerCase(),r=t[1].trim().toLowerCase();il.has(n)&&!il.has(r)&&(e.className=`language-${n}`,e.textContent=t.slice(1).join("\n"));}});const r=Fi(n).trim();return r||this.extractUserQueryText(t).trim()}extractUserQueryExportContent(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";return this.extractUserQueryMarkdown(e).trim()||this.extractUserQueryText(e)}extractAssistantResponseText(e){return this.isExportSnapshotElement(e)?e.textContent?.trim()||"":super.extractAssistantResponseText(e)}isExportSnapshotElement(e){return e.hasAttribute(ul)}shouldSkipElement(e){return e.classList.contains("sr-only")}extractTextWithLineBreaks(e){const t=[],n=new Set(["div","p","li","h1","h2","h3","h4","h5","h6","pre","blockquote","tr","section","article"]),r=e=>{if(e.nodeType===Node.TEXT_NODE){const n=e.textContent||"";t.push(n);}else if(e.nodeType===Node.ELEMENT_NODE){const o=e,i=o.tagName.toLowerCase();if(this.shouldSkipElement(o))return;if("br"===i)return void t.push("\n");for(const e of o.childNodes)r(e);if(n.has(i)&&t.length>0){t[t.length-1].endsWith("\n")||t.push("\n");}}};return r(e),t.join("").replace(/\n{3,}/g,"\n\n").trim()}replaceUserQueryContent(e,t){const n=e.querySelector(".whitespace-pre-wrap");if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;n.style.display="none";const r=document.createElement("div");return r.className="gh-user-query-markdown gh-markdown-preview",r.innerHTML=t,n.after(r),true}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:ml,assistantResponseSelector:fl,turnSelector:pl,useShadowDOM:false}:{userQuerySelector:'[data-message-author-role="user"]',assistantResponseSelector:'[data-message-author-role="assistant"]',turnSelector:'[data-testid^="conversation-turn"]',useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportSnapshot(),this.exportBundle=null;const t="markdown"===e.format&&"zip"===e.packaging?ia():null,n=document.querySelector(this.getResponseContainerSelector())||document.body,r=this.getScrollContainer()||n;let o=r instanceof HTMLElement?await this.collectExportMessageSnapshots(r,t):this.readVisibleExportMessageSnapshots(n,t);return 0===o.length&&r!==n&&(o=this.readVisibleExportMessageSnapshots(n,t)),0===o.length&&n!==document.body&&(o=this.readVisibleExportMessageSnapshots(document,t)),0===o.length?null:(this.mountExportSnapshot(o),this.exportBundle={messages:o.map(({role:e,content:t})=>({role:e,content:t})),assets:t?.assets},{count:o.length})}async extractExportBundle(e){return this.exportBundle}async extractExportMessages(e){return this.exportBundle?.messages??null}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundle=null;}async collectExportMessageSnapshots(e,t){const n=e.scrollTop,r=new Map,o=new Map;let i=0;const a=e=>{for(const t of e){o.has(t.turnKey)||o.set(t.turnKey,i++);const e=r.get(t.turnKey);if(!e){r.set(t.turnKey,t);continue}const n=Math.min(e.order,t.order);t.content.length>e.content.length?r.set(t.turnKey,{...t,order:n}):n!==e.order&&r.set(t.turnKey,{...e,order:n});}};try{const n=this.getAllTurnShellsSorted();if(0===n.length)a(this.readVisibleExportMessageSnapshots(e,t));else {for(const r of n)this.turnHasMountedMessage(r)||(this.scrollTurnIntoView(r),e.dispatchEvent(new Event("scroll",{bubbles:!0})),await this.waitForTurnMessageMounted(r,900)),this.turnHasMountedMessage(r)&&(a(this.extractTurnExportSnapshots(r,null,t)),this.absorbTurnIntoOutlineCache(r));const o=this.extractCollectedTurnIds(r),i=n.filter(e=>{const t=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return t.length>0&&!o.has(t)});if(i.length>0){await this.sleep(200);for(const n of i)this.scrollTurnIntoView(n),e.dispatchEvent(new Event("scroll",{bubbles:!0})),await this.waitForTurnMessageMounted(n,1800),this.turnHasMountedMessage(n)&&(a(this.extractTurnExportSnapshots(n,null,t)),this.absorbTurnIntoOutlineCache(n));}}}finally{try{this.extractOutline(6,!0,!1);}catch{}e.scrollTop=n,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return Array.from(r.values()).sort((e,t)=>{if(e.order!==t.order)return e.order-t.order;return (o.get(e.turnKey)??Number.MAX_SAFE_INTEGER)-(o.get(t.turnKey)??Number.MAX_SAFE_INTEGER)})}getAllTurnShellsSorted(){const e=document.querySelector(this.getResponseContainerSelector())||document,t=Array.from(e.querySelectorAll('section[data-turn], [data-testid^="conversation-turn"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${cl}]`)&&!e.closest(".gh-root, .gh-main-panel")));return t.filter(e=>!t.some(t=>t!==e&&e.contains(t))).sort((e,t)=>this.getExportTurnSortIndex(e)-this.getExportTurnSortIndex(t))}turnHasMountedMessage(e){const t=e.querySelector("[data-message-author-role]");if(t instanceof HTMLElement){if(t.textContent&&t.textContent.trim())return true;if(this.hasExportableChatGPTImage(t))return true}return !!this.hasExportableChatGPTImage(e)||null!==this.getDeepResearchIframe(e)}async waitForTurnMessageMounted(e,t){const n=Date.now()+t;for(;Date.now()e instanceof HTMLElement);for(const i of r){const e=i.getAttribute("data-message-id")||i.closest("[data-message-id]")?.getAttribute("data-message-id")||"";if(!e)continue;const r=this.extractUserQueryText(i).trim();if(!r)continue;let o=r,a=false;o.length>200&&(o=o.substring(0,200),a=true),this.outlineItemCache.set(e,{id:e,level:0,text:o,turnId:t,firstSeenTurnIndex:n,orderInTurn:0,isUserQuery:true,isTruncated:a});}const o=Array.from(e.querySelectorAll('[data-message-author-role="assistant"]')).filter(e=>e instanceof HTMLElement);for(const i of o){const e=i.getAttribute("data-message-id")||i.closest("[data-message-id]")?.getAttribute("data-message-id")||"";if(!e)continue;const r=Array.from(i.querySelectorAll("h1,h2,h3,h4,h5,h6")),o={};let a=0;for(const i of r){if(this.shouldSkipElement(i))continue;if(this.isInRenderedMarkdownContainer(i))continue;const r=i.tagName.toLowerCase(),s=(i.textContent||"").trim();if(!s)continue;const l=`${r}-${s}`,c=o[l]||0;o[l]=c+1;const d=`${e}::${l}::${c}`;this.outlineItemCache.set(d,{id:d,level:parseInt(r.charAt(1),10),text:s,turnId:t,firstSeenTurnIndex:n,orderInTurn:a++,isUserQuery:false});}}}readVisibleExportMessageSnapshots(e,t){const n=e instanceof HTMLElement?e:document.querySelector(this.getResponseContainerSelector()),r=this.findExportTurnContainers(e);if(0===r.length)return Array.from(e.querySelectorAll('[data-message-author-role="user"], [data-message-author-role="assistant"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${cl}]`)&&!e.closest(".gh-root, .gh-main-panel"))).map(e=>this.extractExportMessageSnapshot(e,n,t)).filter(e=>null!==e);const o=[];for(const i of r){const e=this.extractTurnExportSnapshots(i,n,t);o.push(...e);}return o}findExportTurnContainers(e){const t=Array.from(e.querySelectorAll('section[data-turn], [data-testid^="conversation-turn"]')).filter(e=>e instanceof HTMLElement&&(!e.closest(`[${cl}]`)&&!e.closest(".gh-root, .gh-main-panel")));return t.filter(e=>!t.some(t=>t!==e&&e.contains(t)))}extractTurnExportSnapshots(e,t,n){const r=this.collectOwnAuthorMessagesForTurn(e);if(0===r.length){const t=this.extractChatGPTImageMarkdown(e,n,{fallbackAlt:"generated image"}).map(e=>this.normalizeExportMessageContent(e)).filter(e=>e.length>0);if(t.length>0){const n=t.join("\n\n"),r=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return [{role:gl,turnKey:r?`assistant:turn:${r}`:`assistant:images:${n.replace(/\s+/g," ").slice(0,120)}`,order:this.getExportTurnSortIndex(e),content:n}]}return this.extractDeepResearchTurnExportSnapshot(e)}const o=r[0].getAttribute("data-message-author-role"),i="user"===e.getAttribute("data-turn")||"user"===o?hl:gl,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"",s=this.getExportTurnSortIndex(e);if(i===hl){const e=r.map(e=>this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAssets(e,n)||this.extractUserQueryText(e))).filter(e=>e.length>0);if(0===e.length)return [];const t=e.join("\n\n");return [{role:hl,turnKey:a?`user:turn:${a}`:`user:content:${t.replace(/\s+/g," ").slice(0,120)}`,order:s,content:t}]}const l=r.map(e=>this.normalizeExportMessageContent(this.extractAssistantResponseTextFromLiveDom(e))).filter(e=>e.length>0);if(l.push(...this.extractChatGPTImageMarkdown(e,n,{fallbackAlt:"generated image",onlyOutsideAuthorMessages:true}).map(e=>this.normalizeExportMessageContent(e)).filter(e=>e.length>0)),0===l.length)return [];const c=l.join("\n\n"),d=a?`assistant:turn:${a}`:`assistant:content:${c.replace(/\s+/g," ").slice(0,120)}`;return [{role:gl,turnKey:d,order:s,content:c}]}collectOwnAuthorMessagesForTurn(e){return Array.from(e.querySelectorAll('[data-message-author-role="user"], [data-message-author-role="assistant"]')).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(`[${cl}]`))return false;if(t.closest(".gh-root, .gh-main-panel"))return false;return t.closest('section[data-turn], [data-testid^="conversation-turn"]')===e})}extractExportMessageSnapshot(e,t,n){const r="assistant"===e.getAttribute("data-message-author-role")?gl:hl,o=this.normalizeExportMessageContent(r===gl?this.extractAssistantResponseTextFromLiveDom(e):this.extractUserQueryExportContentWithAssets(e,n)||this.extractUserQueryText(e));if(!o)return null;const i=e.getAttribute("data-message-id")||e.closest("[data-message-id]")?.getAttribute("data-message-id")||"",a=i?`${r}:${i}`:`${r}:content:${o.replace(/\s+/g," ").slice(0,120)}`,s=e.closest('section[data-turn], [data-testid^="conversation-turn"]');return {role:r,turnKey:a,order:s?this.getExportTurnSortIndex(s):Number.MAX_SAFE_INTEGER,content:o}}extractAssistantResponseTextFromLiveDom(e){const t=(e.querySelector(".markdown, .prose, [class*='prose']")||e).cloneNode(true);t.querySelectorAll('.sr-only, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t)}extractUserQueryExportContentWithAssets(e,t){const n=[...this.extractUserQueryImageMarkdown(e,t),...this.extractUserQueryFileMarkdown(e,t)],r=this.extractUserQueryMarkdown(e).trim();return r&&n.push(r),n.join("\n\n").trim()}extractUserQueryImageMarkdown(e,t){return this.extractChatGPTImageMarkdown(e,t,{fallbackAlt:"uploaded image",role:"user",category:"image"})}extractChatGPTImageMarkdown(e,t,n={fallbackAlt:"image"}){const r=this.getChatGPTExportImages(e).filter(e=>e instanceof HTMLImageElement&&(!!this.isExportableChatGPTImage(e)&&(!n.onlyOutsideAuthorMessages||!e.closest("[data-message-author-role]")))),o=new Set,i=[];for(const a of r){const e=this.getChatGPTImageExportSource(a);if(!e||o.has(e))continue;o.add(e);const r=Ta({source:e,alt:(a.alt||a.getAttribute("aria-label")||n.fallbackAlt).replace(/\s+/g," ").trim()},t||void 0,{siteId:this.getSiteId(),role:n.role||"assistant",category:n.category||"generated-image",fallbackAlt:n.fallbackAlt});r&&i.push(r);}return i}getChatGPTExportImages(e){const t=Array.from(e.querySelectorAll('[class*="imagegen-image"], [data-testid*="image-gen"]')).map(e=>{const t=Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement);return t.find(e=>{const t=e.className||"";return !t.includes("absolute")&&!t.includes("blur")})||t.find(e=>e.width>0&&e.height>0)||t[0]||null}).filter(e=>e instanceof HTMLImageElement);return t.length>0?t:Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement)}extractUserQueryFileMarkdown(e,t){const n=Array.from(e.querySelectorAll('[role="group"][aria-label], [class*="file-tile"]')).filter(e=>e instanceof HTMLElement),r=new Set,o=[];for(const i of n){const e=this.extractChatGPTFileName(i);if(!e)continue;const n=this.extractChatGPTFileHref(i),a=Ia([{kind:"file",name:e,source:n,type:e}],t||void 0,{siteId:this.getSiteId(),getLabel:()=>e,getMimeHint:()=>e})[0];r.has(a)||(r.add(a),o.push(a));}return o.length>0?["**Attachments:**\n\n"+o.join("\n")]:[]}extractDeepResearchTurnExportSnapshot(e){const t=this.getDeepResearchIframe(e);if(!t)return [];const n=t.getAttribute("src")||t.src||"",r=t.getAttribute("title")||"",o=r&&!r.startsWith("internal://")?r:"ChatGPT Deep Research",i=n?`[${sa(o)}](${n})`:o,a=e.getAttribute("data-turn-id")||e.getAttribute("data-turn-id-container")||"";return [{role:gl,turnKey:a?`assistant:turn:${a}`:`assistant:deep-research:${n}`,order:this.getExportTurnSortIndex(e),content:i}]}getDeepResearchIframe(e){const t=e.querySelector('iframe[title="internal://deep-research"], iframe[src*="connector_openai_deep_research"]');return t instanceof HTMLIFrameElement?t:null}isExportableChatGPTImage(e){const t=this.getChatGPTImageExportSource(e);return !!t&&(!t.includes("/cdn/assets/")&&(!t.startsWith("data:image/svg+xml")&&(ba(t)||t.startsWith("data:image/"))))}hasExportableChatGPTImage(e){return this.getChatGPTExportImages(e).some(e=>this.isExportableChatGPTImage(e))}getChatGPTImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=fa(n);if(e)return e}return ""}extractChatGPTFileName(e){const t=[e.getAttribute("aria-label")||"",e.querySelector("[aria-label]")?.getAttribute("aria-label")||"",e.querySelector(".truncate.font-semibold")?.textContent||"",e.textContent||""].map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean).find(e=>/\.[A-Za-z0-9]{1,10}(\s|$)/.test(e));return t?.match(/[^/\\]+?\.[A-Za-z0-9]{1,10}/)?.[0]||""}extractChatGPTFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=fa(n.getAttribute("href")||n.href||"");if(ba(e))return e}return ""}getExportTurnSortIndex(e){const t=e.getAttribute("data-testid")||"",n=/^conversation-turn-(\d+)/.exec(t);return n?parseInt(n[1],10):Number.MAX_SAFE_INTEGER}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(cl,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(dl,"1");const r=document.createElement("div");r.setAttribute(ul,e.role),r.textContent=e.content,n.appendChild(r),t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${cl}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}normalizeNativeTocText(e){return e.replace(/\s+/g," ").trim()}isCompatibleNativeTocText(e,t){const n=this.normalizeNativeTocText(e),r=this.normalizeNativeTocText(t);if(!n||!r)return false;if(n===r)return true;return !(Math.min(n.length,r.length)<200)&&(n.startsWith(r)||r.startsWith(n))}isNativeTocOutlineId(e){return Boolean(e?.startsWith("chatgpt-native-user-query::"))}getNativeTocOutlineIndex(e){const t=(e||"").match(bl);if(!t?.[1])return null;const n=Number.parseInt(t[1],10);return Number.isNaN(n)?null:n}getNativeTocButtonIndex(e,t){const n=/^Prompt\s+(\d+)$/i.exec((e.getAttribute("aria-label")||"").trim());if(!n?.[1])return t;const r=Number.parseInt(n[1],10);return Number.isNaN(r)?t:Math.max(0,r-1)}getNativeTocButtons(){return Array.from(document.querySelectorAll('button[aria-label^="Prompt "]')).filter(e=>{if(!(e instanceof HTMLElement))return false;const t=e.getAttribute("aria-label")||"";if(!/^Prompt \d+$/i.test(t.trim()))return false;const n=e.closest(".no-scrollbar");return Boolean(n?.querySelectorAll('button[aria-label^="Prompt "]').length)}).sort((e,t)=>{const n=Number.parseInt((e.getAttribute("aria-label")||"").replace(/\D+/g,""),10),r=Number.parseInt((t.getAttribute("aria-label")||"").replace(/\D+/g,""),10);return (Number.isNaN(n)?0:n)-(Number.isNaN(r)?0:r)})}getNativeTocTexts(e){const t=e[0],n=t?.closest(".no-scrollbar")?.parentElement||t?.closest(".relative.flex.items-start")||t?.closest(".fixed"),r=n?Array.from(n.querySelectorAll(["button[data-fill] [title]",'button[class*="__menu-item"] [title]',"ul button [title]","[role='menu'] [title]",".absolute [title]"].join(", "))):[],o=new Set;return r.filter(e=>!o.has(e)&&(o.add(e),e instanceof HTMLElement)).map(e=>this.normalizeNativeTocText(e.getAttribute("title")||e.textContent||"")).filter(e=>e.length>0)}getNativeTocEntries(){const e=this.getNativeTocButtons();if(0===e.length)return [];const t=this.getNativeTocTexts(e);if(t.length!==e.length)return [];const n=new Map;t.forEach(e=>{const t=this.normalizeNativeTocText(e);n.set(t,(n.get(t)||0)+1);});const r=e=>{const n=this.normalizeNativeTocText(e);return !n||t.some(e=>{const t=this.normalizeNativeTocText(e);return !(!t||t===n)&&(n.startsWith(t)||t.startsWith(n))})},o=new Map;Array.from(document.querySelectorAll(this.getUserQuerySelector())).forEach(e=>{const t=this.normalizeNativeTocText(this.extractUserQueryText(e));if(!t)return;const n=o.get(t)||[];n.push(e),o.set(t,n);});const i=[];return e.forEach((e,a)=>{const s=t[a];if(!s)return;const l=this.normalizeNativeTocText(s),c=o.get(l)||[],d=1===n.get(l)&&!r(s)&&1===c.length;i.push({index:this.getNativeTocButtonIndex(e,a),text:s,button:e,element:d?c[0]:null,isActive:e.hasAttribute("data-toc-active")});}),i}getNativeTocButtonEntryForIndex(e){const t=this.getNativeTocButtons().find((t,n)=>this.getNativeTocButtonIndex(t,n)===e);return t?{index:e,text:"",button:t,element:null,isActive:t.hasAttribute("data-toc-active")}:null}getActiveNativeTocIndex(){const e=this.getNativeTocButtons(),t=e.find(e=>e.hasAttribute("data-toc-active"));if(!t)return null;const n=e.indexOf(t);return this.getNativeTocButtonIndex(t,n)}createNativeTocUserQueryOutlineItem(e,t){let n=e.element?this.extractUserQueryText(e.element):e.text,r=false;n.length>200&&(n=n.substring(0,200),r=true);const o=`chatgpt-native-user-query::${e.index}::${this.normalizeNativeTocText(e.text)}`,i=this.getChatGPTMessageId(e.element);return {level:0,text:n,element:e.element,isUserQuery:true,isTruncated:r,id:i||o,navigationId:o,wordCount:t}}resolveNativeTocEntryForOutlineItem(e){const t=this.getNativeTocOutlineIndex(e.navigationId||e.id);return null!==t?this.getNativeTocButtonEntryForIndex(t):null}async waitForNativeTocUserQuery(e,t,n=1600){const r=Date.now()+n;for(;Date.now()this.isVisible(e)&&this.isElementInViewport(e,n));if(0===r.length)return null;const o=r.filter(t=>this.isCompatibleNativeTocText(this.extractUserQueryText(t),e));return 0===o.length?null:t?this.getClosestVisibleElementToViewportCenter(o,n):1===o.length?o[0]:null}isElementInViewport(e,t){const n=e.getBoundingClientRect(),r=t instanceof HTMLElement?t.getBoundingClientRect().top:0,o=t instanceof HTMLElement?t.getBoundingClientRect().bottom:window.innerHeight;return n.bottom>r&&n.top{const t=e.getBoundingClientRect();return {element:e,distance:Math.abs(t.top+t.height/2-r)}}).sort((e,t)=>e.distance-t.distance)[0]?.element||null}getElementRenderOrder(e,t){const n=(this.getChatGPTTurnId(e)&&e.closest("[data-turn-id], [data-turn-id-container]")||e).getBoundingClientRect();if(t instanceof HTMLElement){const e=t.getBoundingClientRect();return t.scrollTop+(n.top-e.top)}return window.scrollY+n.top}getOutlineCacheSessionKey(){return `${this.getCurrentCid()||"default"}:${this.getSessionId()||"default"}:${window.location.pathname}`}ensureOutlineCacheSession(){const e=this.getOutlineCacheSessionKey();if(e===this.outlineCacheSessionKey)return;const t=""===this.outlineCacheSessionKey;this.outlineCacheSessionKey=e,this.outlineItemCache.clear(),this.outlineTurnFirstSeenIndex.clear(),this.outlineTurnFirstSeenCounter=0,this.outlineCacheTransitionEndAt=t?0:Date.now()+2e3;}isInOutlineCacheTransition(){return Date.now(){const r=e.getAttribute("data-turn-id-container")||e.getAttribute("data-turn-id");r&&!t.has(r)&&(t.set(r,{element:e,index:n}),n+=1);}),t}recordTurnDocumentOrders(e){if(0===e.size)return;const t=[];if(e.forEach((e,n)=>{this.outlineTurnFirstSeenIndex.has(n)||t.push(n);}),0!==t.length)for(const n of t)this.outlineTurnFirstSeenIndex.set(n,this.outlineTurnFirstSeenCounter++);}getTurnSortIndex(e,t){if(!e)return Number.MAX_SAFE_INTEGER;const n=t.get(e);if(n)return n.index;const r=this.outlineTurnFirstSeenIndex.get(e);return "number"==typeof r?r+1e6:Number.MAX_SAFE_INTEGER}updateChatGPTOutlineCache(e,t){const n=new Map;for(const r of e){if(!r.id)continue;if(this.isNativeTocOutlineId(r.id))continue;const e=this.getChatGPTTurnId(r.element),o=e||r.id,i=n.get(o)||0;n.set(o,i+1);const a=e&&this.outlineTurnFirstSeenIndex.has(e)?this.outlineTurnFirstSeenIndex.get(e):t.get(e||"")?.index??Number.MAX_SAFE_INTEGER,s=this.outlineItemCache.get(r.id);this.outlineItemCache.set(r.id,{id:r.id,level:r.level,text:r.text,turnId:e,firstSeenTurnIndex:a,orderInTurn:i,isUserQuery:r.isUserQuery,isTruncated:r.isTruncated,wordCount:r.wordCount??s?.wordCount});}}mergeCachedChatGPTOutlineItems(e,t,n,r,o,i=false){if(0===this.outlineItemCache.size)return e;const a=new Set(e.map(e=>e.id).filter(e=>!!e)),s=i||e.some(e=>this.isNativeTocOutlineId(e.id));let l=0;const c=[...e];for(const d of this.outlineItemCache.values())this.isNativeTocOutlineId(d.id)||a.has(d.id)||(!d.isUserQuery||r&&!s)&&(!d.isUserQuery&&d.level>n||d.text&&d.text.trim()&&(c.push({level:d.level,text:d.text,element:null,isUserQuery:d.isUserQuery,isTruncated:d.isTruncated,id:d.id,wordCount:o?d.wordCount:void 0}),l+=1));return 0===l?e:c.map((e,n)=>{const r=e.id?this.outlineItemCache.get(e.id):void 0,o=r?.turnId||this.getChatGPTTurnId(e.element),i=this.getNativeTocOutlineIndex(e.navigationId||e.id),a=null!==i?2*i:this.getTurnSortIndex(o,t);return {item:e,originalIndex:n,orderInTurn:null!==i?0:r?.orderInTurn??n,turnIndex:a}}).sort((e,t)=>e.turnIndex!==t.turnIndex?e.turnIndex-t.turnIndex:e.orderInTurn!==t.orderInTurn?e.orderInTurn-t.orderInTurn:e.originalIndex-t.originalIndex).map(({item:e})=>e)}resolveCachedChatGPTOutlineTarget(e){if(!e)return null;this.ensureOutlineCacheSession();const t=this.outlineItemCache.get(e);if(!t)return null;const n=document.querySelector(this.getResponseContainerSelector());if(!n)return null;const r=this.extractMessageIdFromCachedId(t);if(r){const e=this.escapeAttributeValue(r),o=n.querySelector(`[data-message-id="${e}"]`);if(o){if(t.isUserQuery)return o;const e=this.findHeadingInsideMessage(o,t);return e||o}}if(t.turnId){const e=this.getOrderedChatGPTTurnAnchors(n).get(t.turnId)?.element;if(e)return e}return null}extractMessageIdFromCachedId(e){if(!e.id)return null;if(e.isUserQuery)return e.id;const t=e.id.indexOf("::");return t>0?e.id.slice(0,t):null}escapeAttributeValue(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}findHeadingInsideMessage(e,t){const n=t.id.indexOf("::"),r=t.id.lastIndexOf("::");if(n<=0||r<=n)return null;const o=t.id.slice(n+2,r),i=t.id.slice(r+2),a=o.indexOf("-");if(a<=0)return null;const s=o.slice(0,a).toLowerCase(),l=o.slice(a+1);if(!/^h[1-6]$/.test(s))return null;const c=Number.parseInt(i,10)||0,d=Array.from(e.querySelectorAll(s));let u=0;for(const h of d)if((h.textContent||"").trim()===l){if(u===c)return h;u+=1;}return null}async resolveOutlineTarget(e,t){if(e.isUserQuery&&0===e.level){const t=this.resolveNativeTocEntryForOutlineItem(e);if(t){if(t.element)return t.element;t.button.scrollIntoView({block:"nearest",inline:"nearest"}),t.button.click();const n=await this.waitForNativeTocUserQuery(t,e.text);if(n)return n}}const n=this.resolveCachedChatGPTOutlineTarget(e.id);if(n){if(n instanceof HTMLElement&&n.hasAttribute("data-turn-id-container")){this.scrollIntoViewForRevive(n);const t=await this.waitForCachedChatGPTOutlineTargetRemount(e.id);if(t)return t}return n}return super.resolveOutlineTarget(e,t)}scrollIntoViewForRevive(e){try{e.scrollIntoView({block:"center",behavior:"instant"});}catch{e.scrollIntoView({block:"center"});}}async waitForCachedChatGPTOutlineTargetRemount(e,t=1500){if(!e)return null;const n=Date.now()+t;for(;Date.now(){if(!e)return 0;try{if(n){const n=o.querySelectorAll('[data-message-author-role="assistant"]');let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.querySelector(".markdown, .prose, [class*='prose']");if(i)r+=i.textContent||"";else {const e=o.cloneNode(!0);e.querySelectorAll(".sr-only, [class*='sr-only']").forEach(e=>e.remove()),r+=e.textContent||"";}}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(s);let i=!1,a=null;for(const t of Array.from(r)){if(i){a=t;break}(t===e||t.contains(e)||e.contains(t))&&(i=!0);}if(a)return this.calculateRangeWordCount(e,a,o);const l=o.querySelectorAll('[data-message-author-role="assistant"]');if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}},s=this.getUserQuerySelector(),l=[];for(let g=1;g<=e;g++)l.push(`h${g}`);const c=`${s}, ${l.join(", ")}`,d=Array.from(o.querySelectorAll(c)),u=t?this.getNativeTocEntries():[];if(d.forEach((o,l)=>{const c=o.tagName.toLowerCase(),u=o.matches(s),h=/^h[1-6]$/.test(c);let g=false;if(t&&u&&(g=true),h&&!this.shouldSkipElement(o)&&!this.isInRenderedMarkdownContainer(o)){const t=(o.textContent||"").trim(),n=parseInt(c.charAt(1),10);t&&n<=e&&(g=true);}if(g){let e;if(u){let t=this.extractUserQueryText(o),n=false;t.length>200&&(t=t.substring(0,200),n=true),e={level:0,text:t,element:o,isUserQuery:true,isTruncated:n};}else {e={level:parseInt(c.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}const t=this.getChatGPTMessageId(o);if(t&&(e.id=u?t:((e,t,n)=>{i[e]||(i[e]={});const r=`${t}-${n}`,o=i[e][r]||0;return i[e][r]=o+1,`${e}::${r}::${o}`})(t,c,e.text)),n){let t=null;for(let n=l+1;n0){const e=[],t=u.reduce((e,t)=>Math.max(e,t.index),-1),i=e=>{if(!n||!e.element)return;const r=u.find(t=>t.index>e.index);return r?.element?a(e.element,r.element,true):r||e.index!==t?void 0:a(e.element,null,true)},s=u.filter(e=>Boolean(e.element)).map(e=>({index:e.index,renderOrder:this.getElementRenderOrder(e.element,o)})).sort((e,t)=>e.renderOrder-t.renderOrder),l=u.find(e=>e.isActive),c=e=>{const t=this.getElementRenderOrder(e,o);let n,r;for(const o of s){if(!(o.renderOrder<=t)){r=o;break}n=o;}return n?n.index:r?Math.max(0,r.index-1):l?.index??0};u.forEach(t=>{e.push({item:this.createNativeTocUserQueryOutlineItem(t,i(t)),order:1e5*t.index});}),r.filter(e=>!e.isUserQuery).forEach((t,n)=>{const r=t.element?c(t.element):0;e.push({item:t,order:1e5*r+5e4+n});}),r=e.sort((e,t)=>e.order-t.order).map(({item:e})=>e);}const h=this.getOrderedChatGPTTurnAnchors(o);return this.isInOutlineCacheTransition()?r:(this.recordTurnDocumentOrders(h),this.updateChatGPTOutlineCache(r,h),this.mergeCachedChatGPTOutlineItems(r,h,e,t,n,u.length>0))}isGenerating(){return null!==this.findElementBySelectors(this.getStopButtonSelectors())}getStopButtonSelectors(){return ['[data-testid="stop-button"]','button[aria-label*="Stop"]','button[aria-label*="停止"]']}findModelSelectorButton(){return this.findElementBySelectors([...al])}getModelStateContextKey(){return `${this.getCurrentCid()||"default"}::${this.getSessionId()||window.location.pathname||"root"}`}getLatestMessageModelSlug(){const e=document.querySelectorAll("[data-message-model-slug]"),t=e[e.length-1];return t?.getAttribute("data-message-model-slug")?.trim()||null}readModelStateFromOpenMenu(){const e=document.querySelector(sl);if(!this.isVisible(e))return null;const t=Array.from(document.querySelectorAll(ll));if(0===t.length)return null;let n=null,r=null;for(const o of t){const e=o.getAttribute("data-testid")||"",t=e.startsWith("model-switcher-")?e.replace(/^model-switcher-/,"").trim():"",i=o.querySelector(".min-w-0"),a=i?Array.from(i.childNodes).filter(e=>e.nodeType===Node.TEXT_NODE).map(e=>e.textContent?.trim()).find(Boolean)||i.textContent?.replace(/\s+/g," ").trim()||"":o.textContent?.replace(/\s+/g," ").trim()||"";t&&a&&this.cachedModelDisplayNamesBySlug.set(t,a);(Boolean(o.querySelector(".trailing svg, .trailing use"))||"checked"===o.getAttribute("data-state")||"true"===o.getAttribute("aria-checked")||"true"===o.getAttribute("aria-selected"))&&(n=a||null,r=t||null);}return r&&(this.lastKnownModelSlug=r,this.lastKnownModelSlugContextKey=this.getModelStateContextKey(),this.lastKnownModelSlugObservedAt=Date.now()),{name:n,slug:r}}extractModelNameFromSelectorButton(e){return e.querySelector("span.truncate, span[class*='truncate']")?.textContent?.trim()||null}getReliableCurrentModelSignals(){const e=this.readModelStateFromOpenMenu(),t=this.findModelSelectorButton();return [e?.name,e?.slug,t?this.extractModelNameFromSelectorButton(t):null].filter(e=>Boolean(e&&e.trim()))}getCurrentModelSignalsForLockCheck(){const e=this.readModelStateFromOpenMenu(),t=this.findModelSelectorButton();return [e?.name,e?.slug,this.lastKnownModelSlug&&(this.isNewConversation()?Date.now()-this.lastKnownModelSlugObservedAt<6e4:this.lastKnownModelSlugContextKey===this.getModelStateContextKey())?this.lastKnownModelSlug:null,this.getLatestMessageModelSlug(),t?this.extractModelNameFromSelectorButton(t):null].filter(e=>Boolean(e&&e.trim()))}getModelName(){const e=this.readModelStateFromOpenMenu();if(e?.name)return e.name;const t=this.getLatestMessageModelSlug();if(t)return this.cachedModelDisplayNamesBySlug.get(t)||t;const n=this.findModelSelectorButton();if(n){const e=this.extractModelNameFromSelectorButton(n);if(e)return e}return null}getNetworkMonitorConfig(){return {urlPatterns:["backend-api/f/conversation"],urlPathEndsWith:["backend-api/f/conversation"],silenceThreshold:3e3,requestBodyRules:[{type:"json-field-exists",field:"thinking_effort",metadata:{domCompletionRequired:true}}]}}getDefaultLockSettings(){return {enabled:false,keyword:""}}getModelLockCheckText(e){return this.getCurrentModelSignalsForLockCheck().join(" ")}findElementBySelectors(e){for(const t of e){const e=Array.from(document.querySelectorAll(t));for(const t of e)if(this.isVisible(t))return t}return super.findElementBySelectors(e)}lockModel(e,t){const n=e.trim();if(!n)return;const r=n.toLowerCase();if(this.getReliableCurrentModelSignals().join(" ").toLowerCase().trim().includes(r))return void t?.();const o=this.findModelSelectorButton(),i="true"===o?.getAttribute("aria-expanded")||Boolean(this.readModelStateFromOpenMenu()),a=this.lastModelLockAttemptKeyword===n&&Date.now()-this.lastModelLockAttemptAt<1200;i||a||(this.lastModelLockAttemptKeyword=n,this.lastModelLockAttemptAt=Date.now(),super.lockModel(n,()=>{this.lastModelLockAttemptAt=0,t?.();}));}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[...al],menuItemSelector:'[data-radix-collection-item][data-testid^="model-switcher-"], [role="menuitemradio"][data-testid^="model-switcher-"], [role="menuitem"][data-testid^="model-switcher-"]',checkInterval:1e3,maxAttempts:15,menuRenderDelay:500}}simulateClick(e){if(e.matches('button[class*="__composer-pill"][aria-haspopup="menu"]')){const t=e.getAttribute("aria-expanded");e.click();const n=e.getAttribute("aria-expanded");if("true"===n||n!==t)return;return void e.dispatchEvent(new PointerEvent("pointerdown",{bubbles:true,cancelable:true,view:window,pointerId:1,button:0,buttons:1,pointerType:"mouse",isPrimary:true}))}e.click();} /** * 切换 ChatGPT 主题 * 直接修改 localStorage.theme + html.className 实现即时无感切换 * @param targetMode 目标主题模式 */ async toggleTheme(e){try{return localStorage.setItem("theme",e),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:e,storageArea:localStorage})),!0}catch(t){return console.error("[ChatGPTAdapter] toggleTheme error:",t),false}}},new class extends gs{match(){const e=window.location.hostname;return "grok.com"===e||e.endsWith(".grok.com")}getSiteId(){return go}getName(){return "Grok"}getThemeColors(){return {primary:"#f39c12",secondary:"#1e1f22"}}getNativeThemeCss(){return '\n\n/* 全局背景 */\n// .bg-surface, .bg-surface-base {\n// background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important\n// }\n\n/* 链接颜色 */\n.[&_a:not(.not-prose)]:text-current a:not(.not-prose) {\n color: var(--gh-primary) !important;\n}\n\n/* 侧边栏背景 */\n[data-sidebar="sidebar"] {\n background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n}\n\n'}getNewTabUrl(){return "https://grok.com/"}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/c\/[^/?#]+(?:\/|$)/i.test(window.location.pathname)}cachedDialogConversations=null;exportUserAttachmentsByResponseId=null;reloadScheduled=false;async loadAllConversations(){const e=document.querySelector('[data-sidebar="content"]');if(!e)return;const t=e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold");if(t){const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Di);return {showToast:e}},void 0),{t:n}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>de);return {t:e}},void 0);e(n("grokSyncingConversations")),t.click();let o=null;for(let t=0;t<30&&(await new Promise(e=>setTimeout(e,100)),o=document.querySelector('[cmdk-list-sizer=""], [cmdk-list]'),!o);t++);if(o){let e=0,t=0;const n=15;for(let r=0;rsetTimeout(e,400));const n=o.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}return this.cacheDialogConversations(),this.dispatchEscapeKey(),void setTimeout(()=>{this.cachedDialogConversations=null;},5e3)}}cacheDialogConversations(){const e=new Map;document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations=e;}getConversationList(){const e=new Map,t=document.querySelector('[data-sidebar="content"]');if(t){t.querySelectorAll('[data-sidebar="group"]').forEach(t=>{const n=t.querySelectorAll('a[href^="/c/"]');0!==n.length&&n.forEach(t=>{const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;const o=t.querySelector("span.flex-1, span.truncate, span"),i=o?.textContent?.trim()||t.textContent?.trim()||"New Chat",a=t.classList.contains("bg-button-ghost-hover"),s=this.isPinnedSidebarConversation(t);e.set(r,{id:r,title:i,url:n,isPinned:s,isActive:a});});});}return document.querySelectorAll('a[href^="/c/"]').forEach(t=>{if(this.isCmdkActionItem(t))return;const n=t.getAttribute("href");if(!n)return;const r=this.extractConversationIdFromHref(n);if(!r)return;if(e.has(r))return;let o="New Chat",i=false;const a=t.closest("[cmdk-item]");if(a){const e=a.querySelector("span.truncate");o=e?.textContent?.trim()||o,i=null!==a.querySelector('[class*="border-border-l2"]');}else o=t.textContent?.trim()||o;e.set(r,{id:r,title:o,url:n,isPinned:false,isActive:i});}),this.cachedDialogConversations&&this.cachedDialogConversations.forEach((t,n)=>{e.has(n)||e.set(n,t);}),Array.from(e.values())}getSidebarScrollContainer(){return document.querySelector('[data-sidebar="content"]')}getZenModeConfig(){return {hide:[".text-sidebar-foreground",'[data-sidebar="sidebar"]']}}getConversationObserverConfig(){return {selector:'[data-sidebar="content"] a[href^="/c/"], [cmdk-item][data-value^="conversation:"] a[href^="/c/"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href");if(!t)return null;const n=this.extractConversationIdFromHref(t);if(!n)return null;const r=!!e.closest('[data-sidebar="content"]'),o=!!e.closest("[cmdk-item]");let i="",a=false;if(r){const t=e.querySelector("span.flex-1, span.truncate, span");i=t?.textContent?.trim()||e.textContent?.trim()||"",a=this.isPinnedSidebarConversation(e);}else if(o){const t=e.closest("[cmdk-item]"),n=t?.querySelector("span.truncate");i=n?.textContent?.trim()||"",a=false;}return {id:n,title:i,url:t,isPinned:a}},getTitleElement:e=>{const t=e.closest("[cmdk-item]");return t?t.querySelector("span.truncate")||e:e.querySelector("span.flex-1, span.truncate, span")||e}}}navigateToConversation(e,t){return t?(window.location.href=t,true):(window.location.href=`/c/${e}`,true)}async deleteConversationOnSite(e){const t=await this.deleteConversationOnSiteInternal(e);return t.success&&this.scheduleFullReloadAfterDelete([e.id]),t}async deleteConversationsOnSite(e){const t=[],n=[];for(let r=0;r0&&this.scheduleFullReloadAfterDelete(n),t}async deleteConversationOnSiteInternal(e){const t=await this.tryDeleteViaNativeApi(e.id);if(t.success)return t;return await this.deleteConversationViaUi(e.id)?{id:e.id,success:true,method:"ui"}:{id:e.id,success:false,method:"none",reason:t.reason||_m}}async tryDeleteViaNativeApi(e){const t=`/rest/app-chat/conversations/soft/${encodeURIComponent(e)}`;try{const n=await fetch(t,{method:"DELETE",headers:this.buildNativeDeleteHeaders(),credentials:"include"});return n.ok?(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):404===n.status?this.isConversationVisible(e)?{id:e,success:!1,method:"api",reason:Nm}:(this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}):{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)}}catch{return {id:e,success:false,method:"api",reason:Lm}}}buildNativeDeleteHeaders(){const e={accept:"*/*","x-xai-request-id":this.generateRequestId()},t=this.getStatsigId();return t&&(e["x-statsig-id"]=t),e}getStatsigId(){const e=["x-statsig-id","statsig.stableID","statsig.stable_id","statsigStableId"];for(const t of e){const e=localStorage.getItem(t);if("string"==typeof e&&e.length>0)return e}try{for(let e=0;e0)return t}catch{}if(n.length>0)return n}}}catch{}return null}generateRequestId(){return "undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}syncConversationListAfterDelete(e){this.cachedDialogConversations?.delete(e);const t=this.findConversationAnchors(e);for(const n of t){this.getConversationItemContainer(n).remove();}}scheduleFullReloadAfterDelete(e){if(this.reloadScheduled||0===e.length)return;const t=this.extractConversationIdFromHref(window.location.pathname);if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/");}catch{}this.reloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120);}async deleteConversationViaUi(e){let t=false;try{let n=await this.findConversationAnchorWithRetry(e,400);if(n||(t=await this.openConversationDialogIfNeeded(),this.getCmdkListElement()&&await this.scrollCmdkListToLoadAll(),n=await this.findConversationAnchorWithRetry(e,1200)),!n)return !1;const r=this.getConversationItemContainer(n);this.revealConversationActions(r,n);const o=await this.waitForDeleteButton(r,2e3);if(!o)return !1;this.simulateClick(o);const i=await this.waitForConfirmButton(r,2200);if(!i)return !1;this.simulateClick(i);const a=await this.waitForConversationRemoved(e,4e3);return a&&this.syncConversationListAfterDelete(e),a}finally{t&&this.closeConversationDialog();}}async openConversationDialogIfNeeded(){if(this.getCmdkListElement())return false;const e=this.getViewAllButton();if(!e)return false;this.simulateClick(e);const t=Date.now();for(;Date.now()-t<2500;){if(this.getCmdkListElement())return true;await this.sleep(80);}return false}getViewAllButton(){const e=document.querySelector('[data-sidebar="content"]');return e?e.querySelector("button.w-full.justify-start.text-xs.text-secondary.font-semibold"):null}getCmdkListElement(){return document.querySelector('[cmdk-list-sizer=""], [cmdk-list]')}closeConversationDialog(){this.dispatchEscapeKey();}dispatchEscapeKey(){const e=document.activeElement||document.body||document.documentElement;if(e)try{const t=new KeyboardEvent("keydown",{key:"Escape",code:"Escape",keyCode:27,which:27,bubbles:!0,cancelable:!0});e.dispatchEvent(t);}catch{e.dispatchEvent(new Event("keydown",{bubbles:true,cancelable:true}));}}async scrollCmdkListToLoadAll(){const e=this.getCmdkListElement();if(!e)return;let t=-1,n=0;for(let r=0;r<16;r++){e.scrollTop=e.scrollHeight,await this.sleep(300);const r=e.scrollHeight;if(r===t){if(n++,n>=3)break}else t=r,n=0;}}async findConversationAnchorWithRetry(e,t){const n=this.findConversationAnchors(e)[0];if(n)return n;const r=Date.now();for(;Date.now()-rthis.extractConversationIdFromHref(t.getAttribute("href"))===e)}getConversationItemContainer(e){const t=[e.closest("[cmdk-item]"),e.closest('[data-sidebar="menu-button"]'),e.closest('[data-sidebar="menu-item"]'),e.closest("li"),e.parentElement,e];for(const n of t)if(n instanceof HTMLElement)return n;return e}revealConversationActions(e,t){try{e.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});}catch{}e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:true})),t&&(t.focus(),t.dispatchEvent(new FocusEvent("focus",{bubbles:true})));}async waitForDeleteButton(e,t){const n=Date.now();for(;Date.now()-ne.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickConfirmButton(e,t){for(const n of e)if(this.hasKeyword(this.getElementSignal(n),qm))return n;for(const n of e)if(this.hasKeyword(this.getIconSignal(n),qm))return n;for(const n of e)if(this.hasKeyword(this.getElementSignal(n),Dm))return n;if(false!==t?.allowIconOnlyFallback){const t=e.filter(e=>e.querySelector("svg")&&!(e.textContent||"").trim()),n=this.pickRightMostButton(t);if(n)return n}return null}pickRightMostButton(e){if(0===e.length)return null;return [...e].sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]||null}findButtonsInScopes(e){const t=new Set,n=[];for(const r of e){const e=Array.from(r.querySelectorAll("button"));for(const r of e)t.has(r)||this.isVisible(r)&&(t.add(r),n.push(r));}return n}getElementSignal(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.getAttribute("data-testid")||"",e.className||""].join(" ").toLowerCase()}getIconSignal(e){return Array.from(e.querySelectorAll("svg, path, use, [data-icon], [class*='icon'], [aria-label]")).map(e=>[e.getAttribute("aria-label")||"",e.getAttribute("data-icon")||"",e.getAttribute("name")||"",e.className||""].join(" ")).join(" ").toLowerCase()}hasKeyword(e,t){const n=e.toLowerCase();return t.some(e=>n.includes(e.toLowerCase()))}async waitForConversationRemoved(e,t){const n=Date.now();for(;Date.now()-ne.isConnected&&this.isVisible(e))}extractConversationIdFromHref(e){if(!e)return null;const t=e.match(/\/c\/([a-zA-Z0-9-]+)/);return t?t[1]:null}isPinnedSidebarConversation(e){if(!e.closest('[data-sidebar="content"]'))return false;const t=e.closest('a[href^="/c/"]')??e;if(!this.hasPinnedIcon(t))return false;const n=t.closest('[data-sidebar="menu-item"]'),r=t.closest('[data-sidebar="menu"]');return !n||!r||this.isPinnedSectionItem(n)}hasPinnedIcon(e){const t=e.querySelector('[data-sidebar="icon"] svg');if(!t)return false;if(!this.isDomElementVisible(t))return false;const n=Array.from(t.querySelectorAll("path"));return 0!==n.length&&n.some(e=>{const t=(e.getAttribute("d")||"").replace(/\s+/g,"");return !!t&&Mm.some(e=>t===e)})}isPinnedSectionItem(e){let t=e.previousElementSibling;for(;t;){if(!t.matches('[data-sidebar="menu-item"]'))return false;t=t.previousElementSibling;}return true}isCmdkActionItem(e){const t=e.closest("[cmdk-item]");if(!t)return false;if((t.getAttribute("data-value")||"").toLowerCase().startsWith("action:"))return true;const n=t.closest("[cmdk-group]");if(!n)return false;const r=(n.getAttribute("data-value")||"").replace(/\s+/g,"").toLowerCase();return !("actionsshowall"!==r&&!r.startsWith("actions"))}isDomElementVisible(e){if(!e)return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isVisible(e){return e instanceof HTMLElement&&this.isDomElementVisible(e)}async sleep(e){await new Promise(t=>setTimeout(t,e));}getCurrentConversationTitleFromSources(){const e=this.extractConversationIdFromHref(window.location.pathname);if(!e)return null;const t=this.getConversationList().find(t=>t.id===e);if(t?.title?.trim())return t.title.trim();const n=document.querySelector(`[data-sidebar="content"] a[href="/c/${e}"], a[href="/c/${e}"]`);if(!n)return null;const r=n.querySelector("span.flex-1, span.truncate, span")?.textContent?.trim();return r||n.textContent?.trim()||null}getConversationTitleFromPage(){const e=document.querySelector(".conversation-title"),t=e?.textContent?.trim();return t||null}getSessionName(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()||this.getCleanedDocumentTitle()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()||this.getConversationTitleFromPage()||this.getCleanedDocumentTitle()}getCleanedDocumentTitle(){const e=super.getSessionName();if(!e)return null;return e.replace(/\s*[|]\s*Shared Grok Conversation$/i,"").replace(/\s*[|]\s*Grok$/i,"").trim()||null}getNewChatButtonSelectors(){return ['a[href="/"]','[data-sidebar="header"] a','button[aria-label*="新"]','button[aria-label*="New"]']}getLatestReplyText(){const e=document.querySelectorAll(".message-bubble:not(.rounded-br-lg)");if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".response-content-markdown");if(n){const e=n.cloneNode(true);e.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=Fi(e).trim();return t||this.extractTextWithLineBreaks(e)}return this.extractTextWithLineBreaks(t)}normalizeContentMaxWidth(e){const t=e.trim();if(!t.endsWith("%"))return t;const n=Number.parseFloat(t);return Number.isFinite(n)?`min(${n}vw, calc(100vw - 32px))`:t}getWidthSelectors(){return [{selector:'[class*="[--content-max-width:"]',property:"--content-max-width",transformValue:e=>this.normalizeContentMaxWidth(e)},{selector:'[style*="--content-max-width"]',property:"--content-max-width",transformValue:e=>this.normalizeContentMaxWidth(e)}]}getUserQueryWidthSelectors(){return [{selector:".message-bubble.rounded-br-lg",property:"max-width",noCenter:true,extraCss:"margin-left: auto !important; margin-right: 0 !important;"}]}getTextareaSelectors(){return [".tiptap.ProseMirror[contenteditable='true']",'[contenteditable="true"].ProseMirror',".query-bar [contenteditable='true']","form [contenteditable='true']"]}getSubmitButtonSelectors(){return ['button[type="submit"]','form button[type="submit"]','.query-bar button[type="submit"]']}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"true"===e.getAttribute("contenteditable"))}insertPrompt(e){const t=this.textarea;if(!t)return false;if(!t.isConnected)return this.textarea=null,false;if(t.focus(),"true"===t.getAttribute("contenteditable")){t.innerHTML=`

${e}

`,t.dispatchEvent(new Event("input",{bubbles:true}));const n=window.getSelection();if(n){const e=document.createRange();e.selectNodeContents(t),e.collapse(false),n.removeAllRanges(),n.addRange(e);}return true}return false}clearTextarea(){this.textarea&&(this.textarea.isConnected?(this.textarea.focus(),"true"===this.textarea.getAttribute("contenteditable")&&(this.textarea.innerHTML='


',this.textarea.dispatchEvent(new Event("input",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=document.querySelector("main");if(e){const t=e.querySelector('[class*="overflow-auto"]');if(t&&t.scrollHeight>t.clientHeight)return t;if(e.scrollHeight>e.clientHeight)return e}const t=document.querySelectorAll('[class*="overflow-y-auto"], [class*="overflow-auto"]');for(const n of Array.from(t)){const e=n;if(e.scrollHeight>e.clientHeight+100)return e}return null}getResponseContainerSelector(){return "main"}getChatContentSelectors(){return ['[class*="prose"]','[dir="ltr"]']}getUserQuerySelector(){return ".message-bubble.rounded-br-lg"}cloneUserQuerySource(e){const t=e.querySelector(".response-content-markdown");if(!t)return null;const n=(t.querySelector(".gh-user-query-original")||t).cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown").forEach(e=>e.remove()),n}isLikelyInlineCodeSpan(e){if("span"!==e.tagName.toLowerCase())return false;if(e.childElementCount>0)return false;const t=e.getAttribute("class")||"",n=/(^|\s)!?font-mono(\s|$)/.test(t),r=/(^|\s)rounded-sm(\s|$)/.test(t);return n&&r}normalizeUserQueryMarkdownSource(e){return e.querySelectorAll("span").forEach(t=>{const n=t;if(!this.isLikelyInlineCodeSpan(n))return;const r=(e.ownerDocument||document).createElement("code");r.textContent=n.textContent||"",n.replaceWith(r);}),e}extractUserQueryMarkdownFromSource(e){return Fi(this.normalizeUserQueryMarkdownSource(e)).trim()}extractUserQueryText(e){const t=this.cloneUserQuerySource(e);return t?this.extractTextWithLineBreaks(t).trim():this.extractTextWithLineBreaks(e).trim()}extractUserQueryMarkdown(e){const t=this.cloneUserQuerySource(e);if(t){const e=this.extractUserQueryMarkdownFromSource(t);if(e)return e}return e.textContent?.trim()||""}extractUserQueryExportContent(e){return this.extractGrokUserQueryExportContent(e)}extractGrokExportMessages(e){const t=document.querySelector(this.getResponseContainerSelector())||document.body,n=this.getGrokExportMessageItems(t),r=[];for(const o of n){const t=this.findGrokUserMessageRoot(o);if(t){const n=this.extractGrokUserQueryExportContent(t,e,o).trim();n&&r.push({role:"user",content:n});continue}const n=this.findGrokAssistantMessageRoot(o);if(n){const t=this.extractGrokAssistantExportContent(n,e).trim();t&&r.push({role:"assistant",content:t});}}return r}getGrokExportMessageItems(e){const t=Array.from(e.querySelectorAll('[id^="response-"]')).filter(e=>e.querySelector(".message-bubble")&&!e.closest(".gh-main-panel"));return t.length>0?t:Array.from(e.querySelectorAll(".message-bubble")).filter(e=>!e.closest(".gh-main-panel"))}findGrokUserMessageRoot(e){const t=this.getUserQuerySelector();return e.matches(t)?e:e.querySelector(t)}findGrokAssistantMessageRoot(e){const t=".message-bubble:not(.rounded-br-lg)";return e.matches(t)?e:e.querySelector(t)}extractGrokUserQueryExportContent(e,t,n){const r=this.extractGrokUserAttachments(e,n),o=this.extractGrokUserBodyMarkdown(e);if(0===r.length)return o||this.extractUserQueryText(e);const i=this.formatGrokUserImageAttachments(r,t),a=this.formatGrokUserFileAttachments(r,t),s=a.length>0?`${se("exportAttachmentsLabel")}:\n${a.join("\n")}`:"";return [i.join("\n\n"),s,o].filter(Boolean).join("\n\n")}extractGrokUserBodyMarkdown(e){const t=this.cloneUserQuerySource(e);if(!t)return this.extractUserQueryText(e);this.removeGrokUserAttachmentNodes(t),this.removeGrokExportDecorations(t,{removeImages:true});return this.extractUserQueryMarkdownFromSource(t)||this.extractTextWithLineBreaks(t).trim()}extractGrokAssistantExportContent(e,t){return [this.extractGrokAssistantBodyMarkdown(e),this.extractGrokImageMarkdown(e,t,"generated image").join("\n\n")].filter(Boolean).join("\n\n")}extractGrokAssistantBodyMarkdown(e){const t=(e.matches(".response-content-markdown")?e:e.querySelector(".response-content-markdown")||e).cloneNode(true);this.removeGrokExportDecorations(t,{removeImages:true});const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}removeGrokExportDecorations(e,t={}){const n=["button",'[role="button"]',"svg",'[aria-hidden="true"]',".gh-user-query-markdown"];t.removeImages&&n.push("img","picture","video"),e.querySelectorAll(n.join(", ")).forEach(e=>e.remove());}removeGrokUserAttachmentNodes(e){Array.from(e.querySelectorAll('a[href], [role="group"], [aria-label], [title], [class*="file"], [class*="attachment"]')).forEach(t=>{this.isLikelyGrokAttachmentCard(t,e)&&t.remove();});}extractGrokUserAttachments(e,t){const n=this.resolveGrokUserAttachmentScope(e,t);if(!n)return [];const r=[],o=new Set,i=e=>{if(this.hasEquivalentGrokAttachment(r,e))return;const t=this.getGrokAttachmentDedupKey(e);o.has(t)||(o.add(t),r.push(e));};return this.getCachedGrokUserAttachments(n).forEach(i),this.extractGrokUserImageAttachments(n).forEach(i),this.extractGrokUserFileAttachments(n).forEach(i),r}getGrokAttachmentDedupKey(e){const t=this.extractGrokAssetIdFromSource(e.source);if(t)return `${e.kind}:asset:${t}`;const n=e.name.toLowerCase();return n?`${e.kind}:name:${n}`:`${e.kind}:${e.source}:${e.type}:${e.size}`}hasEquivalentGrokAttachment(e,t){const n=this.extractGrokAssetIdFromSource(t.source),r=t.name.toLowerCase();return e.some(e=>{if(e.kind!==t.kind)return false;const o=this.extractGrokAssetIdFromSource(e.source);return !(!o||!n||o!==n)||Boolean(r&&e.name.toLowerCase()===r)})}getCachedGrokUserAttachments(e){if(!this.exportUserAttachmentsByResponseId)return [];const t=this.extractGrokResponseId(e);return t&&this.exportUserAttachmentsByResponseId.get(t)||[]}extractGrokResponseId(e){const t=e.closest('[id^="response-"]');return (t?.id||(e.id.startsWith("response-")?e.id:"")).replace(/^response-/,"")}resolveGrokUserAttachmentScope(e,t){if(t instanceof HTMLElement)return t;const n=e.closest('[id^="response-"]');if(n instanceof HTMLElement)return n;const r=e.closest(".message-bubble")?.parentElement;if(r instanceof HTMLElement)return r;const o=e.closest(this.getUserQuerySelector());return o instanceof HTMLElement?o:null}extractGrokUserImageAttachments(e){return this.getGrokExportImages(e).filter(e=>!e.closest(".gh-user-query-markdown")).flatMap(e=>{const t=this.getGrokImageExportSource(e);if(!this.isExportableGrokImageSource(t))return [];const n=this.extractGrokImageAlt(e,t,"uploaded image");return [{kind:"image",name:n,source:t,type:this.extractFileTypeFromName(n)||"image",size:""}]})}extractGrokUserFileAttachments(e){return Array.from(e.querySelectorAll('a[href], [role="group"], [aria-label], [title], [class*="file"], [class*="attachment"]')).filter(t=>this.isLikelyGrokAttachmentCard(t,e)).flatMap(e=>{const t=this.extractGrokAttachmentCardName(e);if(!t)return [];const n=this.extractGrokAttachmentCardSource(e),r=this.extractFileTypeFromName(t);return [{kind:this.isImageAttachmentName(t,r)?"image":"file",name:t,source:n,type:r,size:this.extractGrokAttachmentCardSize(e)}]})}isLikelyGrokAttachmentCard(e,t){if(e===t)return false;if(e.closest(".gh-user-query-markdown"))return false;if(e.closest("pre, code"))return false;if(e.closest(".response-content-markdown p"))return false;return !!this.extractGrokAttachmentCardName(e)&&Boolean(e.querySelector("a[href], img, svg")||e.matches("a[href]")||this.extractGrokAttachmentCardSource(e))}extractGrokImageMarkdown(e,t,n){const r=new Set,o=[];for(const i of this.getGrokExportImages(e)){const e=this.getGrokImageExportSource(i);if(!this.isExportableGrokImageSource(e)||r.has(e))continue;r.add(e);const a=this.extractGrokImageAlt(i,e,n),s=Ta({source:e,alt:a,extensionHint:a},t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:n});s&&o.push(s);}return o}getGrokExportImages(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement)}getGrokImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.closest("a[href]")?.getAttribute("href")||""];for(const n of t){const e=fa(n);if(e)return e}return ""}isExportableGrokImageSource(e){return !!e&&(!e.startsWith("data:image/svg+xml")&&(!/\/images\/(?:favicon|apple-touch-icon|android-chrome)/i.test(e)&&(ba(e)||e.startsWith("data:image/"))))}extractGrokImageAlt(e,t,n){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractFilenameFromUrl(t),n].map(e=>this.normalizeAttachmentText(e)).find(Boolean)||n}formatGrokUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatGrokUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"image"!==e.kind||!e.source,getLabel:e=>this.formatGrokAttachmentLabel(e)})}formatGrokAttachmentLabel(e){const t=this.formatGrokAttachmentDetails(e);return t?`${e.name} (${t})`:e.name}formatGrokAttachmentDetails(e){return [e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?e.type:"",e.size].filter(Boolean).join(", ")}extractGrokAttachmentCardName(e){const t=[...this.extractGrokAttachmentLeafTexts(e),e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e instanceof HTMLAnchorElement&&e.download||"",e.textContent||"",this.extractFilenameFromUrl(this.extractGrokAttachmentCardSource(e))];for(const n of t){const e=this.extractFilenameFromText(n);if(e)return e}return ""}extractGrokAttachmentLeafTexts(e){return Array.from(e.querySelectorAll("div, span, p")).filter(e=>0===e.children.length&&!e.querySelector("svg, img")).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean)}extractGrokAttachmentCardSource(e){const t=[];e instanceof HTMLAnchorElement&&t.push(e.getAttribute("href")||e.href||"");const n=e.closest("a[href]");n instanceof HTMLAnchorElement&&t.push(n.getAttribute("href")||n.href||""),e.querySelectorAll("a[href]").forEach(e=>{e instanceof HTMLAnchorElement&&t.push(e.getAttribute("href")||e.href||"");});for(const o of ["data-url","data-src","data-file-url","data-download-url"])t.push(e.getAttribute(o)||"");const r=e.querySelector("img");r instanceof HTMLImageElement&&t.push(this.getGrokImageExportSource(r));for(const o of t){const e=fa(o);if(ba(e)||e.startsWith("data:"))return e}return ""}extractGrokAttachmentCardSize(e){const t=this.normalizeAttachmentText(e.textContent||"");return t.match(/\b\d+(?:\.\d+)?\s*[KMGT]?B\b/i)?.[0]||""}extractFilenameFromText(e){const t=this.normalizeAttachmentText(e).replace(/^(attached\s+file|attachment|file|附件|文件)[::]?\s+/i,"").trim();if(!t||this.isFileMetaText(t))return "";if(/^[^/\\]+\.[A-Za-z0-9]{1,10}$/.test(t))return t;const n=t.match(/(?:^|[\s([{])([^/\\]+?\.[A-Za-z0-9]{1,10})(?=$|[\s)\]}])/);return n?.[1]?.trim()||""}isFileMetaText(e){return /^[A-Za-z0-9.+-]{1,12}\s+\d+(?:\.\d+)?\s*[KMGT]?B$/i.test(e)}isImageAttachmentName(e,t){const n=(this.extractFileTypeFromName(e)||t).toLowerCase();return ["avif","gif","jpg","jpeg","png","svg","webp"].includes(n)}extractFileTypeFromName(e){return e.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toUpperCase()||""}extractFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename")||t.searchParams.get("file_name");return n?.trim()?n.trim():decodeURIComponent(t.pathname).split("/").pop()?.trim()||""}catch{return ""}}extractGrokAssetIdFromSource(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname.split("/").filter(Boolean),n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return t.reverse().find(e=>n.test(e))||""}catch{return ""}}normalizeAttachmentText(e){return e.replace(/\s+/g," ").trim()}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}replaceUserQueryContent(e,t){const n=e.querySelector(".response-content-markdown");if(!n)return false;if(n.querySelector(".gh-user-query-markdown"))return false;const r=Array.from(n.children),o=document.createElement("div");o.className="gh-user-query-original",o.style.display="none",r.forEach(e=>{o.appendChild(e);}),n.appendChild(o);const i=document.createElement("div");return i.className="gh-user-query-markdown gh-markdown-preview",i.innerHTML=t,n.insertBefore(i,o),true}getExportConfig(){return {userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:".message-bubble:not(.rounded-br-lg) .response-content-markdown",turnSelector:"",useShadowDOM:false}}async prepareConversationExport(e){return this.exportUserAttachmentsByResponseId=await this.collectGrokShareUserAttachments(),null}async restoreConversationAfterExport(e,t){this.exportUserAttachmentsByResponseId=null;}async collectGrokShareUserAttachments(){const e=this.extractGrokShareId();if(!e)return null;try{const t=await fetch(`/rest/app-chat/share_links/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});return t.ok?this.parseGrokShareUserAttachments(await t.json()):(console.warn("[GrokAdapter] Failed to load share attachment metadata:",t.status),null)}catch(t){return console.warn("[GrokAdapter] Failed to load share attachment metadata:",t),null}}extractGrokShareId(){const e=window.location.pathname.match(/^\/share\/([^/?#]+)/);return e?.[1]?decodeURIComponent(e[1]):""}parseGrokShareUserAttachments(e){const t=this.toGrokRecord(e),n=t?.responses;if(!Array.isArray(n))return null;const r=new Map;for(const o of n){const e=this.toGrokRecord(o),t=this.readGrokString(e?.responseId);if(!t)continue;const n=e?.fileAttachmentsMetadata;if(!Array.isArray(n))continue;const i=n.map(e=>this.parseGrokFileAttachmentMetadata(e)).filter(e=>null!==e);i.length>0&&r.set(t,i);}return r.size>0?r:null}parseGrokFileAttachmentMetadata(e){const t=this.toGrokRecord(e);if(!t)return null;const n=this.readGrokString(t.fileName)||this.readGrokString(t.fileMetadataId)||"file",r=this.readGrokString(t.fileMimeType)||this.extractFileTypeFromName(n),o=this.buildGrokAssetSource(this.readGrokString(t.fileUri));return {kind:r.toLowerCase().startsWith("image/")||this.isImageAttachmentName(n,r)?"image":"file",name:n,source:o,type:r,size:""}}buildGrokAssetSource(e){const t=e.trim();if(!t)return "";if(/^(blob:|data:|https?:\/\/)/i.test(t))return fa(t);if(t.startsWith("//"))return `https:${t}`;if(t.startsWith("assets.grok.com/"))return `https://${t}`;const n=t.replace(/^\/+/,"");return /^(users|generated)\//i.test(n)?`https://assets.grok.com/${n}`:fa(t)}toGrokRecord(e){return e&&"object"==typeof e?e:null}readGrokString(e){return "string"==typeof e?e.trim():""}async extractExportMessages(e){const t=this.extractGrokExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractGrokExportMessages(e))}getAssistantMermaidSupportMode(){return "native"}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=e=>{const t=e.closest('[id^="response-"]');return t?t.id:null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector();if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,l)=>{if(this.isInRenderedMarkdownContainer(t))return;const c=parseInt(t.tagName.charAt(1),10);if(c<=e){const e={level:c,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=l+1;e{const c=t.tagName.toLowerCase();if(t.matches(l)){let e=this.extractUserQueryText(t),a=false;e.length>200&&(e=e.substring(0,200),a=true);const s={level:0,text:e,element:t,isUserQuery:true,isTruncated:a},c=i(t);c&&(s.id=c),n&&(s.wordCount=(e=>{const t=e.closest('[id^="response-"]');if(!t)return 0;let n=t.nextElementSibling,r=0;for(;n&&!n.querySelector(l);){const e=n.querySelector(".message-bubble:not(.rounded-br-lg)");if(e){const t=e.querySelector(".response-content-markdown");t&&(r+=t.textContent?.trim().length||0);}n=n.nextElementSibling;}if(0===r){const t=o.querySelectorAll(".message-bubble:not(.rounded-br-lg)");for(const n of Array.from(t)){if(!(e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING))continue;const t=e.parentElement?.nextElementSibling?.querySelector(l);if(t&&!(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING))continue;const o=n.querySelector(".response-content-markdown");o&&(r+=o.textContent?.trim().length||0);}}return r})(t)),r.push(s);}else if(/^h[1-6]$/.test(c)){if(this.isInRenderedMarkdownContainer(t))return;const d=parseInt(c.charAt(1),10);if(d<=e){const e={level:d,text:t.textContent?.trim()||"",element:t},h=i(t);if(h&&(e.id=s(h,c,e.text)),n){let n=null;for(let t=a+1;t{const t=e.closest("ms-chat-turn")?.id||"";return this.normalizeTurnId(t)===o})||null}getScrollbarQueryEntries(){const e=Array.from(document.querySelectorAll(["ms-items-scrollbar button[aria-controls]","ms-items-scrollbar button[data-test-item-id]","ms-prompt-scrollbar button[aria-controls]","ms-prompt-scrollbar button[data-test-item-id]"].join(", "))).filter(e=>e instanceof HTMLElement),t=new Set,n=[];return e.forEach(e=>{const r=e.getAttribute("aria-controls")||e.getAttribute("data-test-item-id")||"",o=this.normalizeTurnId(r);if(!o||t.has(o))return;const i=this.normalizeScrollbarQueryText(e.getAttribute("aria-label")||e.getAttribute("title")||"");i&&(t.add(o),n.push({turnId:o,text:i,button:e,element:this.findUserQueryElementByTurnId(o),index:n.length}));}),n}getTextFromScrollbar(e){const t=this.normalizeTurnId(e);if(!t)return null;const n=this.getScrollbarQueryEntries().find(e=>e.turnId===t);return n?.text||null}async waitForUserQueryElementByTurnId(e,t,n=1600){const r=Date.now();for(;Date.now()-re.turnId===t);return !!n&&(n.button.scrollIntoView({block:"nearest",inline:"nearest"}),n.button.click(),true)}resolveScrollbarTurnIdForOutlineItem(e,t){const n=(e.id||"").match(/^aistudio-user:(.+)$/);if(n?.[1])return this.normalizeTurnId(n[1]);const r=this.getScrollbarQueryEntries();return void 0!==t?r[t-1]?.turnId||null:r.find(t=>this.isSameOutlineText(t.text,e.text))?.turnId||null}getCurrentConversationTitleFromSources(){const e=this.getSessionId();if(!e)return null;const t=document.querySelector("h1[class*='mode-title'], h1.page-title, .page-title h1"),n=t?.textContent?.trim();if(n)return n;if(this.cachedLibraryConversations&&this.cachedLibraryConversations.length>0){const t=this.cachedLibraryConversations.find(t=>t.id===e);if(t?.title?.trim())return t.title.trim()}const r=document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"]`),o=r?.textContent?.trim();return o||null}getSessionName(){return this.getCurrentConversationTitleFromSources()}getConversationTitle(){return this.getCurrentConversationTitleFromSources()}getTextareaSelectors(){return ["textarea.textarea","textarea.cdk-textarea-autosize",'textarea[placeholder*="prompt"]','textarea[placeholder*="Start typing"]']}getSubmitButtonSelectors(){return ['ms-run-button button[type="submit"]','ms-run-button.supports-add-instead-of-run button[type="submit"]','button[ms-button][type="submit"]','button.ms-button-primary[type="submit"]']}getSubmitKeyConfig(){try{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return {key:"Enter"};return 2===JSON.parse(e).enterKeyBehavior?{key:"Ctrl+Enter"}:{key:"Enter"}}catch{return {key:"Enter"}}}isValidTextarea(e){return null!==e.offsetParent&&(!e.closest(".gh-main-panel")&&"textarea"===e.tagName.toLowerCase())}insertPrompt(e){const t=this.textarea;return !!t&&(t.isConnected?(t.focus(),"textarea"===t.tagName.toLowerCase()&&(t.value=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true})),t.selectionStart=t.selectionEnd=e.length,true)):(this.textarea=null,false))}clearTextarea(){const e=this.textarea;e&&(e.isConnected?(e.focus(),"textarea"===e.tagName.toLowerCase()&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:true})),e.dispatchEvent(new Event("change",{bubbles:true})))):this.textarea=null);}getScrollContainer(){const e=[".chat-container",".virtual-scroll-container",'[class*="scroll"]','main [style*="overflow"]'];for(const n of e){const e=document.querySelector(n);if(e&&e.scrollHeight>e.clientHeight)return e}const t=document.querySelector("main");if(t){const e=t.querySelector('[class*="overflow"]');if(e&&e.scrollHeight>e.clientHeight)return e}return null}getResponseContainerSelector(){return ".chat-container, main"}getChatContentSelectors(){return [".chat-turn-container",'[class*="message"]','[class*="response"]']}getWidthSelectors(){return [{selector:".chat-session-content",property:"max-width"},{selector:".chat-turn-container",property:"max-width"},{selector:".table-container > table",property:"width",value:"100%",noCenter:true,extraCss:"min-width: 100% !important;"}]}getZenModeConfig(){return {hide:["ms-navbar","ms-navbar-v2","ms-right-side-panel"]}}getCleanModeConfig(){return {hide:["ms-hallucinations-disclaimer"]}}getMarkdownFixerConfig(){return {selector:"ms-cmark-node span.ng-star-inserted",fixSpanContent:true}}getAIStudioModelSelectorButton(e=false){const t=["button.model-selector-card",".model-selector-card"];for(const o of t){const t=document.querySelector(o);if(t instanceof HTMLElement&&(!e||this.isVisible(t)))return t}const n=document.querySelector('[data-test-id="model-name"]'),r=n?.closest("button");return r instanceof HTMLElement&&(!e||this.isVisible(r))?r:null}getRunSettingsToggleButton(e=false){const t=document.querySelector('button[aria-label="Toggle run settings panel"]');return t instanceof HTMLElement&&(!e||this.isVisible(t))?t:null}clickModelSelector(){const e=this.getAIStudioModelSelectorButton();if(e)return this.simulateClick(e),true;const t=this.getRunSettingsToggleButton();if(!t)return false;this.simulateClick(t);const n=this.getAIStudioModelSelectorButton();return !!n&&(this.simulateClick(n),true)}lockModel(e,t){if(!e)return;let n=0;const r=setInterval(async()=>{n++;const o=this.getAIStudioModelSelectorButton();if(o){clearInterval(r),o.click();const n=await this.waitForModelSidebar();if(!n)return console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),void this.closeModelSidebar();await this.ensureAllModelsCategory(n);const a=`model-carousel-row-models/${e}`,s=document.getElementById(a);if(s){const n=s.querySelector("div > div > div > span:first-child"),r=n?.textContent?.trim()||e,o=this.getSessionId();o&&localStorage.setItem(`ophel:aistudio:model:${o}`,r),s.click(),t&&t();try{const e=Ai.getState().settings;e.aistudio?.collapseRunSettings&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500);}catch(i){console.error("[AIStudioAdapter] Auto-collapse run settings failed:",i);}}else console.warn(`[AIStudioAdapter] 未找到目标模型: ${e}`),this.closeModelSidebar();}else {const e=this.getRunSettingsToggleButton();e?(e.click(),n=Math.max(0,n-2)):n>=10&&(clearInterval(r),console.warn("[AIStudioAdapter] 未找到模型选择按钮"));}},1e3);}async getModelList(){let e=false,t=this.getAIStudioModelSelectorButton();if(!t){const n=this.getRunSettingsToggleButton();if(n){e=true,n.click();for(let e=0;e<20&&(await new Promise(e=>setTimeout(e,200)),t=this.getAIStudioModelSelectorButton(),!t);e++);}}if(!t)return console.warn("[AIStudioAdapter] 模型选择器按钮未找到"),[];t.click();const n=await this.waitForModelSidebar();if(!n){if(console.warn("[AIStudioAdapter] 模型侧边栏加载超时"),e){const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();}return []}await this.ensureAllModelsCategory(n);const r=this.extractModelsFromSidebar(n);return this.closeModelSidebar(),e&&setTimeout(()=>{const e=document.querySelector('button[aria-label="Close run settings panel"]');e&&e.click();},500),r}async waitForModelSidebar(){const e=Date.now();for(;Date.now()-e<5e3;){const e=document.querySelector(".ms-sliding-right-panel-dialog, mat-dialog-container.mat-mdc-dialog-container");if(e)return await new Promise(e=>setTimeout(e,300)),e;await new Promise(e=>setTimeout(e,100));}return null}async ensureAllModelsCategory(e){const t=Array.from(e.querySelectorAll("[data-test-category-button]"));if(0===t.length)return;const n=t.find(e=>"All"===e.textContent?.trim());n&&"true"!==n.getAttribute("aria-selected")&&(n.click(),await this.sleep(400));}extractModelsFromSidebar(e){const t=[];return e.querySelectorAll(".model-options-container button.content-button").forEach(e=>{const n=(e.id||"").replace("model-carousel-row-","").replace("models/",""),r=e.querySelector("div > div > div > span:first-child"),o=r?.textContent?.trim()||n;n&&o&&t.push({id:n,name:o});}),t}closeModelSidebar(){const e=document.querySelector("button[data-test-close-button]");e?e.click():document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:true}));}async loadAllConversations(){const e="/library"===window.location.pathname;if(!e){if(!(await this.navigateToLibraryViaSpa()))return void(window.location.href="/library")}const t=this.extractLibraryConversations();t.length>0&&(this.cachedLibraryConversations=t),e||window.history.back(),setTimeout(()=>{this.cachedLibraryConversations=null;},1e4);}async navigateToLibraryViaSpa(){const e=document.querySelector('ms-navbar-v2 a[href="/library"]'),t=document.querySelector('a[href="/library"]'),n=e??t;return n&&(n.closest("ms-navbar-v2")||n.hasAttribute("routerlink")||n.hasAttribute("ng-reflect-router-link"))&&n?(n.click(),this.waitForLibraryTable()):(window.history.pushState(null,"","/library"),window.dispatchEvent(new PopStateEvent("popstate",{state:null})),this.waitForLibraryTable())}async waitForLibraryTable(){for(let e=0;e<50;e++){await new Promise(e=>setTimeout(e,100));if(document.querySelector("ms-library-table table"))return await new Promise(e=>setTimeout(e,200)),true}return false}extractLibraryConversations(){const e=[];return document.querySelectorAll("ms-library-table table tbody tr").forEach(t=>{const n=t.querySelector('a[href*="/prompts/"]');if(!n)return;const r=n.getAttribute("href")||"",o=r.match(/\/prompts\/([^/]+)/);if(!o)return;const i=o[1],a=n.getAttribute("title")?.trim()||n.textContent?.trim()||"Untitled";e.push({id:i,title:a,url:r,isActive:window.location.pathname.includes(i),isPinned:false});}),e}extractSidebarConversations(){const e=new Map;return document.querySelectorAll('a[href*="/prompts/"]').forEach(t=>{const n=t.getAttribute("href");if(!n||n.includes("new_chat"))return;const r=n.match(/\/prompts\/([^/]+)/);if(!r)return;const o=r[1];if(e.has(o))return;const i=t.textContent?.trim()||"Untitled",a=window.location.pathname.includes(o);e.set(o,{id:o,title:i,url:n,isActive:a,isPinned:false});}),Array.from(e.values())}getConversationList(){return "/library"===window.location.pathname?this.extractLibraryConversations():this.cachedLibraryConversations&&this.cachedLibraryConversations.length>0?this.cachedLibraryConversations:this.extractSidebarConversations()}getSidebarScrollContainer(){return "/library"===window.location.pathname?document.querySelector("ms-library-table .lib-table-wrapper")||null:document.querySelector("ms-navbar-v2")||document.querySelector("main")||document.body||null}getConversationObserverConfig(){return "/library"===window.location.pathname?{selector:'ms-library-table a.name-btn[href*="/prompts/"]:not([href*="new_chat"])',shadow:false,extractInfo:e=>{const t=e.getAttribute("href");if(!t)return null;const n=t.match(/\/prompts\/([^/]+)/);if(!n)return null;return {id:n[1],title:e.getAttribute("title")?.trim()||e.textContent?.trim()||"Untitled",url:t,isPinned:false}},getTitleElement:e=>e}:null}navigateToConversation(e,t){const n=document.querySelector(`ms-library-table a.name-btn[href*="/prompts/${e}"]`);return n?(n.click(),true):(window.location.href=t||`/prompts/${e}`,true)}async deleteConversationOnSite(e){return (await this.deleteConversationsOnSite([e]))[0]||{id:e.id,success:false,method:"none",reason:ps}}async deleteConversationsOnSite(e){const t=await this.enterLibraryPageForDelete(),n=[],r=[];let o=false;try{for(let t=0;t0&&this.scheduleFullReloadAfterDelete(r),n}finally{t.enteredLibrary&&!o&&await this.restoreFromLibraryPage(t.originalPath);}}async deleteConversationOnSiteInternal(e){const t=this.shouldUseNativeDeleteApi()?await this.tryDeleteViaGrpcApi(e.id):{id:e.id,success:false,method:"none",reason:fs};if(t.success)return t;const n=await this.deleteConversationViaUi(e.id);return {id:e.id,success:n,method:n?"ui":"none",reason:n?void 0:t.reason||ps}}shouldUseNativeDeleteApi(){return false}async tryDeleteViaGrpcApi(e){const t=await this.buildGoogleAuthorizationHeader(window.location.origin);if(!t)return {id:e,success:false,method:"none",reason:bs};const n=this.resolveGoogleApiKey();if(!n)return {id:e,success:false,method:"none",reason:ys};const r=this.normalizePromptName(e),o=this.getDeletePromptEndpoints();let i=0;try{for(const a of o){const o=await fetch(a,{method:"POST",credentials:"include",headers:{accept:"*/*",authorization:t,"content-type":"application/json+protobuf","x-goog-api-key":n,"x-goog-authuser":this.resolveGoogAuthUser(),"x-user-agent":"grpc-web-javascript/0.1"},body:JSON.stringify([r])});if(i=o.status,o.ok)return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"};if(404!==o.status){if(!(400===o.status||o.status>=500))return {id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(o.status)}}else if(!this.isConversationVisible(e))return this.cachedRpcOrigin=this.normalizeRpcOriginFromEndpoint(a),this.syncConversationListAfterDelete(e),{id:e,success:!0,method:"api"}}return 404===i?{id:e,success:!1,method:"api",reason:ws}:{id:e,success:!1,method:"api",reason:this.toDeleteApiHttpReason(i||0)}}catch{return {id:e,success:false,method:"api",reason:vs}}}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e}`}}normalizePromptName(e){return e?e.startsWith("prompts/")?e:`prompts/${e}`:""}getDeletePromptEndpoints(){const e=[];this.cachedRpcOrigin&&e.push(this.cachedRpcOrigin),e.push(...this.resolveRpcOriginsFromPerformance()),e.push("https://alkalimakersuite-pa.clients6.google.com");return Array.from(new Set(e.filter(Boolean))).map(e=>`${e}${Ss}/DeletePrompt`)}resolveRpcOriginsFromPerformance(){const e=performance.getEntriesByType("resource");if(!e||0===e.length)return [];const t=[];for(let n=e.length-1;n>=0;n--){const r=e[n]?.name;if(!r||!r.includes(Ss))continue;const o=this.normalizeRpcOriginFromEndpoint(r);o&&t.push(o);}return Array.from(new Set(t))}normalizeRpcOriginFromEndpoint(e){try{const t=new URL(e);return this.isLikelyRpcHost(t.hostname)?`${t.protocol}//${t.host}`:null}catch{return null}}isLikelyRpcHost(e){return /(?:^|\.)alkalimakersuite-[a-z0-9-]+\.clients\d+\.google\.com$/i.test(e)}async buildGoogleAuthorizationHeader(e){const t=Math.floor(Date.now()/1e3),n=this.getCookieValue("SAPISID"),r=this.getCookieValue("__Secure-1PAPISID"),o=this.getCookieValue("__Secure-3PAPISID"),i=[],a=n||r||o;if(a){const n=await this.buildSapisidHashToken(a,e,t);n&&i.push(`SAPISIDHASH ${n}`);}if(r){const n=await this.buildSapisidHashToken(r,e,t);n&&i.push(`SAPISID1PHASH ${n}`);}if(o){const n=await this.buildSapisidHashToken(o,e,t);n&&i.push(`SAPISID3PHASH ${n}`);}return 0===i.length?null:i.join(" ")}async buildSapisidHashToken(e,t,n){try{const r=`${n} ${e} ${t}`,o=await crypto.subtle.digest("SHA-1",(new TextEncoder).encode(r));return `${n}_${Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join("")}`}catch{return null}}resolveGoogleApiKey(){if(this.cachedApiKey&&this.isValidGoogleApiKey(this.cachedApiKey))return this.cachedApiKey;const e=window.WIZ_global_data,t=e?.SNlM0e;if(this.isValidGoogleApiKey(t))return this.cachedApiKey=t,t;for(let r=0;rt.id!==e));[`a.prompt-link[href*="/prompts/${e}"]`,`a.name-btn[href*="/prompts/${e}"]`,`a[href*="/prompts/${e}"]`].forEach(e=>{Array.from(document.querySelectorAll(e)).forEach(e=>{(e.closest("tr")||e.closest("li")||e.closest("mat-row")||e).remove();});});}isConversationVisible(e){return Boolean(document.querySelector(`a.prompt-link[href*="/prompts/${e}"], a.name-btn[href*="/prompts/${e}"], a[href*="/prompts/${e}"]`))}scheduleFullReloadAfterDelete(e){if(0===e.length)return;const t=this.getSessionId();if(t&&e.includes(t))try{window.history.replaceState(window.history.state,"","/prompts/new_chat");}catch{}}async deleteConversationViaUi(e){const t=await this.findLibraryRowByPromptId(e,1500);if(!t)return false;const n=this.findLibraryRowMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(2500);if(!r)return false;this.simulateClick(r);const o=await this.waitForDeleteConfirmButton(2500);if(!o)return false;this.simulateClick(o);const i=await this.waitForConversationRemoved(e,5e3);return i&&this.syncConversationListAfterDelete(e),i}async enterLibraryPageForDelete(){const e=`${window.location.pathname}${window.location.search}${window.location.hash}`;if("/library"===window.location.pathname)return {enteredLibrary:false,originalPath:e};return await this.navigateToLibraryViaSpa()&&"/library"===window.location.pathname?{enteredLibrary:true,originalPath:e}:{enteredLibrary:false,originalPath:e}}async restoreFromLibraryPage(e){if(!e||"/library"!==window.location.pathname)return;window.history.back();const t=Date.now();for(;Date.now()-t<3e3;){if("/library"!==window.location.pathname)return;await this.sleep(80);}}async findLibraryRowByPromptId(e,t=1200){const n=Date.now();for(;Date.now()-nthis.isVisible(e));if(n.length>0)return n.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0];const r=Array.from(e.querySelectorAll("button")).filter(e=>this.isVisible(e));return 0===r.length?null:r.sort((e,t)=>t.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nn.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getUserQuerySelector(){return ".chat-turn-container.user"}findUserQueryElement(e,t){const n=this.getScrollbarQueryEntries()[e-1];if(n){const e=this.findUserQueryElementByTurnId(n.turnId);if(!e)return null;const r=this.extractUserQueryText(e);return !t||this.isSameOutlineText(r,t)?e:null}return super.findUserQueryElement(e,t)}textCache=new Map;wordCountCache=new Map;lastSessionIdForCache=null;extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.getSessionId();this.lastSessionIdForCache!==t&&(this.textCache.clear(),this.wordCountCache.clear(),this.lastSessionIdForCache=t);const n=e.closest("ms-chat-turn")?.id;let r="";const o=this.findUserContentChunk(e);if(o)r=this.extractCleanTextFromChunk(o);else {const t=e.querySelector(".turn-content");if(t){const e=t.cloneNode(true);e.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),r=(e.textContent||"").trim();}else r=this.extractTextWithLineBreaks(e);}if(!r&&n){const e=this.getTextFromScrollbar(n);e&&(r=e);}return r?(n&&this.textCache.set(n,r),r):n&&this.textCache.has(n)?this.textCache.get(n):""}extractUserQueryMarkdown(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=(this.findUserContentChunk(e)||e).cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAttachments(e)}extractUserQueryExportContentWithAttachments(e,t){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const n=this.extractAIStudioUserAttachments(e),r=this.extractUserQueryMarkdown(e).trim()||(0===n.length?this.extractUserQueryText(e):"");if(0===n.length)return r;const o=this.formatAIStudioUserImageAttachments(n,t),i=this.formatAIStudioUserFileAttachments(n,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,r].filter(Boolean).join("\n\n")}extractAIStudioUserAttachments(e){const t=[],n=new Set;return this.extractAIStudioUserImageAttachments(e).forEach(e=>{const r=`image:${e.source||e.name}`;n.has(r)||(n.add(r),t.push(e));}),this.extractAIStudioUserFileAttachments(e).forEach(e=>{const r=`file:${e.source||e.name}:${e.details||""}`;n.has(r)||(n.add(r),t.push(e));}),t}extractAIStudioUserImageAttachments(e){return Array.from(e.querySelectorAll("ms-image-chunk img")).filter(e=>e instanceof HTMLImageElement).flatMap(e=>{const t=this.extractAIStudioImageSource(e);if(!t)return [];const n=(e.alt||e.getAttribute("title")||"uploaded image").replace(/\s+/g," ").trim();return [{kind:"image",name:n||"uploaded image",source:t,mimeHint:n}]})}extractAIStudioImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=fa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&ba(e)))return e}return ""}extractAIStudioUserFileAttachments(e){return Array.from(e.querySelectorAll("ms-file-chunk")).flatMap(e=>{const t=this.extractAIStudioFileName(e);return t?[{kind:"file",name:t,source:this.extractAIStudioFileSource(e),details:this.extractAIStudioFileDetails(e),mimeHint:t}]:[]})}extractAIStudioFileName(e){const t=e.querySelector(".name"),n=t?.getAttribute("title")?.trim();if(n)return n;const r=t?.textContent?.trim();if(r)return r;const o=e.getAttribute("aria-label")||e.querySelector("[aria-label]")?.getAttribute("aria-label");return o?.split(",")[0]?.trim()||""}extractAIStudioFileDetails(e){return Array.from(e.querySelectorAll(".token-count")).map(e=>e.textContent?.replace(/\s+/g," ").trim()||"").find(Boolean)||""}extractAIStudioFileSource(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const n of t){const e=fa(n.href||n.getAttribute("href")||"");if(ba(e))return e}return ""}formatAIStudioUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId(),getExtensionHint:e=>e.mimeHint||e.name})}formatAIStudioUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),getLabel:e=>this.formatAIStudioFileLabel(e),getMimeHint:e=>e.mimeHint||e.name})}formatAIStudioFileLabel(e){return e.details?`${e.name} (${e.details})`:e.name}createAIStudioUserQueryOutlineItem(e,t,n,r){let o=this.normalizeScrollbarQueryText(e),i=false;o.length>200&&(o=o.substring(0,200),i=true);const a=n?this.normalizeTurnId(n):"",s={level:0,text:o,element:t,isUserQuery:true,isTruncated:i};a&&(s.id=`aistudio-user:${a}`),void 0!==r&&(s.wordCount=r);const l=t?this.getNextTurnContextForUserQuery(t):void 0;return l&&(s.context=l),s}getNextTurnContextForUserQuery(e){const t=e.closest("ms-chat-turn"),n=t?.nextElementSibling;if(!n||"ms-chat-turn"!==n.tagName.toLowerCase())return;return this.extractTextWithLineBreaks(n).trim().substring(0,50)||void 0}findPreviousUserTurnIdForElement(e){const t=e.closest("ms-chat-turn");if(!t)return null;const n=t.querySelector(".chat-turn-container.user");if(n&&!n.contains(e))return this.normalizeTurnId(t.id);let r=t.previousElementSibling;for(;r;){if(r.querySelector(".chat-turn-container.user"))return this.normalizeTurnId(r.id);r=r.previousElementSibling;}return null}findUserContentChunk(e){const t=["ms-text-chunk","ms-prompt-chunk.text-chunk","ms-prompt-chunk","ms-cmark-node.cmark-node.user-chunk"];for(const n of t){const t=e.querySelector(n);if(!t)continue;if(this.extractCleanTextFromChunk(t))return t}return null}extractCleanTextFromChunk(e){const t=e.cloneNode(true);return t.querySelectorAll('.actions-container, button, [role="button"], svg, [aria-hidden="true"], ms-image-chunk, ms-file-chunk').forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:qs,assistantResponseSelector:Rs,turnSelector:Ds,useShadowDOM:false}:{userQuerySelector:this.getUserQuerySelector(),assistantResponseSelector:Es,turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "fallback"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportBundleCache=null,this.clearExportSnapshot();const t="markdown"===e.format&&"zip"===e.packaging?ia():void 0,n=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector()),r=document.querySelector(this.getResponseContainerSelector())||document.querySelector("main")||document.body,o=n instanceof HTMLElement?await this.collectExportMessageSnapshots(n,t):this.readVisibleExportMessageSnapshots(r,t);return 0===o.length?null:(t&&(this.exportBundleCache={messages:o.map(({role:e,content:t})=>({role:e,content:t})),assets:t.assets}),this.mountExportSnapshot(o),{count:o.length})}async extractExportBundle(e){return this.exportBundleCache}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundleCache=null;}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(".chat-container")||document.querySelector("main");if(!o)return r;const i=e=>{const t=e.closest("ms-chat-turn");return t&&t.id?t.id.replace(/^turn-/,""):null},a={},s=(e,t,n)=>{a[e]||(a[e]={});const r=`${t}-${n}`,o=a[e][r]||0;return a[e][r]=o+1,`${e}::${r}::${o}`},l=this.getUserQuerySelector(),c=e=>{const t=e.closest("ms-chat-turn");if(!t)return 0;const n=t.id;let r=t.nextElementSibling,o=0,i=false;for(;r;){if(r.querySelector(l))break;const e=r.querySelector(".chat-turn-container.model, .chat-turn-container:not(.user)");if(e){const t=e.querySelectorAll("ms-cmark-node");for(const e of Array.from(t)){if(e.closest("ms-thought-chunk"))continue;const t=e.textContent?.trim().length||0;t>0&&(i=true,o+=t);}}r=r.nextElementSibling;}return i&&n&&this.wordCountCache.set(n,o),0===o&&n&&this.wordCountCache.has(n)?this.wordCountCache.get(n):o};if(!t){const t=[];for(let n=1;n<=e;n++)t.push(`h${n}`);const a=Array.from(o.querySelectorAll(t.join(", ")));return a.forEach((t,l)=>{if(t.closest("textarea")||t.closest(".user-prompt-container"))return;if(this.isInRenderedMarkdownContainer(t))return;const c=parseInt(t.tagName.charAt(1),10);if(c<=e){const e={level:c,text:t.textContent?.trim()||"",element:t},d=i(t);if(d){const n=t.tagName.toLowerCase();e.id=s(d,n,e.text);}if(n){let n=null;for(let e=l+1;e0){const t=new Map,r=[],a=e=>{const t=(e.closest("ms-chat-turn")||e).getBoundingClientRect();if(o instanceof HTMLElement){const e=o.getBoundingClientRect();return o.scrollTop+(t.top-e.top)}return window.scrollY+t.top},l=u.filter(e=>Boolean(e.element)).map(e=>({index:e.index,renderOrder:a(e.element)})).sort((e,t)=>e.renderOrder-t.renderOrder),h=u.find(e=>"true"===e.button.getAttribute("aria-pressed")||e.button.classList.contains("ms-button-active")),g=e=>{const t=a(e);let n,r;for(const o of l){if(!(o.renderOrder<=t)){r=o;break}n=o;}return n?n.index:r?Math.max(0,r.index-1):h?.index??0};u.forEach(e=>{t.set(e.turnId,e.index);const o=e.element?this.extractUserQueryText(e.element):"",i=this.createAIStudioUserQueryOutlineItem(o||e.text,e.element,e.turnId,n&&e.element?c(e.element):void 0);r.push({item:i,order:1e5*e.index});});const p=Array.from(o.querySelectorAll(d.join(", ")));return p.forEach((a,l)=>{if(a.closest(".user-prompt-container")||a.closest("textarea"))return;if(this.isInRenderedMarkdownContainer(a))return;const c=a.tagName.toLowerCase(),d=parseInt(c.charAt(1),10);if(d>e)return;const u={level:d,text:a.textContent?.trim()||"",element:a},h=i(a);if(h&&(u.id=s(h,c,u.text)),n){let e=null;for(let n=l+1;ne.order-t.order).map(({item:e})=>e)}const h=`${l}, ${d.join(", ")}`,g=Array.from(o.querySelectorAll(h));return g.forEach((t,i)=>{const a=t.tagName.toLowerCase();if(t.classList.contains("user")&&t.classList.contains("chat-turn-container")){const e=t.closest("ms-chat-turn"),o=this.createAIStudioUserQueryOutlineItem(this.extractUserQueryText(t),t,e?.id,n?c(t):void 0);r.push(o);}else if(/^h[1-6]$/.test(a)){if(t.closest(".user-prompt-container")||t.closest("textarea"))return;if(this.isInRenderedMarkdownContainer(t))return;const s=parseInt(a.charAt(1),10);if(s<=e){const e={level:s,text:t.textContent?.trim()||"",element:t};if(n){let n=null;for(let t=i+1;te.remove());const r=this.extractAssistantResponseMarkdown(t).trim();if(n.length>0){const e=n.join("\n\n");return r?`${e}\n\n${r}`:e}return r}extractAssistantResponseMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll(`${Ts}, .author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]`).forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotesFromElement(e){const t=Array.from(e.querySelectorAll(Ts)),n=[];return t.forEach(e=>{const t=this.extractThoughtMarkdown(e).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractThoughtMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll('.author-label, .actions-container, button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove()),this.normalizeAssistantExportDom(t);const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}normalizeAssistantExportDom(e){this.unwrapCmarkNodes(e),this.replaceInlineCodeSpans(e),this.replaceKatexComponents(e),this.replaceCodeBlockComponents(e);}unwrapCmarkNodes(e){Array.from(e.querySelectorAll("ms-cmark-node")).forEach(e=>{e instanceof HTMLElement&&e.parentNode&&e.replaceWith(...Array.from(e.childNodes));});}replaceInlineCodeSpans(e){e.querySelectorAll(".inline-code").forEach(e=>{if(!(e instanceof HTMLElement))return;if("code"===e.tagName.toLowerCase())return;const t=document.createElement("code");t.textContent=e.textContent||"",e.replaceWith(t);});}replaceKatexComponents(e){e.querySelectorAll("ms-katex").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim()||"";if(!t)return;const n=document.createElement(e.classList.contains("inline")?"span":"div");n.className=e.classList.contains("inline")?"math-inline":"math-block",n.setAttribute("data-math",t),e.replaceWith(n);});}replaceCodeBlockComponents(e){e.querySelectorAll("ms-code-block").forEach(e=>{if(!(e instanceof HTMLElement))return;const t=this.extractCodeBlockFromComponent(e);if(!t)return;const n=document.createElement("pre"),r=document.createElement("code");t.language&&(r.className=`language-${t.language}`),r.textContent=t.code,n.appendChild(r),e.replaceWith(n);});}extractCodeBlockFromComponent(e){const t=e.querySelector("pre code")||e.querySelector("pre"),n=t?.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(!n.trim())return null;return {language:[e.getAttribute("data-test-language"),e.getAttribute("data-language"),e.querySelector(".mat-expansion-panel-header-title .ng-star-inserted:last-child")?.textContent].map(e=>e?.trim().toLowerCase()||"").find(e=>e&&"code"!==e)||"",code:n}}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=document.querySelectorAll(`${Es}, .model-prompt-container`);try{for(let e=t.length-1;e>=0;e-=1){const n=this.extractAssistantResponseText(t[e]).trim();if(n)return n}return null}finally{this.exportIncludeThoughtsOverride=e;}}isExportSnapshotElement(e){return e.hasAttribute(Is)}async collectExportMessageSnapshots(e,t){const n=Array.from((e.querySelector("ms-chat-session")||document).querySelectorAll(Cs)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ms}]`));return 0===n.length?this.collectExportMessageSnapshotsByScrollSweep(e,t):this.collectExportMessageSnapshotsByDomIteration(e,n,t)}async collectExportMessageSnapshotsByDomIteration(e,t,n){const r=e.scrollTop,o=this.shouldIncludeThoughtsInExport(),i=[];let a=[],s=[];const l=e=>{if(0===a.length||!o)return void(a=[]);const t=a[a.length-1],n=this.buildAssistantContentFromModelTurns(a,o);n&&i.push({role:Ns,turnKey:`assistant:${t.id||`idx:${e}`}`,order:e,content:n}),a=[];},c=()=>{if(0===s.length)return;const e=[];for(const t of s){const r=this.getUserContainerForTurn(t);if(!r)continue;const o=this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAttachments(r,n));o&&e.push(o);}if(e.length>0){const n=s[0],r=t.indexOf(n);i.push({role:Ls,turnKey:`user:${n.id||`idx:${r}`}`,order:r,content:e.join("\n\n")});}s=[];};try{for(let e=0;ee.order-t.order)}async retryMissingTurns(e,t,n,r){const o=new Set(t.filter(e=>e.role===Ls).map(e=>e.turnKey.replace(/^user:/,""))),i=new Set(t.filter(e=>e.role===Ns).map(e=>e.turnKey.replace(/^assistant:/,""))),a=[];let s=null;for(let c=0;c0&&t.push({role:Ls,turnKey:`user:${n.id||`idx:${o}`}`,order:o,content:a.join("\n\n")});}for(const r of l){const o=e.indexOf(r);if(o<0)continue;const i=[];for(let t=o-1;t>=0;t-=1){const n=e[t],r=n.querySelector(".chat-turn-container.model");if(!r||!this.isThoughtOnlyModelTurn(r))break;i.unshift(n);}i.push(r);for(const e of i){try{e.scrollIntoView({block:"start",behavior:"instant"});}catch{e.scrollIntoView({block:"start"});}await this.waitForTurnContentMounted(e,5e3);}const a=this.buildAssistantContentFromModelTurns(i,n);a&&t.push({role:Ns,turnKey:`assistant:${r.id||`idx:${o}`}`,order:o,content:a});}}}turnHasMountedContent(e){const t=e.querySelector("ms-prompt-chunk");if(!t)return false;if(t.querySelector("ms-text-chunk, ms-thought-chunk, ms-image-chunk, ms-file-chunk, img"))return true;return (t.textContent||"").trim().length>0}async waitForTurnContentMounted(e,t){const n=Date.now()+Math.floor(t/2);for(;Date.now()null!==e.closest(Ts))}buildAssistantContentFromModelTurns(e,t){if(0===e.length)return "";const n=[];for(const r of e){const e=r.querySelector(".chat-turn-container.model");if(!e)continue;if(this.isThoughtOnlyModelTurn(e)){if(!t)continue;this.extractThoughtBlockquotesFromElement(e).forEach(e=>n.push(e));continue}const o=this.getAssistantFragmentsForTurn(r),i=[];for(const t of o){const e=this.normalizeExportMessageContent(this.extractAssistantResponseText(t));e&&i.push(e);}i.length>0&&n.push(i.join("\n\n"));}return n.join("\n\n")}async collectExportMessageSnapshotsByScrollSweep(e,t){const n=this.buildExportSnapshotPositions(e),r=e.scrollTop;let o=[];try{for(const r of n){e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const n=this.readVisibleExportMessageSnapshots(e,t);o=this.mergeExportMessageBatch(o,n);}}finally{e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return this.repairLikelyTruncatedUserSnapshots(o,e,t)}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}readVisibleExportMessageSnapshots(e,t){return Array.from(e.querySelectorAll(Cs)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${Ms}]`)).flatMap(n=>this.extractExportSnapshotsFromTurn(n,e,t))}extractExportSnapshotsFromTurn(e,t,n){const r=[],o=this.getTurnRenderOrder(e,t),i=this.getUserContainerForTurn(e);if(i){const t=this.normalizeExportMessageContent(this.extractUserQueryExportContentWithAttachments(i,n));t&&r.push({role:Ls,turnKey:this.getExportTurnKey(e,"user",t),order:o,content:t});}const a=this.getAssistantFragmentsForTurn(e);if(a.length>0){let t="";a.forEach(e=>{const n=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));t=this.mergeSnapshotContent(t,n);}),t&&r.push({role:Ns,turnKey:this.getExportTurnKey(e,"assistant",t),order:o+.5,content:t});}return r}getTurnRenderOrder(e,t){const n=e.getBoundingClientRect();if(t instanceof HTMLElement){const e=t.getBoundingClientRect();return t.scrollTop+(n.top-e.top)}return window.scrollY+n.top}getUserContainerForTurn(e){return Array.from(e.querySelectorAll(".chat-turn-container.user")).filter(t=>t instanceof HTMLElement&&t.closest(Cs)===e)[0]||null}getAssistantFragmentsForTurn(e){return Array.from(e.querySelectorAll(As)).filter(t=>{if(!(t instanceof HTMLElement))return false;if(t.closest(Cs)!==e)return false;const n=t.parentElement?.closest(As);return n?.closest(Cs)!==e})}getExportTurnKey(e,t,n){const r=e.closest("ms-chat-turn")?.id?.replace(/^turn-/,"").trim();if(r)return `${t}:${r}`;return `${t}:content:${n.replace(/\s+/g," ").trim().slice(0,120)}`}mergeSnapshotContent(e,t){if(!t)return e;if(!e)return t;if(e===t||e.includes(t))return e;if(t.includes(e))return t;const n=this.normalizeSnapshotComparisonText(e),r=this.normalizeSnapshotComparisonText(t);if(n&&r){if(r.startsWith(n)&&t.length>=e.length)return t;if(n.startsWith(r)&&e.length>=t.length)return e}return `${e}\n\n${t}`.trim()}async repairLikelyTruncatedUserSnapshots(e,t,n){const r=e.filter(e=>this.isLikelyTruncatedUserSnapshot(e));if(0===r.length)return e;const o=e.map(e=>({...e})),i=t.scrollTop;try{for(const e of r){const r=Math.max(0,e.order-Math.max(120,.25*t.clientHeight)),i=e.order+Math.max(120,.25*t.clientHeight),a=[r,e.order,i].map(e=>Math.round(e));for(const s of a){t.scrollTop=s,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),await this.sleep(120);const r=this.readVisibleExportMessageSnapshots(t,n).find(t=>t.turnKey===e.turnKey);if(!r)continue;const i=o.findIndex(t=>t.turnKey===e.turnKey);if(-1===i)break;if(o[i]={...o[i],order:Math.min(o[i].order,r.order),content:this.mergeSnapshotContent(o[i].content,r.content)},!this.isLikelyTruncatedUserSnapshot(o[i]))break}}}finally{t.scrollTop=i,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return o}isLikelyTruncatedUserSnapshot(e){if(e.role!==Ls)return false;const t=e.content.trim();return /(?:\.{3}|…)$/.test(t)}normalizeSnapshotComparisonText(e){return e.replace(/\r\n/g,"\n").replace(/\u2026/g,"...").replace(/\.{3}\s*$/g,"").replace(/\s+/g," ").trim()}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));const n=e.map(e=>({...e}));let r=null;for(let o=0;ot.turnKey===e.turnKey);if(-1!==i){const t=n[i];n[i]={...t,order:Math.min(t.order,e.order),content:this.mergeSnapshotContent(t.content,e.content)},r=i;continue}const a=this.findNextKnownSnapshotIndex(n,t,o+1);let s=n.length;null!==r?(s=r+1,null!==a&&s>a&&(s=a)):null!==a&&(s=a),n.splice(s,0,{...e}),r=s;}return n}findNextKnownSnapshotIndex(e,t,n){for(let r=n;re.turnKey===n);if(-1!==o)return o}return null}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(Ms,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(_s,"1");const r=document.createElement("div");r.setAttribute(Is,e.role),r.textContent=e.content,n.appendChild(r),t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${Ms}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}getNewChatButtonSelectors(){return ['button[iconname="add"]','button[data-test-clear="outside"]','button .material-symbols-outlined[aria-hidden="true"]']} /** * 切换 AI Studio 主题 * AI Studio 使用 localStorage.aiStudioUserPreference.theme 存储主题 * 值域:light / dark / system * @param targetMode 目标主题模式 */ async toggleTheme(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);n.theme=e,localStorage.setItem("aiStudioUserPreference",JSON.stringify(n));const r=document.body;"dark"===e?(r.classList.add("dark-theme"),r.classList.remove("light-theme")):(r.classList.remove("dark-theme"),r.classList.add("light-theme")),r.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage}));const o=document.querySelector("app-root, ms-app, body");return o&&o.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}catch(t){return console.error("[AIStudioAdapter] toggleTheme error:",t),false}} /** * 将 Ophel 扩展配置应用到 AI Studio 的 localStorage * 在页面加载时调用,用于设置默认界面状态和模型 * @param settings Ophel 的 AI Studio 设置 */ applySettings(e){try{const t=localStorage.getItem("aiStudioUserPreference")||"{}",n=JSON.parse(t);let r=!1;if(void 0!==e.collapseNavbar){const t=!e.collapseNavbar;n.isNavbarExpanded!==t&&(n.isNavbarExpanded=t,r=!0);}if(void 0!==e.collapseTools){const t=!e.collapseTools;n.areToolsOpen!==t&&(n.areToolsOpen=t,r=!0);}if(void 0!==e.collapseAdvanced){const t=!e.collapseAdvanced;n.isAdvancedOpen!==t&&(n.isAdvancedOpen=t,r=!0);}if(void 0!==e.enableSearch&&n.enableSearchAsATool!==e.enableSearch&&(n.enableSearchAsATool=e.enableSearch,r=!0),e.defaultModel&&""!==e.defaultModel.trim()){const t=e.defaultModel.trim();n.promptModel!==t&&(n.promptModel=t,n._promptModelOverride=t,r=!0);}r&&(localStorage.setItem("aiStudioUserPreference",JSON.stringify(n)),window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:JSON.stringify(n),storageArea:localStorage})));}catch(t){console.error("[AIStudioAdapter] applySettings error:",t);}}},new class extends gs{activeOrganizationId=null;activeOrganizationIdExpiresAt=0;exportDocumentCache=[];exportIncludeThoughtsOverride=null;exportThoughtBlocks=new WeakMap;exportThoughtBlocksByAssistantIndex=new Map;match(){return window.location.hostname.includes("claude.ai")||window.location.hostname.includes("claude.com")}getSiteId(){return so}getName(){return "Claude"}getThemeColors(){return {primary:"#d97757",secondary:"#c66045"}}getNewTabUrl(){return "https://claude.ai/new"}isNewConversation(){return "/new"===window.location.pathname||"/"===window.location.pathname}isSharePage(){return window.location.pathname.startsWith("/public/")||window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&/^\/chat\/[a-f0-9-]+(?:\/|$)/i.test(window.location.pathname)}getConversationList(){const e=document.querySelectorAll('a[data-dd-action-name="sidebar-chat-item"]');return Array.from(e).map(e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"",o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"",a=window.location.href.includes(r);let s=false;const l=e.closest("div.flex.flex-col");if(l){const e=l.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=l.querySelector("ul"),r=n?.classList.contains("-mx-1.5");s=t||r;}return {id:r,title:i,url:t.startsWith("http")?t:`https://claude.ai${t}`,isActive:a,isPinned:s}}).filter(e=>e.id)}getSidebarScrollContainer(){const e=document.querySelector("nav");if(e){return e.querySelector("div.overflow-y-auto")||e}return null}async deleteConversationOnSite(e){return this.deleteConversationOnSiteInternal(e)}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt+5e3)return this.activeOrganizationId;if(this.isUserscriptRuntime()){const e=await this.fetchOrganizationIdFromApi();if(e)return this.activeOrganizationId=e,this.activeOrganizationIdExpiresAt=t+6e5,e;const n=this.getOrganizationIdFromStorage();if(n)return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getCookieValue("lastActiveOrg");return this.isValidOrganizationId(r)?(this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r):null}const n=this.getCookieValue("lastActiveOrg");if(this.isValidOrganizationId(n))return this.activeOrganizationId=n,this.activeOrganizationIdExpiresAt=t+6e5,n;const r=this.getOrganizationIdFromStorage();if(r)return this.activeOrganizationId=r,this.activeOrganizationIdExpiresAt=t+6e5,r;const o=await this.fetchOrganizationIdFromApi();return o?(this.activeOrganizationId=o,this.activeOrganizationIdExpiresAt=t+6e5,o):null}isUserscriptRuntime(){return true}async fetchOrganizationIdFromApi(){try{const e=await fetch("/api/organizations",{method:"GET",headers:{accept:"application/json, text/plain, */*"},credentials:"include"});if(!e.ok)return null;const t=await e.json();return this.extractOrganizationId(t)}catch{return null}}getOrganizationIdFromStorage(){const e=["lastActiveOrg","activeOrg","organizationId","lastActiveOrganization","LSS-lastActiveOrg"];for(const t of e){const e=localStorage.getItem(t),n=this.extractOrganizationId(e);if(n)return n}for(let t=0;t0?t:null}getCookieValue(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));if(!n)return null;try{return decodeURIComponent(n[1])}catch{return n[1]}}syncSidebarAfterRemoteDelete(e){const t=this.findConversationRow(e);if(!t)return;(t.closest("li")||t).remove();}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;const n=await this.findConversationMenuButton(t);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteMenuItem(n);if(!r)return false;if(this.simulateClick(r),await this.waitForConversationRemoved(e,1e3))return true;const o=await this.waitForDeleteConfirmButton();return o&&this.simulateClick(o),this.waitForConversationRemoved(e,5e3)}async isConversationStillVisible(e){return !!(await this.findConversationRowWithRetry(e))}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`a[data-dd-action-name="sidebar-chat-item"][href="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href$="/chat/${e}"], a[data-dd-action-name="sidebar-chat-item"][href*="/chat/${e}?"]`)}async findConversationMenuButton(e){const t=e.closest("li")||e.parentElement||e,n=['button[aria-haspopup="menu"]','button[data-testid*="menu"]','button[aria-label*="more"]','button[aria-label*="More"]','button[aria-label*="options"]','button[aria-label*="Options"]','button[aria-label*="更多"]','button[aria-label*="选项"]','button[aria-label*="選項"]'].join(", ");for(let r=0;r<10;r++){t.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),t.dispatchEvent(new MouseEvent("mousemove",{bubbles:true})),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const r=Array.from(t.querySelectorAll(n)).filter(e=>this.isVisible(e));if(r.length>0){const e=this.pickRightMostElement(r);if(e)return e}const o=Array.from(t.querySelectorAll("button")).filter(e=>this.isVisible(e));if(o.length>0){const e=this.pickRightMostElement(o);if(e)return e}await this.sleep(80);}return null}getMenuScopeFromTrigger(e){const t=e.getAttribute("aria-controls")||e.getAttribute("aria-owns");if(t){const e=document.getElementById(t);if(e)return e}const n=Array.from(document.querySelectorAll('[role="menu"], [data-radix-menu-content], [data-state="open"]')).filter(e=>this.isVisible(e));return 0===n.length?null:this.pickNearestElement(e,n)}async waitForDeleteMenuItem(e,t=2500){const n=Date.now();for(;Date.now()-nthis.isVisible(e))||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nt.getBoundingClientRect().right-e.getBoundingClientRect().right)[0]}pickNearestElement(e,t){if(0===t.length)return null;const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2;let i=null,a=Number.POSITIVE_INFINITY;for(const s of t){const e=s.getBoundingClientRect(),t=e.left+e.width/2,n=e.top+e.height/2,l=Math.hypot(t-r,n-o);ln.includes(e.toLowerCase()))}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getTextareaSelectors(){return ['[contenteditable="true"]',".ProseMirror",'div[role="textbox"]']}getSubmitButtonSelectors(){return ['button[aria-label="Send Message"]','button[data-testid="send-button"]','button[aria-label="Send"]']}isValidTextarea(e){if(null===e.offsetParent)return false;if(e.closest(".gh-main-panel"))return false;const t="true"===e.getAttribute("contenteditable"),n=e.classList.contains("ProseMirror"),r="textbox"===e.getAttribute("role");return t||n||r}insertPrompt(e){const t=this.getTextareaElement();if(!t)return false;t.focus();try{if(document.execCommand("selectAll",!1,void 0),!document.execCommand("insertText",!1,e))throw new Error("execCommand failed")}catch{t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e){e.focus();try{document.execCommand("selectAll",!1,void 0),document.execCommand("delete",!1,void 0);}catch{e.textContent="";}e.dispatchEvent(new Event("input",{bubbles:true}));}}getConversationTitle(){const e=this.getSessionId();if(e&&"default"!==e){const t=document.querySelector(`a[href*="${e}"]`);if(t)return t.querySelector("span.truncate")?.textContent?.trim()||null}return null}findClaudeScrollContainer(){const e=e=>{if(!e)return false;const t=window.getComputedStyle(e).overflowY;return !("auto"!==t&&"scroll"!==t&&"overlay"!==t&&"true"!==e.getAttribute("data-autoscroll-container"))&&e.scrollHeight>e.clientHeight+4};let t=Array.from(document.querySelectorAll('.font-claude-response, [data-testid="user-message"]')).find(e=>!e.closest(rg))||null;for(;t&&t!==document.body;){if(e(t))return t;t=t.parentElement;}const n=['[data-autoscroll-container="true"]',"#main-content .overflow-y-scroll","#root .overflow-y-auto.overflow-x-hidden"];for(const r of n){const t=document.querySelector(r);if(e(t))return t}return null}getScrollContainer(){const e=this.findClaudeScrollContainer(),t=document.scrollingElement,n=e?e.scrollHeight-e.clientHeight:-1,r=t?t.scrollHeight-t.clientHeight:-1;return e&&t&&r>n+100&&t.scrollHeight>t.clientHeight+4?t:e||(t&&t.scrollHeight>t.clientHeight+4?t:super.getScrollContainer())}getChatContentSelectors(){return ['div[data-testid="user-message"]',"div.font-claude-response"]}isClaudeDocumentPanelOpen(){return null!==this.getClaudeDocumentMarkdownElement()}getClaudeDocumentRoot(){return document.querySelector(rg)}getClaudeDocumentMarkdownElement(){return document.querySelector("#wiggle-file-content .standard-markdown, #wiggle-file-content .progressive-markdown")}getClaudeDocumentTitle(){return this.getClaudeDocumentRoot()?.querySelector("h1")?.textContent?.trim()||""||null}getClaudeArtifactCells(e=document){return Array.from(e.querySelectorAll(ig))}getClaudeDocumentArtifactCells(e=document){return this.getClaudeArtifactCells(e).filter(e=>this.isMarkdownDocumentArtifact(e))}isMarkdownDocumentArtifact(e){return /\bMD\b/i.test(this.getClaudeArtifactMetadata(e))}getClaudeArtifactMetadata(e){return e.querySelector(".text-text-400")?.textContent?.trim()||""}getClaudeArtifactTitle(e){return e.querySelector(".line-clamp-1")?.textContent?.trim()||""||"Document"}getClaudeArtifactButton(e){const t=e.closest(".group\\/artifact-block, [class*='group/artifact-block']"),n=t?.querySelector('button[aria-label="View Document"]')||e.querySelector('button[aria-label="View Document"]');return n instanceof HTMLElement?n:null}async openClaudeArtifactDocument(e){const t=this.getClaudeArtifactButton(e);if(!t)return null;const n=this.getClaudeDocumentSignature();return t.scrollIntoView({block:"center",inline:"nearest",behavior:"auto"}),await new Promise(e=>setTimeout(e,50)),this.simulateClick(t),this.waitForClaudeDocumentMarkdown(n)}getClaudeDocumentSignature(e=this.getClaudeDocumentMarkdownElement()){const t=e?.textContent?.trim()||"";return t?`${t.length}:${t.slice(0,160)}:${t.slice(-160)}`:""}async waitForClaudeDocumentMarkdown(e="",t=3e3){const n=Date.now();for(;Date.now()-nsetTimeout(e,100));}return this.getClaudeDocumentMarkdownElement()}closeClaudeDocumentPanel(){const e=this.findClaudeDocumentPanelButton('button[aria-label="Go back"]');e instanceof HTMLElement&&this.simulateClick(e);}findClaudeDocumentPanelButton(e){const t=this.getClaudeDocumentRoot();let n=t?.parentElement||null;for(;n&&n!==document.body;){const t=n.querySelector(e);if(t instanceof HTMLElement)return t;n=n.parentElement;}return null}getModelName(){const e=document.querySelector('button[data-testid="model-selector-dropdown"]');return e&&e.textContent?e.textContent.trim():null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-testid="model-selector-dropdown"]'],menuItemSelector:'[role="menuitem"], [role="menuitemradio"]',checkInterval:1e3,maxAttempts:20,subMenuSelector:'[aria-haspopup="menu"]',subMenuTriggers:["more models","更多模型"]}}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,Math.max(t.width-1,1))),r=t.top+Math.max(1,Math.min(t.height/2,Math.max(t.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r},i=t=>{"function"==typeof PointerEvent&&e.dispatchEvent(new PointerEvent(t,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));};i("pointerenter"),i("pointerover"),i("pointermove"),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new MouseEvent("mousemove",o));const a=e.getAttribute("role"),s=(e.textContent||"").toLowerCase();"menuitem"===a&&(e.matches('[aria-haspopup="menu"]')||s.includes("more models")||s.includes("更多模型"))||(i("pointerdown"),e.dispatchEvent(new MouseEvent("mousedown",o)),i("pointerup"),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o)));}getNewChatButtonSelectors(){return ['a[data-dd-action-name="sidebar-new-item"]','a[href="/new"]']}getDefaultLockSettings(){return {enabled:false,keyword:"sonnet"}}getClaudeChatCandidates(e){return Array.from(e.querySelectorAll(this.getChatContentSelectors().join(", ")))}getRelativeTop(e,t){const n=e.getBoundingClientRect();return t.getBoundingClientRect().top-n.top+e.scrollTop}getOutlineRoot(){return this.getScrollContainer()||this.findClaudeScrollContainer()||document}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getClaudeChatCandidates(e);if(!t.length)return null;const n=e.scrollTop;let r=null,o=Number.NEGATIVE_INFINITY;t.forEach(t=>{const i=this.getRelativeTop(e,t);i<=n+100&&i>o&&(r=t,o=i);}),r||(r=t[0],o=this.getRelativeTop(e,r));const i=n-o,a=r.getAttribute("data-message-id")||r.id;if(a){let e=`[data-message-id="${a}"]`;return r.matches(e)||(e=`#${a}`),{type:"selector",selector:e,offset:i}}const s=t.indexOf(r);if(-1===s)return null;return {type:"index",index:s,offset:i,textSignature:(r.textContent||"").trim().substring(0,50)}}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("selector"===e.type&&e.selector)n=t.querySelector(e.selector);else if("index"===e.type&&"number"==typeof e.index){const r=this.getClaudeChatCandidates(t);if(r[e.index]){if(n=r[e.index],e.textSignature){(n.textContent||"").trim().substring(0,50)!==e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||n);}}else e.textSignature&&(n=r.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature)||null);}if(!n)return false;const r=this.getRelativeTop(t,n)+(e.offset||0);return t.scrollTo({top:r,behavior:"instant"}),true}getOutlineSources(){const e=[{id:"conversation",kind:"conversation",label:"对话",available:true}],t=this.extractClaudeDocumentOutline(6,false);return t.length>0&&e.push({id:ng,kind:"document",label:"文档",available:true,count:t.length}),e}supportsDynamicOutlineSources(){return true}getOutlineSourcesSignature(){const e=this.getClaudeDocumentSignature();return `conversation:1|${ng}:${e||"0"}`}extractOutlineForSource(e,t=6,n=false,r=false){return e===ng?this.extractClaudeDocumentOutline(t,r):this.extractOutline(t,n,r)}extractOutline(e=6,t=false,n=false){const r=[],o=this.getOutlineRoot(),i=e=>e.replace(/[\s\S]*?<\/thinking>/gi,"").trim(),a=this.getUserQuerySelector(),s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(rg)&&null!==e.closest(".font-claude-response"));if(s.forEach((t,o)=>{const i=parseInt(t.tagName[1]);if(i>e)return;if(t.classList.contains("pointer-events-none"))return;if(t.classList.contains("sr-only"))return;const a=t.textContent?.trim()||"";if(!a)return;const l={level:i,text:a.length>200?a.slice(0,200):a,element:t,isUserQuery:false,isTruncated:a.length>80};if(n){let e=null;for(let t=o+1;t{const t=e.textContent?.trim()||"";if(!t)return;const s={level:0,text:t.length>200?t.slice(0,200):t,element:e,isUserQuery:true,isTruncated:t.length>60};n&&(s.wordCount=(e=>{const t=Array.from(o.querySelectorAll(a)),n=Array.from(o.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(rg)),r=t.indexOf(e);if(-1===r)return 0;const s=t[r+1];let l=0;for(const o of n){if(!(e.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(s&&s.compareDocumentPosition(o)&Node.DOCUMENT_POSITION_FOLLOWING)continue;const t=o.querySelector(".standard-markdown, .progressive-markdown");if(t){const e=t.textContent?.trim()||"";l+=i(e).length;}}return l})(e)),r.push(s);}),r.sort((e,t)=>{if(!e.element||!t.element)return 0;return e.element.compareDocumentPosition(t.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1});}return r}extractClaudeDocumentOutline(e=6,t=false){const n=this.getClaudeDocumentMarkdownElement();return n instanceof Element?vl(n,{maxLevel:e,showWordCount:t,idPrefix:"claude-document",shouldSkipHeading:e=>this.shouldSkipClaudeDocumentHeading(e),calculateWordCount:(e,t,n)=>this.calculateRangeWordCount(e,t,n)}):[]}shouldSkipClaudeDocumentHeading(e){return e.classList.contains("sr-only")||this.isInRenderedMarkdownContainer(e)}findClaudeDocumentHeading(e,t){const n=this.getClaudeDocumentMarkdownElement();return n?wl(n,e,t,e=>this.shouldSkipClaudeDocumentHeading(e)):null}getOutlineScrollContainer(e="conversation"){if(e===ng){return xl(this.getClaudeDocumentMarkdownElement())||this.getClaudeDocumentRoot()}return this.getScrollContainer()}async resolveOutlineTarget(e,t,n="conversation"){return n===ng?this.findClaudeDocumentHeading(e.level,e.text):super.resolveOutlineTarget(e,t,n)}scrollToOutlineSourceTarget(e,t="conversation"){if(t===ng){if(kl(e,xl(e)||this.getOutlineScrollContainer(t)))return}this.scrollToOutlineTarget(e);}isGenerating(){if(document.querySelector('button[aria-label="Stop response"]'))return true;return !!document.querySelector('[class*="streaming"], [class*="typing"]')}getStopButtonSelectors(){return ['button[aria-label="Stop response"]']}getNetworkMonitorConfig(){return {urlPatterns:["/api/"],urlPathEndsWith:["/completion"],silenceThreshold:500}}getExportConfig(){return {userQuerySelector:'[data-testid="user-message"]',assistantResponseSelector:".font-claude-response",turnSelector:null,useShadowDOM:false}}getAssistantMermaidSupportMode(){return "native"}getLatestReplyText(){const e=Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(rg));if(0===e.length)return null;const t=e[e.length-1],n=t.querySelector(".standard-markdown, .progressive-markdown");if(n){return Fi(n).trim()||n.textContent?.trim()||null}return t.textContent?.trim()||null}getResponseContainerSelector(){return ".font-claude-response"}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportDocumentCache=[],this.exportThoughtBlocks=new WeakMap,this.exportThoughtBlocksByAssistantIndex=new Map;const t=e.includeThoughts?await this.expandClaudeThoughtBlocksForExport():[];e.includeThoughts&&this.captureClaudeThoughtBlocksForExport();const n={documentPanelWasOpen:this.isClaudeDocumentPanelOpen(),documentSignature:this.getClaudeDocumentSignature(),documentTitle:this.getClaudeDocumentTitle(),documentArtifactIndex:null,thoughtContainersExpandedForExport:t};if(!this.shouldCollectClaudeDocumentsForExport(e))return n;if(this.exportDocumentCache=await this.collectClaudeDocumentArtifacts(),n.documentPanelWasOpen&&n.documentSignature){const e=this.findCachedClaudeDocumentByState(n);n.documentArtifactIndex=e?.index??null;}return n}async restoreConversationAfterExport(e,t){try{if(!this.isClaudeExportLifecycleState(t))return;if(t.documentPanelWasOpen)return void(await this.restoreClaudeDocumentPanel(t));this.closeClaudeDocumentPanel();}finally{this.isClaudeExportLifecycleState(t)&&this.restoreClaudeThoughtBlocksAfterExport(t),this.exportDocumentCache=[],this.exportIncludeThoughtsOverride=null,this.exportThoughtBlocks=new WeakMap,this.exportThoughtBlocksByAssistantIndex=new Map;}}isClaudeExportLifecycleState(e){return "object"==typeof e&&null!==e&&"documentPanelWasOpen"in e&&"boolean"==typeof e.documentPanelWasOpen}shouldCollectClaudeDocumentsForExport(e){return "markdown"===e.format||"clipboard"===e.format}async restoreClaudeDocumentPanel(e){if(!e.documentSignature||this.getClaudeDocumentSignature()===e.documentSignature)return;const t=this.findCachedClaudeDocumentByState(e),n=true===t?.element.isConnected?t.element:this.getClaudeDocumentArtifactCells()[t?.index??-1];n&&await this.openClaudeArtifactDocument(n);}findCachedClaudeDocumentByState(e){if(null!==e.documentArtifactIndex&&void 0!==e.documentArtifactIndex){const t=this.exportDocumentCache.find(t=>t.index===e.documentArtifactIndex);if(t)return t}if(e.documentSignature){const t=this.exportDocumentCache.find(t=>t.signature===e.documentSignature);if(t)return t}if(e.documentTitle){const t=this.exportDocumentCache.filter(t=>t.title===e.documentTitle);if(1===t.length)return t[0]}return null}async extractExportBundle(e){return this.hasClaudeExportAssets()?this.createExportBundleFromMessages(e=>this.extractClaudeExportMessages(e)):null}async extractExportMessages(e){return 0!==this.exportDocumentCache.length||this.isClaudeDocumentPanelOpen()||this.hasClaudeUserAttachments()||this.hasClaudeThoughtExportCache()?this.extractClaudeExportMessages():null}getObserveTarget(){return this.getScrollContainer()}getUserQuerySelector(){return '[data-testid="user-message"]'}extractUserQueryText(e){return e.textContent?.trim()||""}extractUserQueryExportContent(e){return this.extractClaudeUserQueryExportContent(e)}hasClaudeExportAssets(){return this.exportDocumentCache.length>0||this.hasClaudeUserAttachments()}hasClaudeUserAttachments(){const e=this.getOutlineRoot();return Array.from(e.querySelectorAll(this.getUserQuerySelector())).some(e=>this.extractClaudeUserAttachments(e).length>0)}extractUserQueryMarkdown(e){const t=e.querySelectorAll("p.whitespace-pre-wrap");if(0===t.length)return "";const n=[];return t.forEach(e=>{const t=e.textContent||"";dg(t)&&n.push(t);}),0===n.length?"":"# CLAUDE_INCREMENTAL\nplaceholder"}replaceUserQueryContent(e,t){if(e.querySelector(".gh-claude-enhanced"))return false;const n=e.querySelectorAll("p.whitespace-pre-wrap");if(0===n.length)return false;let r=false;return n.forEach(e=>{const t=e.textContent||"";if(!dg(t))return;const n=Hh(t,false,{enableMath:true}),o=document.createElement("div");o.className="gh-claude-enhanced gh-user-query-markdown gh-markdown-preview whitespace-pre-wrap break-words",o.innerHTML=n,e.replaceWith(o),r=true;}),r}extractClaudeUserQueryExportContent(e,t){const n=this.extractUserQueryText(e).trim(),r=this.extractClaudeUserAttachments(e);if(0===r.length)return n;const o=this.formatClaudeUserImageAttachments(r,t),i=this.formatClaudeUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractClaudeUserAttachments(e){const t=this.getClaudeUserMessageContainer(e);if(!t)return [];const n=[],r=new Set;return this.extractClaudeUserImageAttachments(t).forEach(e=>{const t=`image:${e.source||e.name}`;r.has(t)||(r.add(t),n.push(e));}),this.extractClaudeUserFileAttachments(t).forEach(e=>{const t=`file:${e.source||e.name}:${e.type||""}`;r.has(t)||(r.add(t),n.push(e));}),n}getClaudeUserMessageContainer(e){const t=e.closest('[data-user-message-bubble="true"]');if(!t)return e;let n=null,r=t.parentElement;for(;r&&r!==document.body&&!r.matches(".font-claude-response, main, [role='main']")&&!(r.querySelectorAll(this.getUserQuerySelector()).length>1);){if(r.querySelector(ag)||r.querySelector("img")){n=r;break}r=r.parentElement;}return n||t}extractClaudeUserImageAttachments(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&!e.closest(rg)).flatMap(e=>{if(e.closest(ag))return [];const t=fa(e.currentSrc||e.src||e.getAttribute("src")||"");if(!t||!ba(t))return [];const n=(e.alt||"uploaded image").replace(/\s+/g," ").trim();return [{kind:"image",name:n||"uploaded image",alt:n,source:t}]})}extractClaudeUserFileAttachments(e){return Array.from(e.querySelectorAll(ag)).flatMap(e=>{const t=this.extractClaudeUserFileName(e);if(!t)return [];return [{kind:"file",name:t,type:this.extractClaudeUserFileType(e),source:this.extractClaudeUserFileSource(e)}]})}extractClaudeUserFileName(e){const t=e.querySelector("h1, h2, h3, h4, h5, h6")?.textContent?.trim();if(t)return t;const n=e.querySelector("[aria-label]")?.getAttribute("aria-label")||"";return n.split(",")[0]?.trim()||""}extractClaudeUserFileType(e){const t=Array.from(e.querySelectorAll("p")).map(e=>e.textContent?.trim()||"").find(e=>/^[A-Za-z0-9.+-]{1,12}$/.test(e));if(t)return t.toLowerCase();const n=e.querySelector("[aria-label]")?.getAttribute("aria-label")||"";return n.split(",")[1]?.trim().toLowerCase()||""}extractClaudeUserFileSource(e){const t=Array.from(e.querySelectorAll("a[href]")).filter(e=>e instanceof HTMLAnchorElement);for(const o of t){const e=fa(o.href||o.getAttribute("href")||"");if(ba(e))return e}const n=e.querySelector("img");if(n instanceof HTMLImageElement){const e=fa(n.currentSrc||n.src||n.getAttribute("src")||"");if(ba(e))return e}const r=this.extractClaudeDownloadableAttributeUrl(e);return r||""}extractClaudeDownloadableAttributeUrl(e){const t=["href","src","data-href","data-src","data-url","data-file-url","data-download-url"],n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of t){const t=fa(r.getAttribute(e)||"");if(ba(t))return t}return ""}formatClaudeUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId(),getAlt:e=>e.alt||e.name||"uploaded image"})}formatClaudeUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),getLabel:e=>e.type&&!this.fileNameEndsWithType(e.name,e.type)?`${e.name} (${e.type})`:e.name})}fileNameEndsWithType(e,t){const n=e.toLowerCase(),r=t.replace(/^\./,"").toLowerCase();return !!r&&n.endsWith(`.${r}`)}async collectClaudeDocumentArtifacts(){const e=[],t=this.getClaudeDocumentArtifactCells();for(let n=0;nt.element===e);if(t)return t;if(!this.isMarkdownDocumentArtifact(e))return null;const n=this.getClaudeDocumentArtifactCells().indexOf(e);if(n>=0){const e=this.exportDocumentCache.find(e=>e.index===n);if(e)return e}const r=this.getClaudeArtifactTitle(e),o=this.exportDocumentCache.filter(e=>e.artifactTitle===r||e.title===r);return 1===o.length?o[0]:1===this.exportDocumentCache.length?this.exportDocumentCache[0]:null}extractClaudeExportMessages(e){const t=[],n=this.getOutlineRoot(),r=Array.from(n.querySelectorAll(this.getUserQuerySelector())),o=Array.from(n.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(rg)),i=Math.max(r.length,o.length);for(let a=0;a{if(e.matches(ig))return void i.push(this.formatClaudeArtifactExportContent(e,t));const n=Fi(this.prepareClaudeAssistantMarkdownBlockForExport(e,t)).trim()||e.textContent?.trim()||"";i.push(n);});const a=i.filter(Boolean).join("\n\n").trim();if(r&&o.length>0){const e=o.join("\n\n");return a?`${e}\n\n${a}`:e}return a}getClaudeAssistantExportBlocks(e){return Array.from(e.querySelectorAll(`${og}, ${ig}`)).filter(e=>!e.closest(rg)&&!this.isInsideClaudeThoughtBlock(e)).filter(t=>{const n=t.parentElement?.closest(`${og}, ${ig}`);return !n||!e.contains(n)})}prepareClaudeAssistantMarkdownBlockForExport(e,t){const n=this.getClaudeArtifactCells(e),r=e.cloneNode(true);return Array.from(r.querySelectorAll(ig)).forEach((e,r)=>{const o=n[r]||e,i=document.createElement("p");i.textContent=this.formatClaudeArtifactExportContent(o,t),e.replaceWith(i);}),r}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}async expandClaudeThoughtBlocksForExport(){const e=this.getClaudeThoughtToggleButtons(document),t=[];for(const n of e){if("true"===n.getAttribute("aria-expanded"))continue;const e=this.getClaudeThoughtBlockContainer(n);if(!e)continue;await this.openClaudeThoughtBlock(n,e)&&t.push(e);}return t}async openClaudeThoughtBlock(e,t){try{e.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});}catch{e.scrollIntoView({block:"center",inline:"nearest"});}return this.simulateClick(e),!!(await this.waitForClaudeThoughtBlockExpanded(t,900))||(e.isConnected&&"true"!==e.getAttribute("aria-expanded")?(e.click(),this.waitForClaudeThoughtBlockExpanded(t,1800)):this.waitForClaudeThoughtBlockExpanded(t,1800))}async waitForClaudeThoughtBlockExpanded(e,t){const n=Date.now();for(;Date.now()-n{if(!e.isConnected)return;const t=e.querySelector(sg);t instanceof HTMLElement&&"true"===t.getAttribute("aria-expanded")&&this.simulateClick(t);});}getClaudeThoughtToggleButtons(e=document){return Array.from(e.querySelectorAll(sg)).filter(e=>e instanceof HTMLElement&&this.isClaudeThoughtToggleButton(e))}isClaudeThoughtToggleButton(e){if(!e.closest(".font-claude-response"))return false;const t=this.getClaudeThoughtBlockContainer(e);if(!t)return false;const n=t.querySelector(lg)?.textContent?.trim();return Boolean(n)}getClaudeThoughtBlockContainer(e){const t=e.closest(".font-claude-response");let n=null,r=e.parentElement;for(;r&&r!==t&&r!==document.body;){const e=null!==r.querySelector(lg),t=null!==r.querySelector(sg);if(e&&t&&(n=r,this.isClaudeThoughtRootCandidate(r)))return r;r=r.parentElement;}return n}isClaudeThoughtRootCandidate(e){return ("string"==typeof e.className?e.className:"").includes("grid-rows")||null!==e.querySelector(".row-start-2")}isInsideClaudeThoughtBlock(e){return null!==this.getClaudeThoughtBlockContainer(e)}captureClaudeThoughtBlocksForExport(){Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(rg)).forEach((e,t)=>{const n=this.extractClaudeThoughtBlockquotes(e);n.length>0&&(this.exportThoughtBlocks.set(e,n),this.exportThoughtBlocksByAssistantIndex.set(t,n));});}hasClaudeThoughtExportCache(){return this.exportThoughtBlocksByAssistantIndex.size>0}getClaudeThoughtBlocksForElement(e,t){if(void 0!==t){const e=this.exportThoughtBlocksByAssistantIndex.get(t);if(e)return e}const n=this.exportThoughtBlocks.get(e);if(n)return n;const r=e.closest(".font-claude-response");if(r){const e=this.exportThoughtBlocks.get(r);if(e)return e}const o=this.getClaudeAssistantResponseIndex(e);if(o>=0){const e=this.exportThoughtBlocksByAssistantIndex.get(o);if(e)return e}return this.extractClaudeThoughtBlockquotes(e)}getClaudeAssistantResponseIndex(e){const t=e.matches(".font-claude-response")?e:e.closest(".font-claude-response");return t?Array.from(document.querySelectorAll(".font-claude-response")).filter(e=>!e.closest(rg)).indexOf(t):-1}extractClaudeThoughtBlockquotes(e){const t=this.getClaudeThoughtToggleButtons(e),n=[],r=new Set;return t.forEach(e=>{const t=this.getClaudeThoughtBlockContainer(e);if(!t||r.has(t))return;r.add(t);const o=this.extractClaudeThoughtMarkdown(t).trim();if(!o)return;const i=t.querySelector(lg)?.textContent?.trim()||"";n.push(this.formatAsThoughtBlockquote(o,i));}),n}extractClaudeThoughtMarkdown(e){const t=e.cloneNode(true);return t.querySelectorAll(`${sg}, ${lg}, svg`).forEach(e=>e.remove()),Fi(t).trim()||this.extractTextWithLineBreaks(t).trim()}formatAsThoughtBlockquote(e,t=""){const n=t.replace(/\s+/g," ").trim();return ["> [Thoughts]",...n?[`> **${n}**`,">"]:[],...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}formatClaudeArtifactExportContent(e,t){const n=this.getClaudeArtifactTitle(e),r=this.findCachedClaudeDocumentForArtifact(e);return r?.content?t?La(t,r.content,{title:r.title||n,fallbackTitle:"claude-document",directory:"assets/documents",idPrefix:"claude-document"}):this.formatClaudeDocumentInlineContent(r.content,r.title||n):this.formatClaudeArtifactPlaceholder(e)}formatClaudeDocumentInlineContent(e,t){const n=e.trim();return n?/^#{1,6}\s+/m.test(n)?n:`### ${t}\n\n${n}`:""}formatClaudeArtifactPlaceholder(e,t=""){const n=this.getClaudeArtifactTitle(e),r=this.getClaudeArtifactMetadata(e);return `[Artifact: ${n}${r?` - ${r}`:""}${t?` | Download: ${t}`:""}]`}extractAssistantResponseText(e){return this.extractClaudeAssistantResponseTextWithDocuments(e)}getConversationObserverConfig(){return {selector:'a[data-dd-action-name="sidebar-chat-item"]',shadow:false,extractInfo:e=>{const t=e.getAttribute("href")||"",n=t.match(/\/chat\/([a-f0-9-]+)/),r=n?n[1]:"";if(!r)return null;const o=e.querySelector("span.truncate"),i=o?.textContent?.trim()||"";let a=false;const s=e.closest("div.flex.flex-col");if(s){const e=s.querySelector("h3"),t=e&&!e.hasAttribute("role"),n=s.querySelector("ul"),r=n?.classList.contains("-mx-1.5");a=t||r;}return {id:r,title:i,url:`https://claude.ai${t}`,isActive:window.location.href.includes(r),isPinned:a}},getTitleElement:e=>e.querySelector("span.truncate")}}navigateToConversation(e,t){const n=t||`https://claude.ai/chat/${e}`,r=document.querySelector(`a[href*="${e}"]`);return r?(r.click(),true):(window.location.href=n,true)}getSessionName(){return this.getConversationTitle()}getWidthSelectors(){return [{selector:"#main-content .max-w-3xl",property:"max-width"},{selector:"#main-content .max-w-4xl",property:"max-width"}]}getZenModeConfig(){return {hide:['nav:has(a[data-dd-action-name="sidebar-chat-item"])']}}getCleanModeConfig(){return {hide:['[data-disclaimer="true"]']}}getUserQueryWidthSelectors(){return [{selector:'[data-testid="user-message"]',property:"max-width"}]}async toggleTheme(e){try{const t=localStorage.getItem("LSS-userThemeMode"),n="system"===e?window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light":e,r={value:"system"===e?"auto":e,tabId:cg(),timestamp:Date.now()},o=JSON.stringify(r);return localStorage.setItem("LSS-userThemeMode",o),function(e){const t=document.documentElement,n=document.body;t.classList.toggle("dark","dark"===e),t.classList.remove("light"),t.style.colorScheme=e,n&&(n.classList.remove("dark","light"),n.removeAttribute("data-theme"),n.style.removeProperty("color-scheme"));}(n),window.dispatchEvent(new StorageEvent("storage",{key:"LSS-userThemeMode",oldValue:t,newValue:o,storageArea:localStorage})),await new Promise(e=>setTimeout(e,300)),!0}catch(t){return console.error("[ClaudeAdapter] toggleTheme error:",t),false}}},new class extends gs{nativeOutlineCache=null;nativeOutlineRevealRequestId=0;exportSnapshotRoot=null;exportSnapshotActive=false;exportIncludeThoughtsOverride=null;exportBundleCache=null;match(){const e="chat.deepseek.com"===window.location.hostname;return e&&this.consumePendingDeleteRefresh(),e}getSiteId(){return bo}getName(){return "DeepSeek"}getThemeColors(){return {primary:"#4b6bfe",secondary:"#3a5ae0"}}getNativeThemeCss(){return "\n/* =============================================\n * DeepSeek 站点原生主题适配器 (DeepSeek Theme Adapter)\n * ============================================= */\nbody, page, .ds-theme {\n /* 核心页面背景层 - 覆盖基础背景 */\n // --dsw-alias-bg-base: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n --dsr-side-hover-bg: var(--gh-hover) !important;\n\n --dsw-alias-markdown-inline-code: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block-banner: var(--gh-bg-tertiary) !important;\n --dsw-alias-markdown-code-block: var(--gh-bg-secondary) !important;\n}\n\n/* 侧边栏背景 */\n.b8812f16, .f3d18f6a {\n background-color: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n}\n"}getTextareaSelectors(){return ['textarea[placeholder*="DeepSeek"]','textarea[placeholder*="deepseek"]',"textarea.ds-scroll-area","form textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=window.location.pathname,t=e.match(ug);if(t?.[1])return t[1];const n=e.match(hg);return n?.[1]||""}isNewConversation(){const e=window.location.pathname;return !this.isSharePage()&&("/"===e||"/a/chat"===e||"/a/chat/"===e||!ug.test(e))}isSharePage(){return window.location.pathname.startsWith("/share/")}getNewTabUrl(){return "https://chat.deepseek.com/"}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";return t&&"DeepSeek"!==t&&t.replace(/\s*[-|]\s*DeepSeek$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:pg,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>this.findTitleElement(e)}}async deleteConversationOnSite(e){const t=this.getSessionId(),n=this.getUserToken();if(!n)return {id:e.id,success:false,method:"api",reason:Ig};const r=await this.deleteConversationViaApi(e,n);return r.success&&(e.id===t?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getSessionId(),n=this.getUserToken();if(!n)return e.map(e=>({id:e.id,success:false,method:"api",reason:Ig}));const r=[];let o=false,i=false;for(const a of e){const e=await this.deleteConversationViaApi(a,n);r.push(e),e.success&&(i=true,a.id===t&&(o=true));}return i&&(o?this.scheduleHomeRefreshAfterDelete():this.schedulePageReloadAfterDelete()),r}getConversationTitle(){if(this.isSharePage())return this.getShareConversationTitle();const e=this.getSessionId(),t=(e?document.querySelector(`${pg}[href*="/a/chat/s/${e}"]`):null)||document.querySelector(`${pg}[aria-current="page"]`);return t?this.extractConversationTitle(t):null}navigateToConversation(e,t){const n=document.querySelector(`${pg}[href*="/a/chat/s/${e}"]`);return n?(n.click(),true):super.navigateToConversation(e,t||`https://chat.deepseek.com/a/chat/s/${e}`)}getSidebarScrollContainer(){const e=document.querySelector(pg);return e?.closest(".ds-scroll-area")||null}getZenModeConfig(){return {hide:[".dc04ec1d","._0fcaa63"]}}getCleanModeConfig(){return {hide:["._0fcaa63"]}}getScrollContainer(){const e=Array.from(document.querySelectorAll(mg)).filter(e=>!e.parentElement?.closest(mg)),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll(`${fg}, ${bg}`)).filter(e=>!e.closest(".gh-root, .gh-table-container"));return this.pickBestScrollableAncestor(n)}getResponseContainerSelector(){return 'main .ds-scroll-area:has(.ds-message), [role="main"] .ds-scroll-area:has(.ds-message), .ds-scroll-area:has(.ds-message)'}getUserQuerySelector(){return bg}findUserQueryElement(e,t){const n=this.getVisibleUserQueryElements();if(0===n.length)return null;if(e>0&&n.length>=e){const r=n[e-1];if(this.isEquivalentUserQueryText(this.extractUserQueryText(r),t))return r}return n.find(e=>this.isEquivalentUserQueryText(this.extractUserQueryText(e),t))||null}getChatContentSelectors(){return [fg,bg]}scrollToOutlineTarget(e){this.nativeOutlineRevealRequestId+=1,super.scrollToOutlineTarget(e);}extractUserQueryText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.findUserContentRoot(e);if(!t)return this.resolveUserMessageElement(e)?"":this.extractTextWithLineBreaks(e).trim();const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, .ds-icon-button, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractDeepSeekUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}extractAssistantResponseText(e){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const t=this.shouldIncludeThoughtsInExport(),n=this.resolveAssistantMessageElement(e),r=this.resolveAssistantBodyMarkdownElement(e),o=t&&n?this.extractThoughtBlockquotesFromMessage(n):[],i=r?this.extractMarkdownText(r):"";return t&&o.length>0?i?`${o.join("\n\n")}\n\n${i}`:o.join("\n\n"):i}extractOutline(e=6,t=false,n=false){const r=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!r)return [];const o=[],i=[],a=Array.from(r.querySelectorAll(mg)).filter(e=>!e.parentElement?.closest(mg));if(a.forEach((r,s)=>{const l=this.getAssistantBodyMarkdown(r);if(!l){if(!t)return;const e=this.extractUserQueryMarkdown(r);if(!e)return;let l;n&&(l=this.findNextAssistantMarkdown(a,s)?.textContent?.trim().length||0);const c=this.createUserQueryOutlineItem(e,r,l);return i.push(c),void o.push(c)}const c=Array.from(l.querySelectorAll("h1, h2, h3, h4, h5, h6"));c.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let s;if(n){let e=null;for(let t=r+1;t80;return {level:0,text:o?`${r.slice(0,80)}...`:r,element:t,isUserQuery:true,isTruncated:o,wordCount:n}}getExportConfig(){return this.exportSnapshotActive?{userQuerySelector:Eg,assistantResponseSelector:Tg,turnSelector:null,useShadowDOM:false}:{userQuerySelector:bg,assistantResponseSelector:fg,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.exportBundleCache=null,this.clearExportSnapshot();const t="markdown"===e.format&&"zip"===e.packaging?ia():void 0,n=await this.collectShareExportMessageSnapshots(t);if(n?.length)return t&&(this.exportBundleCache={messages:n,assets:t.assets}),this.mountExportSnapshot(n),{count:n.length};const r=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());if(!(r instanceof HTMLElement))return null;const o=await this.collectExportMessageSnapshots(r,t);return 0===o.length?null:(t&&(this.exportBundleCache={messages:o,assets:t.assets}),this.mountExportSnapshot(o),{count:o.length})}async extractExportBundle(e){return this.exportBundleCache}async restoreConversationAfterExport(e,t){this.clearExportSnapshot(),this.exportIncludeThoughtsOverride=null,this.exportBundleCache=null;}getLatestReplyText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=t.scrollTop,n=Math.max(0,t.scrollHeight-t.clientHeight);try{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}finally{t.scrollTop=e,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLatestReplyTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getLastCodeBlockText(){const e=this.exportIncludeThoughtsOverride;this.exportIncludeThoughtsOverride=false;const t=this.getScrollContainer()||document.querySelector(this.getResponseContainerSelector());try{if(t instanceof HTMLElement){const e=this.buildBottomUpScanPositions(t),n=t.scrollTop;try{for(const n of e){t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect();const e=this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(t));if(e)return e}}finally{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0}));}}return this.extractLastCodeBlockTextFromMessages(this.getVisibleAssistantMessages(document))}finally{this.exportIncludeThoughtsOverride=e;}}getSubmitButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d="${_g}"])`,`button.ds-icon-button:has(svg path[d="${_g}"])`]}findSubmitButton(e){const t=this.getSubmitButtonSelectors().join(", ");if(!t)return null;const n=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),r=new Set;for(const o of n){const e=o.querySelectorAll(t);for(const t of Array.from(e)){const e=t;if(!r.has(e)&&null!==e.offsetParent)return r.add(e),e}}return null}getNewChatButtonSelectors(){return ['a[href="/a/chat"]','a[href="/a/chat/"]']}getWidthSelectors(){return [{selector:":root",property:"--message-list-max-width",noCenter:true},{selector:".ds-virtual-list-items, .ds-virtual-list-visible-items",property:"--message-list-max-width",noCenter:true}]}getUserQueryWidthSelectors(){const e=["max-width: 100% !important;","min-width: 0 !important;","box-sizing: border-box !important;","margin-left: auto !important;","margin-right: 0 !important;","overflow-wrap: anywhere !important;","word-break: break-word !important;"].join(" ");return [{selector:vg,property:"width",extraCss:e,noCenter:true}]}isGenerating(){const e=this.findComposerButtons();for(const t of e){const e=t.querySelector("svg path");if((e?.getAttribute("d")||"").startsWith(Mg))return true}return false}getStopButtonSelectors(){return [`div[role="button"].ds-icon-button:has(svg path[d^="${Mg}"])`,`button.ds-icon-button:has(svg path[d^="${Mg}"])`]}getModelName(){const e=Array.from(document.querySelectorAll(".ds-toggle-button--selected")).map(e=>e.innerText?.trim()||e.textContent?.trim()||"").filter(Boolean);return 0===e.length?"DeepSeek":`DeepSeek (${e.join(", ")})`}getNetworkMonitorConfig(){return {urlPatterns:["/api/v0/chat/completion"],silenceThreshold:500}}async toggleTheme(e){try{const t="system"===e?"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e,n=JSON.stringify({value:e,__version:"0"});localStorage.setItem(gg,n);const r=document.body;return r&&(r.classList.remove("light","dark"),r.classList.add("change-theme",t),"dark"===t?r.setAttribute("data-ds-dark-theme","dark"):r.removeAttribute("data-ds-dark-theme"),r.style.colorScheme=t,window.setTimeout(()=>{document.body===r&&r.classList.remove("change-theme");},300)),window.dispatchEvent(new StorageEvent("storage",{key:gg,newValue:n,storageArea:localStorage})),!0}catch(t){return console.error("[DeepSeekAdapter] toggleTheme error:",t),false}}findComposerButtons(){const e=this.getTextareaElement(),t=[e?.closest("form"),e?.parentElement,e?.closest("div"),document.body].filter(Boolean),n=new Set,r=[];for(const o of t){const e=o.querySelectorAll('div[role="button"].ds-icon-button, button.ds-icon-button, .ds-icon-button[aria-disabled="false"]');for(const t of Array.from(e)){const e=t;null===e.offsetParent||n.has(e)||(n.add(e),r.push(e));}if(r.length>0)return r}return r}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(mg).length,i=e.querySelectorAll(bg).length,a=e.querySelectorAll(fg).length;let s=0;return s+=200*Math.min(o,80),s+=120*Math.min(i,40),s+=120*Math.min(a,40),e.scrollTop>0&&(s+=800),r.height>=.35*t&&(s+=500),r.width>=.45*n&&(s+=350),(e.matches("main, [role='main']")||e.closest("main, [role='main']"))&&(s+=250),e.querySelector("textarea")&&(s-=700),e.querySelector(".gh-table-container")&&(s-=250),s}extractNativeUserQueries(e){const t=this.collectNativeOutlineEntries();if(0===t.length)return [];const n=[],r=new Map;let o=0;return t.forEach(t=>{const i=this.findMatchingUserQueryIndex(e,t.text,o),a=i>=0?e[i]:null;i>=0&&(o=i+1);const s=this.createUserQueryOutlineItem(t.text,a?.element||null);s.wordCount=a?.wordCount;const l=this.normalizeUserQueryMatchText(t.text),c=r.get(l)||0;r.set(l,c+1),s.id=a?.id||`deepseek-user-query::${c}::${this.normalizeUserQueryMatchText(t.text)}`,n.push(s);}),n}mergeOutlineWithNativeUserQueries(e,t){if(!e.some(e=>e.isUserQuery))return [...t,...e];const n=[],r=[];let o=null,i=0;e.forEach(e=>{if(!e.isUserQuery)return void(o?o.assistantItems.push(e):n.push(e));const a=this.findMatchingNativeUserQueryIndex(t,e,i);a>=0?(o={type:"matched",nativeIndex:a,assistantItems:[]},i=a+1):o={type:"unmatched",userItem:e,assistantItems:[]},r.push(o);});const a=r.find(e=>"matched"===e.type);if(!a)return [...t,...e];const s=[];let l=0;if(n.length>0){const e=Math.max(a.nativeIndex-1,0);for(;l<=e&&l{if("matched"!==e.type)s.push(e.userItem,...e.assistantItems);else {for(;l<=e.nativeIndex&&l({...e})):[];const n=this.findNativeOutlineScrollContainer(t),r=this.getNativeOutlineSnapshot(e,t,n);if(this.nativeOutlineCache&&this.nativeOutlineCache.sessionId===e&&this.nativeOutlineCache.snapshot===r)return this.nativeOutlineCache.items.map(e=>({...e}));const o=this.scanNativeOutlineEntries(t,n);return o.length>0&&(this.nativeOutlineCache={sessionId:e,snapshot:r,items:o.map(e=>({...e}))}),o}findNativeOutlineList(){const e=Array.from(document.querySelectorAll(".ds-virtual-list")).filter(e=>e instanceof HTMLElement&&e.querySelector(".ds-virtual-list-items, .ds-virtual-list-visible-items")&&!e.querySelector(pg)&&!e.closest("aside, nav"));let t=null,n=-1;return e.forEach(e=>{const r=e.getBoundingClientRect();let o=0;e.closest('[style*="--scroll-nav-page-padding"]')&&(o+=2500),e.closest("main, [role='main']")&&(o+=600),e.querySelector(".ds-virtual-list-visible-items")&&(o+=400),r.width>=140&&r.width<=420&&(o+=350),r.height>=120&&(o+=250),e.scrollHeight>e.clientHeight+20&&(o+=300),e.querySelector(mg)&&(o-=1500),o>n&&(t=e,n=o);}),n>0?t:null}findNativeOutlineScrollContainer(e){const t=[e,e.closest(".ds-scroll-area"),e.parentElement,e.closest('[style*="--scroll-nav-page-padding"]')?.querySelector(".ds-scroll-area")].filter(e=>e instanceof HTMLElement);let n=null,r=-1;return t.forEach(t=>{const o=window.getComputedStyle(t);if(!(t.scrollHeight>t.clientHeight+8||"auto"===o.overflowY||"scroll"===o.overflowY||t.classList.contains("ds-virtual-list")||t.classList.contains("ds-scroll-area"))||t.clientHeight<=0)return;let i=0;t===e&&(i+=500),t.classList.contains("ds-virtual-list")&&(i+=350),t.classList.contains("ds-scroll-area")&&(i+=250),i+=Math.min(t.scrollHeight-t.clientHeight,2e3),i>r&&(n=t,r=i);}),r>0?n:null}getNativeOutlineSnapshot(e,t,n){const r=t.querySelector(".ds-virtual-list-items"),o=t.querySelector(".ds-virtual-list-visible-items"),i=n||t;return [e,i.scrollHeight,i.clientHeight,r?.scrollHeight||0,o?.childElementCount||0].join("::")}scanNativeOutlineEntries(e,t){const n=this.readVisibleNativeOutlineEntries(e);if(!t)return n;const r=Math.max(0,t.scrollHeight-t.clientHeight);if(r<=0)return n;const o=t.scrollTop,i=Math.max(48,Math.floor(.6*t.clientHeight)),a=new Set([0,r,o]);for(let l=0;le-t).forEach(n=>{t.scrollTop=n,t.dispatchEvent(new Event("scroll",{bubbles:!0})),t.getBoundingClientRect(),e.getBoundingClientRect();const r=this.readVisibleNativeOutlineEntries(e);s=this.mergeNativeOutlineEntryBatch(s,r,n);});}finally{t.scrollTop=o,t.dispatchEvent(new Event("scroll",{bubbles:true}));}return s}readVisibleNativeOutlineEntries(e){const t=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!t)return [];const n=[];return Array.from(t.children).forEach((e,t)=>{if(!(e instanceof HTMLElement))return;const r=this.extractNativeOutlineText(e);r&&n.push({text:r,batchIndex:t});}),n}extractNativeOutlineText(e){const t=Array.from(e.children).filter(e=>e instanceof HTMLElement);for(const n of t){const e=this.normalizeOutlineText(n.innerText||n.textContent||"");if(e)return e}return this.normalizeOutlineText(e.innerText||e.textContent||"")}mergeNativeOutlineEntryBatch(e,t,n){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e,scrollTop:e.scrollTop??n}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const o=e.slice(-r),i=t.slice(0,r);if(this.nativeOutlineEntrySequenceEquals(o,i))return [...e,...t.slice(r).map(e=>({...e,scrollTop:e.scrollTop??n}))]}return [...e,...t.map(e=>({...e,scrollTop:e.scrollTop??n}))]}nativeOutlineEntrySequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.nativeOutlineEntryEquals(e,t[n]))}nativeOutlineEntryEquals(e,t){return this.normalizeUserQueryMatchText(e.text)===this.normalizeUserQueryMatchText(t.text)}findMatchingUserQueryIndex(e,t,n){for(let r=n;r0&&t<=e.length?e[t-1]:e.find(e=>this.isEquivalentUserQueryText(e.text,n))||null}buildNativeOutlineJumpPositions(e,t,n,r,o){const i=Math.max(0,r.scrollHeight-r.clientHeight),a=e.length>1?Math.round(i*Math.max(n-1,0)/Math.max(e.length-1,1)):0,s=e.filter(e=>this.isEquivalentUserQueryText(e.text,o)).map(e=>e.scrollTop).filter(e=>"number"==typeof e),l=[t.scrollTop,a,a-.5*r.clientHeight,a+.5*r.clientHeight,...s,0,i],c=new Set;return l.map(e=>Math.max(0,Math.min(i,Math.round(e||0)))).filter(e=>!c.has(e)&&(c.add(e),true))}findVisibleNativeOutlineItem(e,t,n){const r=e.querySelector(".ds-virtual-list-visible-items")||e.querySelector(".ds-virtual-list-items");if(!r)return null;const o=Array.from(r.children).filter(e=>e instanceof HTMLElement);if("number"==typeof t.batchIndex&&t.batchIndex>=0&&t.batchIndexthis.isEquivalentUserQueryText(this.extractNativeOutlineText(e),n))||null}dispatchNativeOutlineClick(e){const t=e.querySelector('button, [role="button"], a')||e;t.dispatchEvent(new MouseEvent("mousedown",{bubbles:true,cancelable:true})),t.dispatchEvent(new MouseEvent("mouseup",{bubbles:true,cancelable:true})),t.click();}async waitForUserQueryElement(e,t,n){const r=Date.now();for(;Date.now()-r<3200;){if(n!==this.nativeOutlineRevealRequestId)return null;const r=this.findUserQueryElement(e,t);if(r)return r;await this.sleep(80);}return n!==this.nativeOutlineRevealRequestId?null:this.findUserQueryElement(e,t)}getVisibleUserQueryElements(){return Array.from(document.querySelectorAll(bg)).filter(e=>e instanceof HTMLElement&&!e.parentElement?.closest(mg))}sleep(e){return new Promise(t=>window.setTimeout(t,e))}isExportSnapshotElement(e){return e.hasAttribute(Sg)}async collectShareExportMessageSnapshots(e){if(!this.isSharePage())return null;const t=this.getSessionId();if(!t)return null;try{const n=await fetch(`/api/v0/share/content?share_id=${encodeURIComponent(t)}`,{credentials:"include"});if(!n.ok)return null;const r=await n.json(),o=this.extractShareExportMessagesFromPayload(r,e);return o.length>0?o:null}catch(n){return console.warn("[DeepSeekAdapter] Failed to collect share export payload:",n),null}}extractShareExportMessagesFromPayload(e,t){const n=this.getNestedRecord(e,["data","biz_data"]),r=n?.messages;if(!Array.isArray(r))return [];const o=[];return r.forEach(e=>{const n=this.toRecord(e);if(!n)return;const r="string"==typeof n.role?n.role.toUpperCase():"",i=Array.isArray(n.fragments)?n.fragments:[];if("USER"===r){const e=[],n=[];i.forEach(t=>{const r=this.toRecord(t);if(!r)return;const o="string"==typeof r.type?r.type.toUpperCase():"";"FILE"!==o?"REQUEST"===o&&"string"==typeof r.content&&n.push(r.content):e.push(...this.extractShareUserAttachments(r));});const r=this.normalizeExportMessageContent(this.formatUserQueryExportContent(n.join("\n\n"),e,t));return void(r&&o.push({role:Cg,content:r}))}if("ASSISTANT"===r){const e=[],t=[];i.forEach(n=>{const r=this.toRecord(n);if(!r||"string"!=typeof r.content)return;const o="string"==typeof r.type?r.type.toUpperCase():"";"THINK"===o?t.push(r.content):"RESPONSE"===o&&e.push(r.content);});const n=this.shouldIncludeThoughtsInExport()?t.map(e=>e.trim()).filter(Boolean).map(e=>this.formatAsThoughtBlockquote(e)):[],r=this.normalizeExportMessageContent([...n,...e.map(e=>e.trim()).filter(Boolean)].filter(Boolean).join("\n\n"));r&&o.push({role:Ag,content:r});}}),o}extractShareUserAttachments(e){return (Array.isArray(e.files)?e.files:[]).flatMap(e=>{const t=this.toRecord(e);if(!t)return [];const n="string"==typeof t.file_name?t.file_name.trim():"";if(!n)return [];const r="string"==typeof t.signed_path?t.signed_path.trim():"",o="number"==typeof t.file_size?this.formatFileSize(t.file_size):"";return [{kind:true===t.is_image?"image":"file",name:n,type:this.extractFileTypeFromName(n),size:o,source:r?fa(r):""}]})}getNestedRecord(e,t){let n=this.toRecord(e);for(const r of t){if(!n)return null;n=this.toRecord(n[r]);}return n}toRecord(e){return e&&"object"==typeof e?e:null}extractDeepSeekUserQueryExportContent(e,t){if(this.isExportSnapshotElement(e))return e.textContent?.trim()||"";const n=this.extractDomUserAttachments(e),r=this.extractUserQueryText(e);return this.formatUserQueryExportContent(r,n,t)}resolveUserMessageElement(e){if(e.matches(bg))return e;const t=e.closest(bg);return t instanceof HTMLElement?t:null}extractDomUserAttachments(e){const t=this.resolveUserMessageElement(e);if(!t)return [];const n=[],r=new Set;return this.extractDomUserImageAttachments(t).forEach(e=>{const t=`image:${e.source||e.name}`;r.has(t)||(r.add(t),n.push(e));}),this.extractDomUserFileAttachments(t).forEach(e=>{const t=`file:${e.source||e.name}:${e.type}:${e.size}`;r.has(t)||(r.add(t),n.push(e));}),n}extractDomUserImageAttachments(e){return Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&!e.closest(".gh-user-query-markdown")).flatMap(e=>{const t=this.getDeepSeekImageExportSource(e);if(!t)return [];const n=this.extractImageAttachmentName(e,t);return [{kind:"image",name:n,type:this.extractFileTypeFromName(n)||"image",size:"",source:t}]})}extractDomUserFileAttachments(e){return Array.from(e.querySelectorAll("div")).filter(t=>this.isLikelyUserFileAttachmentCard(t,e)).flatMap(e=>{const t=this.extractAttachmentCardName(e);if(!t)return [];const n=this.extractAttachmentCardSource(e),r=this.extractAttachmentCardType(e,t)||this.extractFileTypeFromName(t);return [{kind:this.isImageAttachmentName(t,r)?"image":"file",name:t,type:r,size:this.extractAttachmentCardSize(e),source:n}]})}formatUserQueryExportContent(e,t,n){const r=this.stripUserAttachmentBodyText(e,t);if(0===t.length)return r;const o=this.formatUserImageAttachments(t,n),i=this.formatUserFileAttachments(t,n),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,r].filter(Boolean).join("\n\n")}formatUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"image"!==e.kind||!e.source,getLabel:e=>this.formatAttachmentLabel(e)})}formatAttachmentLabel(e){const t=this.formatAttachmentDetails(e);return t?`${e.name} (${t})`:e.name}formatAttachmentDetails(e){return [e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?e.type:"",e.size].filter(Boolean).join(", ")}getDeepSeekImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=fa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&ba(e)))return e}return ""}extractImageAttachmentName(e,t){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractFilenameFromUrl(t),"uploaded image"].map(e=>this.normalizeAttachmentText(e)).find(Boolean)||"image"}isLikelyUserFileAttachmentCard(e,t){if(e===t)return false;if(e.closest(".gh-user-query-markdown"))return false;if(!this.isWithinUserAttachmentContainer(e,t))return false;if(!e.querySelector("svg")||e.querySelector("img"))return false;const n=this.extractAttachmentCardName(e);if(!n)return false;return this.normalizeAttachmentText(e.textContent||"")!==n}isWithinUserAttachmentContainer(e,t){let n=e;for(;n&&n!==t;){if(n.parentElement===t)return this.isLikelyUserAttachmentContainer(n);n=n.parentElement;}return false}isLikelyUserAttachmentContainer(e){if(e.matches(".gh-inline-bookmark, .gh-user-query-raw, .gh-user-query-markdown"))return false;if(e.matches("button, [role=button], .ds-icon-button, .ds-focus-ring"))return false;if(e.querySelector("img"))return true;return !!this.normalizeAttachmentText(e.textContent||"")&&(!!e.querySelector("svg")&&""!==this.extractAttachmentCardName(e))}stripUserAttachmentBodyText(e,t){return e&&0!==t.length?e.replace(/\r\n/g,"\n").split("\n").filter(e=>!this.isUserAttachmentBodyLine(e,t)).join("\n").trim():e}isUserAttachmentBodyLine(e,t){const n=this.normalizeAttachmentComparisonText(e);return !!n&&t.some(e=>{const t=this.normalizeAttachmentComparisonText(e.name);if(!t||!n.includes(t))return false;const r=this.normalizeAttachmentComparisonText(e.size);if(r&&n.includes(r))return true;const o=e.type&&!this.fileNameEndsWithExtension(e.name,e.type)?this.normalizeAttachmentComparisonText(e.type):"";return !(!o||!n.includes(o))||n===t})}extractAttachmentCardName(e){const t=Array.from(e.querySelectorAll("div, span, p")).filter(e=>!e.querySelector("svg, img")),n=[...t.filter(e=>0===e.children.length).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean),...t.map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean)].find(e=>this.looksLikeFilename(e));if(n)return n;const r=this.normalizeAttachmentText(e.getAttribute("aria-label")||"");if(this.looksLikeFilename(r))return r;const o=this.normalizeAttachmentText(e.getAttribute("title")||"");return this.looksLikeFilename(o)?o:""}extractAttachmentCardType(e,t=""){const n=this.normalizeAttachmentText(t).toLowerCase(),r=Array.from(e.querySelectorAll("div, span, p")).map(e=>this.normalizeAttachmentText(e.textContent||"")).filter(Boolean).find(e=>(!n||!e.toLowerCase().includes(n))&&!this.looksLikeFilename(e)&&/^[A-Za-z0-9.+-]{1,12}(?:\s+\d+(?:\.\d+)?\s*[KMGT]?B)?$/i.test(e));return r?.match(/^[A-Za-z0-9.+-]{1,12}/)?.[0]?.toUpperCase()||""}extractAttachmentCardSize(e){const t=this.normalizeAttachmentText(e.textContent||"");return t.match(/\b\d+(?:\.\d+)?\s*[KMGT]?B\b/i)?.[0]||""}extractAttachmentCardSource(e){const t=Array.from(e.querySelectorAll("a[href]")),n=e.closest("a[href]");n&&t.unshift(n);for(const r of t){if(!(r instanceof HTMLAnchorElement))continue;const e=fa(r.getAttribute("href")||r.href||"");if(ba(e))return e}return ""}looksLikeFilename(e){const t=this.normalizeAttachmentText(e);return !this.isFileMetaText(t)&&/[^/\\]+\.[A-Za-z0-9]{1,10}$/.test(t)}isFileMetaText(e){return /^[A-Za-z0-9.+-]{1,12}\s+\d+(?:\.\d+)?\s*[KMGT]?B$/i.test(e)}isImageAttachmentName(e,t){const n=(this.extractFileTypeFromName(e)||t).toLowerCase();return ["avif","gif","jpg","jpeg","png","svg","webp"].includes(n)}extractFileTypeFromName(e){return e.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]?.toUpperCase()||""}formatFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?0:2;return `${n.toFixed(o)}${t[r]}`}extractFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename")||t.searchParams.get("file_name");if(n?.trim())return n.trim();const r=decodeURIComponent(t.pathname);return r.split("/").pop()?.trim()||""}catch{return ""}}normalizeAttachmentText(e){return e.replace(/\s+/g," ").trim()}normalizeAttachmentComparisonText(e){return this.normalizeAttachmentText(e).toLowerCase().replace(/[(]/g,"(").replace(/[)]/g,")").replace(/\s+/g,"")}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}async collectExportMessageSnapshots(e,t){const n=this.buildExportSnapshotPositions(e),r=e.scrollTop;let o=[];try{for(const r of n){e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:!0})),e.getBoundingClientRect(),await this.sleep(80);const n=this.readVisibleExportMessageSnapshots(e,t);o=this.mergeExportMessageBatch(o,n);}}finally{e.scrollTop=r,e.dispatchEvent(new Event("scroll",{bubbles:true}));}return o}buildExportSnapshotPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight),n=e.scrollTop;if(t<=0)return [n];const r=Math.max(160,Math.floor(.75*e.clientHeight)),o=new Set([0,n,t]);for(let i=0;ie-t)}buildBottomUpScanPositions(e){const t=Math.max(0,e.scrollHeight-e.clientHeight);if(t<=0)return [e.scrollTop];const n=Math.max(160,Math.floor(.9*e.clientHeight)),r=[];for(let o=t;o>0;o-=n)r.push(o);return 0!==r[r.length-1]&&r.push(0),r}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}resolveAssistantMessageElement(e){if(e.matches(mg))return e;const t=e.closest(mg);return t instanceof HTMLElement?t:null}resolveAssistantBodyMarkdownElement(e){if(e.matches(".ds-markdown")&&!this.isThoughtMarkdownElement(e))return e;const t=this.resolveAssistantMessageElement(e);return t?this.getAssistantBodyMarkdown(t):null}getAssistantBodyMarkdown(e){const t=Array.from(e.querySelectorAll(".ds-markdown")).filter(e=>e instanceof HTMLElement&&!this.isThoughtMarkdownElement(e));return t.length>0?t[t.length-1]:null}isThoughtMarkdownElement(e){return null!==e.closest(yg)}extractThoughtBlockquotesFromMessage(e){const t=Array.from(e.querySelectorAll(`${yg} .ds-markdown`)).filter(e=>e instanceof HTMLElement),n=[];return t.forEach(e=>{const t=this.extractMarkdownText(e);t&&n.push(this.formatAsThoughtBlockquote(t));}),n}extractMarkdownText(e){const t=e.cloneNode(true);t.querySelectorAll('button, [role="button"], svg, .ds-icon-button, .ds-focus-ring, [aria-hidden="true"]').forEach(e=>e.remove());const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}getVisibleAssistantMessages(e){return Array.from(e.querySelectorAll(fg)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${kg}]`)&&!e.closest(".gh-root")&&!e.parentElement?.closest(mg))}extractLatestReplyTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=this.extractAssistantResponseText(e[t]).trim();if(n)return n}return null}extractLastCodeBlockTextFromMessages(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=this.getAssistantBodyMarkdown(n);if(!r)continue;const o=this.extractAssistantResponseText(n),i=this.extractLastFencedCodeBlock(o);if(i)return i;const a=this.extractLastCodeBlockTextFromDom(r);if(a)return a}return null}extractLastFencedCodeBlock(e){if(!e)return null;const t=/```[^\n]*\n([\s\S]*?)```/g;let n=null;for(const r of e.matchAll(t))n=r[1]||null;return n&&n.trim()?n.replace(/\r\n/g,"\n").replace(/\n+$/,""):null}extractLastCodeBlockTextFromDom(e){const t=Array.from(e.querySelectorAll("pre code, pre"));for(let n=t.length-1;n>=0;n-=1){const e=t[n];if(!(e instanceof HTMLElement))continue;const r=e.cloneNode(true);r.querySelectorAll('button, [role="button"], svg, .ds-icon-button, [aria-hidden="true"]').forEach(e=>e.remove());const o=r.textContent?.replace(/\r\n/g,"\n").replace(/\n+$/,"")||"";if(o.trim())return o}return null}readVisibleExportMessageSnapshots(e,t){return Array.from(e.querySelectorAll(mg)).filter(e=>e instanceof HTMLElement&&!e.closest(`[${kg}]`)&&!e.parentElement?.closest(mg)).map(e=>this.extractExportMessageSnapshot(e,t)).filter(e=>null!==e)}extractExportMessageSnapshot(e,t){if(this.getAssistantBodyMarkdown(e)){const t=this.normalizeExportMessageContent(this.extractAssistantResponseText(e));return t?{role:Ag,content:t}:null}const n=this.normalizeExportMessageContent(this.extractDeepSeekUserQueryExportContent(e,t));return n?{role:Cg,content:n}:null}normalizeExportMessageContent(e){return e.replace(/\r\n/g,"\n").replace(/\u00a0/g," ").trim()}mergeExportMessageBatch(e,t){if(0===t.length)return e;if(0===e.length)return t.map(e=>({...e}));for(let r=Math.min(e.length,t.length);r>0;r-=1){const n=e.slice(-r),o=t.slice(0,r);if(this.exportMessageSequenceEquals(n,o))return [...e,...t.slice(r).map(e=>({...e}))]}const n=e.map(e=>({...e}));return t.forEach(e=>{this.exportMessageEntryEquals(n[n.length-1],e)||n.push({...e});}),n}exportMessageSequenceEquals(e,t){return e.length===t.length&&e.every((e,n)=>this.exportMessageEntryEquals(e,t[n]))}exportMessageEntryEquals(e,t){return !(!e||!t)&&(e.role===t.role&&e.content===t.content)}mountExportSnapshot(e){this.clearExportSnapshot();const t=document.createElement("div");t.setAttribute(kg,"1"),t.style.display="none",e.forEach(e=>{const n=document.createElement("div");n.setAttribute(Sg,e.role),n.textContent=e.content,t.appendChild(n);}),document.body.appendChild(t),this.exportSnapshotRoot=t,this.exportSnapshotActive=true;}clearExportSnapshot(){this.exportSnapshotActive=false;const e=this.exportSnapshotRoot;this.exportSnapshotRoot=null,e?.isConnected&&e.remove(),document.querySelectorAll(`[${kg}]`).forEach(t=>{t!==e&&t.parentNode?.removeChild(t);});}async deleteConversationViaApi(e,t){try{const n=await fetch("/api/v0/chat_session/delete",{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_session_id:e.id}),credentials:"include"});if(!n.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(n.status)};const r=await this.safeParseJson(n);return this.isDeleteSuccessPayload(r)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(r)}}catch{return {id:e.id,success:false,method:"api",reason:Lg}}}buildDeleteHeaders(e){return {accept:"*/*",authorization:`Bearer ${e}`,"content-type":"application/json","x-client-platform":"web","x-client-locale":this.getClientLocale(),"x-client-timezone-offset":String(60*-(new Date).getTimezoneOffset())}}getUserToken(){const e=localStorage.getItem("userToken");if(!e)return null;try{const t=JSON.parse(e).value;if("string"==typeof t&&t.trim())return t.trim()}catch{}return e.trim().replace(/^"|"$/g,"")||null}getClientLocale(){return (document.documentElement.lang||navigator.language||"en-US").replace(/-/g,"_")}isDeleteSuccessPayload(e){if(!e||"object"!=typeof e)return false;const t=e;if(0!==t.code)return false;const n=t.data;if(!n||"object"!=typeof n)return true;const r=n.biz_code;return void 0===r||0===r}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return Ng;const t=e;if("string"==typeof t.msg&&t.msg.trim())return `${Dg}:${t.msg.trim()}`;const n=t.data;if(n&&"object"==typeof n){const e=n;if("string"==typeof e.biz_msg&&e.biz_msg.trim())return `${Dg}:${e.biz_msg.trim()}`}return Dg}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleHomeRefreshAfterDelete(){try{sessionStorage.setItem(xg,"1");}catch{}window.location.replace(wg);}schedulePageReloadAfterDelete(){window.setTimeout(()=>{window.location.reload();},0);}consumePendingDeleteRefresh(){let e=false;try{if(e="1"===sessionStorage.getItem(xg),!e)return;sessionStorage.removeItem(xg);}catch{return}if("/"===window.location.pathname||""===window.location.pathname)setTimeout(()=>{window.location.reload();},0);else {try{sessionStorage.setItem(xg,"1");}catch{}window.location.replace(wg);}}findNextAssistantMarkdown(e,t){for(let n=t+1;n!e.parentElement?.closest(mg)),t=e?this.extractUserQueryText(e):"",n=this.normalizeOutlineText(t);if(n)return n.length>80?`${n.slice(0,80)}...`:n;const r=document.querySelector('meta[property="og:title"], meta[name="twitter:title"]')?.getAttribute("content")?.replace(/\s*[-|]\s*DeepSeek$/i,"")?.trim();return r&&"来自分享的对话"!==r?r:r||"DeepSeek Share"}isPinnedConversationLink(e){const t=this.findConversationGroup(e);if(!t)return false;const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(0===r.length)return false;const o=r[0],i=n.indexOf(o);if(i<=0)return false;const a=n.find((e,t)=>t0,l=null!==a.querySelector(":scope > .ds-focus-ring, .ds-focus-ring"),c=null!==a.querySelector(":scope > span, span");return s&&l&&c}findConversationGroup(e){let t=e.parentElement;for(;t&&t!==document.body;){const n=Array.from(t.children),r=n.filter(e=>this.isConversationLink(e));if(r.length>0){const o=n.indexOf(r[0]);if(n.some((e,t)=>tt===e))return t}t=t.parentElement;}return null}isConversationLink(e){return e.matches(pg)}extractConversationTitle(e){const t=e.getAttribute("aria-label")?.trim();if(t)return t;const n=this.findTitleElement(e),r=n?.innerText?.trim()||n?.textContent?.trim()||"";if(r)return r.replace(/\s+/g," ").trim();return (e.innerText?.trim()||e.textContent?.trim()||"").replace(/\s+/g," ").trim()}findTitleElement(e){const t=Array.from(e.children).find(e=>e instanceof HTMLElement&&(!e.classList.contains("ds-focus-ring")&&(!e.querySelector('[role="button"], .ds-icon-button')&&!!e.innerText?.trim())));if(t)return t;const n=e.querySelectorAll("span, p, div");for(const r of Array.from(n)){if(r.innerText?.trim()||r.textContent?.trim()||"")return r}return e}findUserContentRoot(e){const t=this.resolveUserMessageElement(e);if(!t)return null;return Array.from(t.children).filter(e=>e instanceof HTMLElement&&(!this.isLikelyUserMessageDecoration(e)&&(!this.isLikelyUserAttachmentContainer(e)&&Boolean(e.innerText?.trim()))))[0]||null}isLikelyUserMessageDecoration(e){return e.matches(".gh-inline-bookmark, .gh-user-query-raw, .gh-user-query-markdown, button, [role=button], .ds-icon-button, .ds-focus-ring")}},new class extends gs{outlineCacheSessionKey="";outlineCacheTransitionEndAt=0;outlineItemCache=new Map;match(){return "www.doubao.com"===window.location.hostname}getSiteId(){return mo}getName(){return "豆包"}getThemeColors(){return {primary:"#315efb",secondary:"#0f6eff"}}supportsHostThemeSync(){return false}getTextareaSelectors(){return ['[data-slate-editor="true"]','textarea[data-testid="chat_input_input"]',"textarea.semi-input-textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length);}else if(t.isContentEditable){const n=window.getSelection();if(n){t.focus(),n.selectAllChildren(t),n.collapseToEnd();const e=t.querySelector('[data-slate-node="element"]');if(e&&n.rangeCount>0){const t=document.createRange();t.selectNodeContents(e),t.collapse(false),n.removeAllRanges(),n.addRange(t);}}const r=new DataTransfer;r.setData("text/plain",e),t.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:true,cancelable:true,composed:true}));}return true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected)if(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true}));}else e.isContentEditable&&(e.focus(),document.execCommand("selectAll",false),e.dispatchEvent(new KeyboardEvent("keydown",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})),document.execCommand("delete",false),e.dispatchEvent(new InputEvent("input",{inputType:"deleteContentBackward",bubbles:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Backspace",code:"Backspace",keyCode:8,bubbles:true,composed:true})));}extractConversationId(e){const t=e.id.match(/^conversation_(.+)$/)?.[1];if(t)return t;const n=(e.getAttribute("href")||"").match(qg);return n?.[1]||null}extractConversationTitle(e){const t=e.querySelector(Bg)||Array.from(e.querySelectorAll("span")).find(e=>e.textContent?.trim())||null;return t?.textContent?.trim()||""}getConversationRows(e=document){return Array.from(e.querySelectorAll(zg))}getHistoryContainer(){return document.querySelector(Pg)}findScrollableAncestor(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t),n=e.overflowY,r=e.overflow;if(("auto"===n||"scroll"===n||"overlay"===n||"auto"===r||"scroll"===r||"overlay"===r)&&t.clientHeight>0)return t;t=t.parentElement;}return null}getActiveConversationRow(){const e=this.getSessionId(),t=this.getConversationRows();return t.find(e=>"page"===e.getAttribute("aria-current"))||t.find(e=>e.className.includes("active-link-")||e.className.includes("e2e-test-active"))||t.find(t=>this.extractConversationId(t)===e)||null}getVirtualScrollContainer(){return Array.from(document.querySelectorAll(Fg)).find(e=>{if(!e.isConnected)return false;if(!(e.querySelector('[data-name="scroll_holder"]')||e.querySelector($g)||e.querySelector(Ug)))return false;const t=window.getComputedStyle(e);return ("auto"===t.overflowY||"scroll"===t.overflowY||"auto"===t.overflow||"scroll"===t.overflow||e.scrollHeight>e.clientHeight)&&e.clientHeight>0})||null}getSharePageMessageContainer(){if(!this.isSharePage())return null;const e=document.querySelector('[class*="message-list-root-"]');if(e)return this.findScrollableAncestor(e)||e;const t=document.querySelector(`${jg}, ${Gg}`);return t?this.findScrollableAncestor(t)||t.parentElement||t:null}getOutlineContentContainer(){return this.getVirtualScrollContainer()||this.getSharePageMessageContainer()}getAssistantContentRoots(e){const t=[];return e instanceof HTMLElement&&e.matches(Vg)&&t.push(e),Array.from(e.querySelectorAll(Vg)).forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);}),t}getAssistantContentRoot(e){return e.matches(Vg)?e:e.querySelector(Vg)||e}getConversationTitle(){const e=this.getActiveConversationRow();return e&&this.extractConversationTitle(e)||null}getSessionId(){const e=window.location.pathname.match(qg),t=e?.[1]||"";return t&&"new"!==t?t:""}isNewConversation(){return /^(?:\/code)?\/chat\/(new\/?)?$/.test(window.location.pathname)}isSharePage(){return window.location.pathname.startsWith("/thread/")}getNewTabUrl(){return `https://www.doubao.com${window.location.pathname.startsWith("/code/")?"/code":""}/chat/`}supportsNewTab(){return true}getConversationList(){const e=this.getConversationRows();if(!e.length)return [];const t=new Map;return e.forEach(e=>{const n=e,r=this.extractConversationId(n);if(!r||"new"===r)return;const o=this.extractConversationTitle(n),i="page"===n.getAttribute("aria-current")||n.className.includes("active-link-")||n.className.includes("e2e-test-active"),a=!!n.querySelector('[class*="pin-"]');t.set(r,{id:r,title:o,url:`https://www.doubao.com/chat/${r}`,isActive:i,isPinned:a});}),Array.from(t.values())}navigateToConversation(e,t){const n=document.querySelector(`#conversation_${e}, ${zg}[href*="/chat/${e}"]`);return n?(n.click(),true):(window.location.href=t||`https://www.doubao.com/chat/${e}`,true)}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!e)return;let t=0,n=0;for(;n<3;){e.scrollTop=e.scrollHeight,await new Promise(e=>setTimeout(e,500));const r=e.querySelectorAll(zg).length;r===t?n++:(t=r,n=0);}}getSidebarScrollContainer(){const e=this.getHistoryContainer();return this.findScrollableAncestor(e)||e}getZenModeConfig(){return {hide:["nav",".container-qOgFQp"]}}getCleanModeConfig(){return {hide:[".container-qOgFQp",'[aria-label="活动入口"]']}}getConversationObserverConfig(){return {selector:zg,shadow:false,extractInfo:e=>{const t=e,n=this.extractConversationId(t);if(!n||"new"===n)return null;return {id:n,title:this.extractConversationTitle(t),url:`https://www.doubao.com/chat/${n}`,isActive:"page"===t.getAttribute("aria-current")||t.className.includes("active-link-")||t.className.includes("e2e-test-active"),isPinned:!!t.querySelector('[class*="pin-"]')}},getTitleElement:e=>e.querySelector(Bg)||Array.from(e.querySelectorAll("span")).find(e=>e.textContent?.trim())||null}}async deleteConversationOnSite(e){const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Xg}}async deleteConversationsOnSite(e){const t=[];for(let n=0;ne.remove());const n=Fi(t).trim();return n||this.extractTextWithLineBreaks(t).trim()}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantResponseTextWithAssets(e,t,n){return [this.extractAssistantMarkdown(e),this.formatDoubaoAssistantImages(this.extractDoubaoAssistantImages(e,n),t).join("\n\n")].filter(Boolean).join("\n\n")}getLatestReplyText(){const e=document.querySelectorAll(Gg);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantMarkdown(t)||null}getUserMessageTextContainer(e){return e.matches(Hg)?e:e.matches(jg)?e.querySelector(Hg):e.querySelector(Wg)||e.querySelector(Hg)}extractUserQueryText(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryMarkdown(e){const t=this.getUserMessageTextContainer(e);return t?this.extractTextWithLineBreaks(t).trim():""}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}extractUserQueryExportContentWithAssets(e,t){const n=this.getUserMessageTextContainer(e),r=n?.textContent?.trim()||""||(n?this.extractUserQueryText(n):""),o=this.extractDoubaoUserAttachments(e);if(0===o.length)return r||this.extractUserQueryText(e);const i=this.formatDoubaoUserImageAttachments(o,t),a=this.formatDoubaoUserFileAttachments(o,t),s=a.length>0?`${se("exportAttachmentsLabel")}:\n${a.join("\n")}`:"";return [i.join("\n\n"),s,r].filter(Boolean).join("\n\n")}extractDoubaoUserAttachments(e){const t=Array.from(e.querySelectorAll('[data-plugin-identifier="block_type:10052"] [data-available="true"]')),n=[],r=new Set;return t.forEach(e=>{const t=this.extractDoubaoUserAttachment(e);if(!t)return;const o=`${t.kind}:${t.source||t.name}:${t.type}`;r.has(o)||(r.add(o),n.push(t));}),n}extractDoubaoUserAttachment(e){const t=this.extractDoubaoDownloadableSource(e),n=this.extractDoubaoCleanTextParts(e),{name:r,type:o}=this.parseDoubaoAttachmentLabel(n);if(!r&&!t)return null;const i=r||"attachment";return {kind:this.isDoubaoImageAttachment(i,o,t)?"image":"file",name:i,source:t,type:o}}parseDoubaoAttachmentLabel(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=["image","图片","圖像","图像","file","文件","附件","document","文档","音频","视频"];let r="",o=t;const i=t[t.length-1]||"";n.some(e=>e.toLowerCase()===i.toLowerCase())&&(r=i,o=t.slice(0,-1));let a=o.join(" ").trim();if(!a&&t.length>0){const e=t.join(" ").trim(),o=n.find(t=>e.toLowerCase().endsWith(t.toLowerCase()));o&&e.length>o.length?(r=o,a=e.slice(0,-o.length).trim()):a=e;}return {name:a,type:r}}extractDoubaoCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}const i=n.join("");return n.length<=1&&i?[i]:n}isDoubaoImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}formatDoubaoUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatDoubaoUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),includeAttachment:e=>"file"===e.kind||!e.source,getLabel:e=>e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?e.name:`${e.name} (${e.type})`:e.name})}formatDoubaoAssistantImages(e,t){return Ma(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractDoubaoAssistantImages(e,t){const n=[],r=new Set,o=(e,o)=>{const i=this.normalizeDoubaoImageSource(e);i&&!r.has(i)&&(r.add(i),t?.usedSources.add(i),n.push({source:i,alt:o||`generated image ${n.length+1}`}));};Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement).forEach(e=>{const t=this.extractDoubaoImageSource(e);if(!t)return;const n=(e.alt||e.getAttribute("aria-label")||"generated image").replace(/\s+/g," ").trim();o(t,n);});const i=this.countDoubaoGeneratedImageSlots(e);for(;t&&n.length0)return t}return t.reduce((e,t)=>{const n=t.querySelectorAll('[class*="image-box-grid-item"]').length;if(n>0)return e+n;const r=t.querySelectorAll('[class*="image-wrapper"]').length;return r>0?e+r:e+t.querySelectorAll("img").length},0)}extractDoubaoImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",...this.extractDoubaoSrcsetCandidates(e.getAttribute("srcset")||""),...Array.from(e.closest("picture")?.querySelectorAll("source")||[]).flatMap(e=>this.extractDoubaoSrcsetCandidates(e.getAttribute("srcset")||e.getAttribute("src")||""))];for(const n of t){const e=this.normalizeDoubaoImageSource(n);if(e)return e}return ""}extractDoubaoSrcsetCandidates(e){return e?e.split(",").map(e=>e.trim().split(/\s+/)[0]||"").filter(Boolean):[]}normalizeDoubaoImageSource(e){const t=fa(e);return t?/^data:image\/svg\+xml/i.test(t)?"":/^data:image\//i.test(t)||ba(t)?t:"":""}extractDoubaoDownloadableSource(e){const t=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&t.push(e.href||e.getAttribute("href")||""),e instanceof HTMLImageElement&&t.push(this.extractDoubaoImageSource(e)),Jg.forEach(n=>{t.push(e.getAttribute(n)||"");});});for(const n of t){const e=fa(n);if(!/^data:image\/svg\+xml/i.test(e)&&(this.normalizeDoubaoImageSource(e)||ba(e)))return e}return ""}createDoubaoAssistantImageFallbackState(){return {sources:this.getDoubaoPerformanceImageSources(),nextIndex:0,usedSources:new Set}}takeNextDoubaoFallbackImageSource(e){for(;e.nextIndex{const r=this.normalizeDoubaoImageSource(n.name);if(r&&!t.has(r)){try{const e=new URL(r);if(!(/(^|\.)byteimg\.com$/i.test(e.hostname)&&(/\/rc_gen_image\//i.test(e.pathname)||/flow-imagex-sign/i.test(e.hostname))))return}catch{return}t.add(r),e.push(r);}}),e}replaceUserQueryContent(e,t){const n=this.getUserMessageTextContainer(e);if(!n)return false;if(n.nextElementSibling?.classList.contains("gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}findModelSelectorButton(){const e=document.querySelectorAll('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]');for(const t of e){const e=t;if(null!==e.offsetParent){const t=e.querySelector(".truncate");if(t&&t.textContent?.trim())return e}}return null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:['button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'],menuItemSelector:'div[role="menuitem"][data-slot="dropdown-menu-item"]',menuRenderDelay:100}}getModelName(){const e=this.findModelSelectorButton();if(!e)return null;const t=e.innerText?.trim();return t?t.split("\n")[0].trim():null}clickModelSelector(){const e=this.findModelSelectorButton();return !!e&&(this.simulateClick(e),true)}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,t.width-1)),r=t.top+Math.max(1,Math.min(t.height/2,t.height-1)),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r};e.dispatchEvent(new PointerEvent("pointerenter",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new PointerEvent("pointerover",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new PointerEvent("pointerdown",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mousedown",o)),e.dispatchEvent(new PointerEvent("pointerup",{...o,pointerId:1,pointerType:"mouse",isPrimary:true})),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}async deleteConversationViaUi(e){const t=await this.findConversationRowWithRetry(e);if(!t)return false;if(!(await this.openConversationMenu(t,e)))return false;const n=await this.waitForDeleteMenuItem(2500);if(!n)return false;this.simulateClick(n);const r=await this.waitForDeleteConfirmButton(2500);return r&&this.simulateClick(r),this.waitForConversationRemoved(e,7e3)}async findConversationRowWithRetry(e){const t=this.findConversationRow(e);return t||(await this.loadAllConversations(),await this.sleep(200),this.findConversationRow(e))}findConversationRow(e){return document.querySelector(`#conversation_${e}`)}getConversationMenuButtons(e){const t=[],n=[],r=new Set,o=e=>{e&&(r.has(e)||(r.add(e),this.isVisible(e)?t.push(e):n.push(e)));},i=e.querySelector('[class*="chat-item-menu-wrapper-"]');if(!i)return [];const a=i.querySelector('button[data-slot="dropdown-menu-trigger"][aria-haspopup="menu"]'),s=i.querySelector('button[data-dbx-name="button"]'),l=i.querySelector('button[aria-haspopup="menu"]');return o(a),o(s),o(l),[...t,...n]}async openConversationMenu(e,t){for(let n=0;n<10;n+=1){e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:true})),e.dispatchEvent(new MouseEvent("mousemove",{bubbles:true}));const t=this.getConversationMenuButtons(e);if(0!==t.length){for(const n of t){document.body.click(),await this.sleep(50);if(await this.tryActivateConversationAction(e,n))return true}await this.sleep(100);}else await this.sleep(80);}return false}async waitForDeleteMenuItem(e=2500){const t=Date.now();for(;Date.now()-tthis.isVisible(e));if(e)return e;return Array.from(document.querySelectorAll('[role="dialog"][aria-modal="true"], [role="dialog"]')).find(e=>{if(!this.isVisible(e))return false;const t=this.getSignalText(e);return t.includes("删除")||t.includes("刪除")||t.includes("delete")})||null}async waitForConversationRemoved(e,t=3500){const n=Date.now();for(;Date.now()-nthis.isVisible(e)))return true;await this.sleep(50);}return false}getSignalText(e){return [e.textContent||"",e.getAttribute("aria-label")||"",e.getAttribute("title")||"",e.className||""].join(" ").toLowerCase()}isVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}async sleep(e){await new Promise(t=>setTimeout(t,e));}getOutlineCacheSessionKey(){return `${this.getCurrentCid()||"default"}:${this.getSessionId()||"default"}:${window.location.pathname}`}ensureOutlineCacheSession(){const e=this.getOutlineCacheSessionKey();if(e===this.outlineCacheSessionKey)return;const t=""===this.outlineCacheSessionKey;this.outlineCacheSessionKey=e,this.outlineItemCache.clear(),this.outlineCacheTransitionEndAt=t?0:Date.now()+1200;}isInOutlineCacheTransition(){return Date.now()>>0;return t.toString(16)}buildOutlineItemId(e,t,n=0){const r=this.getOutlineMessageKey(e);return t.isUserQuery?`doubao:${r}:user`:`doubao:${r}:h${t.level}:${n}:${this.hashOutlineText(t.text)}`}trimOutlineCache(){if(this.outlineItemCache.size<=1200)return;const e=Array.from(this.outlineItemCache.values()).sort((e,t)=>e.rowIndex!==t.rowIndex?e.rowIndex-t.rowIndex:e.orderInMessage-t.orderInMessage),t=new Set(e.slice(-1200).map(e=>e.id));for(const n of this.outlineItemCache.keys())t.has(n)||this.outlineItemCache.delete(n);}clearOutlineCacheForMeta(e){for(const[t,n]of this.outlineItemCache)e.messageId&&n.messageId===e.messageId?this.outlineItemCache.delete(t):n.messageId||n.rowIndex!==e.rowIndex||this.outlineItemCache.delete(t);}mergeCachedOutlineItems(e,t,n,r,o){if(0===this.outlineItemCache.size)return e;const i=[...e];for(const a of this.outlineItemCache.values())t.has(a.id)||a.isUserQuery&&!r||!a.isUserQuery&&a.level>n||a.text.trim()&&i.push({level:a.level,text:a.text,element:null,id:a.id,isUserQuery:a.isUserQuery,isTruncated:a.isTruncated,wordCount:o?a.wordCount:void 0,scrollTop:a.scrollTop});return i.map((e,t)=>{const n=e.id?this.outlineItemCache.get(e.id):void 0;return {item:e,originalIndex:t,rowIndex:n?.rowIndex??Number.MAX_SAFE_INTEGER,orderInMessage:n?.orderInMessage??t}}).sort((e,t)=>e.rowIndex!==t.rowIndex?e.rowIndex-t.rowIndex:e.orderInMessage!==t.orderInMessage?e.orderInMessage-t.orderInMessage:e.originalIndex-t.originalIndex).map(({item:e})=>e)}escapeAttributeValue(e){return "undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}findMessageElementByCacheEntry(e,t){if(t.messageId){const n=this.escapeAttributeValue(t.messageId),r=e.querySelector(`[data-message-id="${n}"]`);if(r)return r}const n=Array.from(e.querySelectorAll($g)).find(e=>this.getVirtualRowIndex(e,-1)===t.rowIndex);return n?.querySelector("[data-message-id]")||null}findHeadingInsideMessage(e,t){if(t.isUserQuery)return e;const n=Array.from(e.querySelectorAll(`h${t.level}`)),r=t.headingMatchIndex??0;let o=0;for(const i of n)if((i.textContent||"").trim()===t.text){if(o===r)return i;o+=1;}return null}resolveCachedDoubaoOutlineTarget(e){if(!e)return null;this.ensureOutlineCacheSession();const t=this.outlineItemCache.get(e);if(!t)return null;const n=this.getOutlineContentContainer();if(!n)return null;const r=this.findMessageElementByCacheEntry(n,t);return r?t.isUserQuery?r:this.findHeadingInsideMessage(r,t):null}scrollVirtualContainerTo(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.max(0,Math.min(t,n));e.scrollTo({top:r,behavior:"instant",__bypassLock:true}),e.dispatchEvent(new Event("scroll",{bubbles:true}));}async waitForCachedDoubaoOutlineTargetMount(e,t=1500){if(!e)return null;const n=Date.now()+t;for(;Date.now(){if(a)return;const t=this.getOutlineMessageKey(e);if(!s.has(t)){s.add(t);for(const[t,n]of this.outlineItemCache)(e.messageId&&n.messageId===e.messageId||!n.messageId&&n.rowIndex===e.rowIndex)&&l.set(t,n);this.clearOutlineCacheForMeta(e);}},d=(e,t,n,r,o)=>{const s=this.buildOutlineItemId(t,e,o);if(e.id=s,e.scrollTop=n,i.add(s),a)return;const d=this.outlineItemCache.get(s)??l.get(s);c(t),this.outlineItemCache.set(s,{id:s,level:e.level,text:e.text,messageId:t.messageId,rowIndex:t.rowIndex,scrollTop:n,orderInMessage:r,headingMatchIndex:o,isUserQuery:e.isUserQuery,isTruncated:e.isTruncated,wordCount:e.wordCount??d?.wordCount});},u=(t,i,a,s,l)=>{const c=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));c.forEach((t,u)=>{const h=parseInt(t.tagName[1],10);if(h>e)return;const g=t.textContent?.trim()||"";if(!g)return;const p=`${h}:${g}`,m=a.get(p)||0;let f;if(a.set(p,m+1),n){let e=null;for(let t=u+1;te instanceof HTMLElement);let g=null;return (h.length>0?h:Array.from(o.querySelectorAll(`${jg}, ${Gg}`)).filter(e=>e instanceof HTMLElement)).forEach((e,i)=>{const a=this.getVirtualMessageMeta(e,i),s=e.matches(jg)?e:e.querySelector(jg)??null;if(s){const e=this.extractUserQueryMarkdown(s);g=e?{element:s,text:e,meta:a,scrollTop:this.getElementVirtualScrollTop(o,s)}:null;}const l=this.getAssistantContentRoots(e);if(0===l.length)return;c(a);const h=n?l.reduce((e,t)=>e+(t.textContent?.length||0),0):void 0;if(g){const e={level:0,text:g.text.length>80?g.text.slice(0,80)+"...":g.text,element:g.element,isUserQuery:true,isTruncated:g.text.length>80,wordCount:h};d(e,g.meta,g.scrollTop,0),t&&r.push(e);}const p=new Map;let m=0;l.forEach(e=>u(e,a,p,()=>m++,e)),g=null;}),a?r:(this.trimOutlineCache(),this.mergeCachedOutlineItems(r,i,e,t,n))}getExportConfig(){return {userQuerySelector:jg,assistantResponseSelector:Gg,turnSelector:Ug,useShadowDOM:false}}async extractExportMessages(e){const t=this.extractDoubaoExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractDoubaoExportMessages(e))}extractDoubaoExportMessages(e){const t=[],n=this.createDoubaoAssistantImageFallbackState(),r=Array.from(document.querySelectorAll(Ug)).filter(e=>e instanceof HTMLElement);if(r.length>0)return r.forEach(r=>{this.getOrderedDoubaoMessages(r).forEach(({role:r,element:o})=>{t.push({role:r,content:"user"===r?this.extractUserQueryExportContentWithAssets(o,e):this.extractAssistantResponseTextWithAssets(o,e,n)});});}),t;return this.getOrderedDoubaoMessages(document).forEach(({role:r,element:o})=>{t.push({role:r,content:"user"===r?this.extractUserQueryExportContentWithAssets(o,e):this.extractAssistantResponseTextWithAssets(o,e,n)});}),t}getOrderedDoubaoMessages(e){const t=[],n=new Set,r=(e,r)=>{r&&!n.has(r)&&(n.add(r),t.push({role:e,element:r}));};return e instanceof Element&&(e.matches(jg)?r("user",e):e.matches(Gg)&&r("assistant",e)),e.querySelectorAll(jg).forEach(e=>r("user",e)),e.querySelectorAll(Gg).forEach(e=>r("assistant",e)),t.sort((e,t)=>{if(e.element===t.element)return 0;const n=e.element.compareDocumentPosition(t.element);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0})}toggleTheme(){return Promise.resolve(false)}isGenerating(){const e=document.querySelector('[data-testid="chat_input_local_break_button"]');return null!==e&&null!==e.offsetParent}getStopButtonSelectors(){return ['[data-testid="chat_input_local_break_button"]']}getNewChatButtonSelectors(){return [Og]}getSubmitButtonSelectors(){return ["[data-testid='chat_input_send_button']","#flow-end-msg-send",".send-btn-wrapper button"]}getWidthSelectors(){return [{selector:'[data-container-name="main"]',property:"max-width"},{selector:".max-w-\\(--content-max-width\\)",property:"max-width"},{selector:".max-w-\\[var\\(--content-max-width\\)\\]",property:"max-width"},{selector:'[style*="--content-max-width"]',property:"--content-max-width"},{selector:".chrome70-container",property:"--center-content-max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${jg} .w-fit[class*="max-w-"]`,property:"max-width"}]}getVisibleAnchorElement(){const e=this.getScrollContainer();if(!e)return null;const t=this.getChatContentSelectors();if(!t.length)return null;const n=Array.from(e.querySelectorAll(t.join(", ")));if(!n.length)return null;const r=e.getBoundingClientRect();let o=null;for(let i=0;i=r.top-50&&t.bottom<=r.bottom+50){o=e;break}if(t.top<=r.top&&t.bottom>=r.top){o=e;break}}if(!o)for(let i=0;ir.bottom){o=e;break}}if(o){const e=n.indexOf(o);if(-1!==e){return {type:"index",index:e,offset:0,textSignature:(o.textContent||"").trim().substring(0,50)}}}return null}scrollToOutlineTarget(e){const t=this.getScrollContainer();if(!t)return void super.scrollToOutlineTarget(e);const n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),o=t.scrollTop+r.top-n.top;t.scrollTo({top:Math.max(0,o),behavior:"instant",__bypassLock:true});}restoreScroll(e){const t=this.getScrollContainer();if(!t||!e)return false;let n=null;if("index"===e.type&&"number"==typeof e.index){const r=this.getChatContentSelectors(),o=Array.from(t.querySelectorAll(r.join(", ")));if(o[e.index]){if(n=o[e.index],e.textSignature){if((n.textContent||"").trim().substring(0,50)!==e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}}else if(e.textSignature){const t=o.find(t=>(t.textContent||"").trim().substring(0,50)===e.textSignature);t&&(n=t);}}return !!n&&(this.scrollToOutlineTarget(n),true)}},new class extends gs{exportIncludeThoughts=void 0;match(){return window.location.hostname===Rm}getSiteId(){return fo}getName(){return "ima"}getThemeColors(){return {primary:"#07a45f",secondary:"#05854d"}}supportsHostThemeSync(){return false}getSessionId(){const e=window.location.pathname.match(Pm);return e?.[1]||""}isNewConversation(){return "/"===(window.location.pathname.replace(/\/+$/,"")||"/")}isSharePage(){return window.location.pathname.startsWith("/share/")}getCurrentCid(){const e=window.localStorage.getItem("ima-official-website-uid");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","userId","openId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=this.getActiveHistoryTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*ima$/i,"").replace(/^ima\s*[-|]\s*/i,"").trim();return n&&"ima"!==n.toLowerCase()?n:null}getNewTabUrl(){return "https://ima.qq.com/"}getConversationTitle(){return this.getActiveHistoryTitle()||this.getSessionName()}getTextareaSelectors(){return ['#tagTextarea [contenteditable="true"], [class*="chatInputContainer"] .tiptap.ProseMirror']}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!!e.isContentEditable&&!!e.closest("#tagTextarea, [class*='chatInputContainer']"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus(),this.selectAllEditorContent(t);if(this.tryPasteText(t,e))return true;try{if(document.execCommand("insertText",!1,e))return this.dispatchEditorInput(t,e,"insertText"),!0}catch{}return t.textContent=e,this.dispatchEditorInput(t,e,"insertText"),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus(),this.selectAllEditorContent(e);try{document.execCommand("delete",!1);}catch{}e.textContent="",this.dispatchEditorInput(e,"","deleteContentBackward");}}getSubmitButtonSelectors(){return [af]}findSubmitButton(e){const t=[e?.closest("#tagTextarea"),e?.closest('[class*="chatInputContainer"]'),document.querySelector('[class*="chatInputContainer"]'),document.body].filter(Boolean);for(const n of t){const e=n.querySelector(af);if(e&&this.isVisibleElement(e)&&!e.querySelector('.icon-send-disable-big, [class*="sendDisableIcon"]'))return e}return null}getNewChatButtonSelectors(){return ['[class*="newChatWrap"]']}getSidebarScrollContainer(){return document.querySelector("#HistoryScrollContainer")}getScrollContainer(){const e=document.querySelector(zm);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return Bm}getChatContentSelectors(){return [$m,Gm]}getUserQuerySelector(){return $m}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg").forEach(e=>{e.remove();}),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}getLatestReplyText(){const e=document.querySelectorAll(Gm),t=e[e.length-1];if(!t)return null;return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Bm)||document.querySelector(zm);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(`${$m}, ${Gm}`)).filter(e=>!e.closest(".gh-root"));return i.forEach((r,a)=>{if(r.matches($m)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Gm));s=e?this.extractAssistantResponseText(e).length:0;}return void o.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractImaExportMessages(e))}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [sf]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/cgi-bin/assistant/qa"],urlPathEndsWith:["/cgi-bin/assistant/qa"],silenceThreshold:2e3}}getModelName(){const e=this.findVisibleElementBySelectors([cf]),t=e?.innerText?.trim()||e?.textContent?.trim()||"";if(t)return t.split("\n")[0].trim();const n=this.findVisibleElementBySelectors([lf]),r=n?.innerText?.trim()||n?.textContent?.trim()||"";return r?r.split("\n")[0].trim():null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[lf,cf],menuItemSelector:'.modelDropdown .t-dropdown__item, .modelDropdown [class*="modelOption"], .t-popup .modelDropdown .t-dropdown__item',menuRenderDelay:200,checkInterval:1e3,maxAttempts:10}}getWidthSelectors(){return [{selector:zm,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:Bm,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:'[class*="_chatInputContainer_"] [class*="_editorContainer_"]',property:"max-width",extraCss:"width: 100vw !important; margin: 0 auto;"}]}getUserQueryWidthSelectors(){return [{selector:Hm,property:"max-width"}]}getZenModeConfig(){return {hide:[".expandable-sidebar-panel-sidebar"]}}getCleanModeConfig(){return {hide:['[class*="_downloadContainer_"]','[class*="footTips"]','[class*="_activityBanner"]','[class*="_activityBannerContent"]','[class*="_qaDownloadGuide"]']}}extractImaExportMessages(e){const t=document.querySelector(Bm)||document.querySelector(zm)||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${$m}, ${Gm}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches($m)?"user":"assistant";return {role:n,content:("user"===n?this.extractUserQueryExportContentWithAssets(t,e):this.extractAssistantResponseTextWithAssets(t,e)).trim()}}).filter(e=>e.content.length>0)}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserQueryText(e),r=this.extractImaUserAttachments(e);if(0===r.length)return n;const o=this.formatImaUserImageAttachments(r,t),i=this.formatImaUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatImaAssistantImages(this.extractImaAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport(),n=e.cloneNode(true),r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(`${Jm}, ${rf}`).forEach(e=>e.remove()),n.querySelectorAll(Zm).forEach(e=>e.remove());const o=this.findAssistantMarkdownRoot(n),i=o instanceof HTMLElement?o:this.findAssistantBubbleRoot(n),a=(i?Fi(i).trim():"")||(i?this.extractTextWithLineBreaks(i).trim():"");if(t&&r.length>0){const e=r.join("\n\n");return a?`${e}\n\n${a}`:e}return a}extractImaUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getImaAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return this.queryElementsIncludingSelf(t,ef).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractImaUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,tf).forEach(e=>{o(this.extractImaUserFileAttachment(e));}),n}extractImaUserImageAttachment(e){const t=this.extractImaImageSource(e);if(!t)return null;const n=e.alt?.trim()||e.getAttribute("title")?.trim()||da(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:ua(n)||ha(t)||"image"}}extractImaUserFileAttachment(e){if(e instanceof HTMLImageElement||e.closest('[class*="imgWrap"], [id^="image-toolkit-"]')||e.querySelector("img"))return null;const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=ga(t),i=this.extractImaDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||da(i,{ignoreGenericDownload:true})||this.extractDataAttributeFilename(e);if(!a&&!i)return null;const s=a||"attachment";return {kind:"file",name:s,source:i,type:r||ua(s)||ha(i),sizeLabel:o}}formatImaUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatImaUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId()})}extractImaAssistantImages(e){const t=this.findAssistantBubbleRoot(e)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,nf).forEach(e=>{if(!(e instanceof HTMLImageElement))return;if(e.closest(".gh-root, .gh-user-query-markdown"))return;const t=this.extractImaImageSource(e),o=ca(t);t&&!r.has(o)&&(r.add(o),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`,extensionHint:this.extractImaImageExtensionHint(e)}));}),n}formatImaAssistantImages(e,t){return Ma(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractImaImageSource(e){const t=[e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeImaExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractImaDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractImaImageSource(e)),!t.includeImages&&e instanceof HTMLImageElement||of.forEach(t=>{n.push(e.getAttribute(t)||"");});});for(const r of n){const e=this.normalizeImaExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeImaExportSource(e,t){const n=e.trim();if(!n||n.startsWith("#")||/^javascript:/i.test(n))return "";const r=fa(n);if(!r)return "";if(/^data:image\/svg\+xml/i.test(r))return "";if(/^data:image\//i.test(r))return t.allowDataImage?r:"";if(/^data:/i.test(r))return r;if(!ba(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===Rm&&/^\/(?:chat|share|ai-chat)(?:\/|$)/i.test(e.pathname))return "";if(e.hostname===Rm&&/\/(?:static|assets)\//i.test(e.pathname))return "";if(/\/wupload\/xy\/(?:qb_tool|ima_tool)\//i.test(e.pathname))return "";if(/\.(?:svg|ico)$/i.test(e.pathname)&&/(?:icon|logo|sprite)/i.test(e.pathname))return ""}catch{return ""}return r}extractImaImageExtensionHint(e){return [e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.alt||""].map(e=>ha(e)||ua(e)).find(Boolean)||""}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll(Jm).forEach(e=>e.remove()),t.querySelectorAll("img").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getImaAttachmentKeys(e){const t=[],n=ca(e.source),r=e.name.trim().toLowerCase(),o=e.type.trim().toLowerCase(),i=e.sizeLabel?.trim().toLowerCase()||"";return n&&t.push(`${e.kind}:source:${n}`),r&&o&&t.push(`${e.kind}:name-type:${r}:${o}`),r&&i&&t.push(`${e.kind}:name-size:${r}:${i}`),t.length>0?t:[`${e.kind}:fallback:${r}:${o}`]}extractDataAttributeFilename(e){const t=["data-file-name","data-filename","data-name","title","aria-label","data-file-id","data-doc-id","data-resource-id"];for(const n of t){const t=e.getAttribute(n)?.trim();if(t)return t}return ""}findUserMessageScope(e){return e.matches($m)?e:e.closest($m)||e}findAssistantBubbleRoot(e){if(e.matches(Qm))return e;const t=e.querySelector(Qm);if(t instanceof HTMLElement)return t;const n=e.querySelector('[class*="bubble"]');return n instanceof HTMLElement?n:e instanceof HTMLElement?e:null}shouldSkipExportElement(e){return null!==e.closest(".gh-root, .gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}getActiveHistoryTitle(){const e=document.querySelector('[class*="historyListWrap"] [class*="itemWrap"][class*="highLight"] [class*="main"]');return e?.textContent?.trim()||""||null}findUserContentRoot(e){return e.matches(Wm)?e:e.querySelector(Wm)||e.querySelector("p")||e}findAssistantMarkdownRoot(e){return e.matches(Km)?e:e.querySelector(Km)}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll(Ym).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(Zm)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="tipsWrap"], [class*="thinkingTitle"], [class*="thinkingHeader"], button, [role=\'button\'], svg, [aria-hidden=\'true\']').forEach(e=>e.remove());const t=(Fi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}tryPasteText(e,t){if("undefined"==typeof DataTransfer||"undefined"==typeof ClipboardEvent)return false;try{const n=new DataTransfer;n.setData("text/plain",t);const r=new ClipboardEvent("paste",{clipboardData:n,bubbles:!0,cancelable:!0,composed:!0});if(!e.dispatchEvent(r))return !0}catch{return false}return false}selectAllEditorContent(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}dispatchEditorInput(e,t,n){e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:t,inputType:n})),e.dispatchEvent(new Event("change",{bubbles:true}));}isVisibleElement(e){if(!e||!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility)return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}findStopButton(){const e=Array.from(document.querySelectorAll('div[class*="stopButton"], [class*="stopButton"]'));for(const t of e){if(!(t instanceof HTMLElement&&this.isVisibleElement(t)))continue;const e=[t.querySelector(":scope > div"),t.querySelector('[class*="container"]'),t];for(const t of e)if(t instanceof HTMLElement&&this.isVisibleElement(t))return t}return null}},new class extends gs{exportIncludeThoughtsOverride=null;exportApiMessages=null;match(){return Ps.has(window.location.hostname)}getSiteId(){return uo}getName(){return "智谱清言"}getThemeColors(){return {primary:"#2454FF",secondary:"#1F46D6"}}async toggleTheme(e){const t=Os[e]||Os.light;try{localStorage.setItem(Bs,t);if(await this.applyThemeByClick(e))return !0;const n="system"===e&&"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,r="system"===e?n?"dark":"light":e,o=e=>{e&&(e.classList.toggle("dark-theme","dark"===r),e.classList.remove("light-theme"),e.setAttribute("data-theme",r),e.setAttribute("data-color-scheme",r),e.style.colorScheme=r);},i=new Set;document.documentElement&&i.add(document.documentElement),document.body&&i.add(document.body);const a=[document.querySelector("#app"),document.querySelector("[data-v-app]"),document.querySelector(".app"),document.querySelector(".app-container")];for(const e of a)e instanceof HTMLElement&&i.add(e);for(const e of i)o(e);return window.dispatchEvent(new StorageEvent("storage",{key:Bs,newValue:t,storageArea:localStorage})),!0}catch{return false}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t){const t=new MouseEvent(r,{bubbles:true,cancelable:true,view:window});n=e.dispatchEvent(t)||n;}n||e.click();}async applyThemeByClick(e){const t=this.findVisibleElement(Fs);if(!t)return false;this.simulateClick(t),await this.delay(120);const n=await this.waitForVisibleElement(".themes",1500);if(!n)return false;this.simulateClick(n),await this.delay(120);const r=await this.findThemeOption(e,1500);return !!r&&(this.simulateClick(r),await this.delay(80),true)}findVisibleElement(e){for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return this.resolveClickable(e)}return null}resolveClickable(e){return e.closest(".me-icon")||e.closest(".me")||e.closest(".userInfoBar-header")||e}async waitForVisibleElement(e,t=800){const n=Date.now();for(;Date.now()-n0)break}return Array.from(t)}matchThemeOption(e,t){const n=t.map(e=>e.replace(/\s+/g,"").toLowerCase());for(const r of e){const e=r.textContent?.replace(/\s+/g,"").toLowerCase()||"";if(e&&n.some(t=>e.includes(t)))return r}return null}async delay(e){await new Promise(t=>window.setTimeout(t,e));}getTextareaSelectors(){return Zs}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSessionId(){const e=new URLSearchParams(window.location.search);if(this.isSharePage())return e.get(zs)?.trim()||e.get("share_id")?.trim()||window.location.pathname.match(/^\/share\/([^/?#]+)/)?.[1]?.trim()||"";const t=e.get("cid");return t?t.trim():""}isNewConversation(){return !this.getSessionId()}getNewChatButtonSelectors(){return [".new-session",'div[class~="new-session"]']}getNewTabUrl(){return new URL("/main/alltoolsdetail?lang=zh",window.location.origin).toString()}isSharePage(){return window.location.pathname.startsWith("/glmsShare")||window.location.pathname.startsWith("/share/")||"1"===new URLSearchParams(window.location.search).get("is_share")}isUserConversationPage(){const e=new URLSearchParams(window.location.search).get("cid")?.trim();return !this.isSharePage()&&Boolean(e)&&e===this.getSessionId()}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*(智谱清言|ChatGLM(?:\s*\d+)?)\s*$/i,"").trim();return n&&"智谱清言"!==n&&"chatglm"!==n.toLowerCase()?n:null}getConversationTitle(){const e=document.querySelector(".conversation-name");if(e){const t=e.textContent?.trim();if(t)return t}return null}getSubmitButtonSelectors(){return [`${Ys}:not(.empty)`]}findSubmitButton(){const e=document.querySelector(Ys);return !e||e.classList.contains("empty")||null===e.offsetParent?null:e}getScrollContainer(){const e=document.querySelector(Us);if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chatScrollContainer");return t&&t.scrollHeight>t.clientHeight?t:super.getScrollContainer()}getResponseContainerSelector(){return Us}getChatContentSelectors(){return [Gs,Hs]}getUserQuerySelector(){return js}extractUserQueryText(e){const t=e.querySelector(Hs)||e;return this.extractTextWithLineBreaks(t).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractChatGLMUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=e.querySelector(Hs);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");r.className=[...n.classList,"gh-user-query-markdown","gh-markdown-preview"].filter(e=>"dots"!==e&&"dot-3-line"!==e).join(" ").trim(),r.innerHTML=t;const o=n.getAttribute("style");o&&r.setAttribute("style",o),r.style.textAlign="left",r.style.display="block",r.style.width="100%",n.style.display="none";const i=e.querySelector(".collapse-button-bg");return i&&(i.style.display="none"),n.after(r),true}extractAssistantResponseText(e){return this.extractChatGLMAssistantExportContent(e).trim()}getLatestReplyText(){const e=document.querySelector(Us)||document.body,t=this.collectChatGLMAssistantExportElements(e),n=t[t.length-1];if(!n)return null;return this.extractAssistantResponseText(n)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Us);if(!r)return [];const o=[],i=Array.from(r.querySelectorAll(".conversation-item"));return i.forEach((r,a)=>{const s=r.querySelector(js);if(s&&t){const e=this.extractUserQueryMarkdown(s);if(e){let t;if(n){const e=(e=>{for(let t=e+1;t80?`${e.slice(0,80)}...`:e,element:s,isUserQuery:true,isTruncated:e.length>80,wordCount:t});}}const l=r.querySelectorAll(Gs);l.length&&l.forEach(t=>{const r=Array.from(t.querySelectorAll("h1, h2, h3, h4, h5, h6"));r.forEach((i,a)=>{if(this.isInRenderedMarkdownContainer(i))return;const s=Number.parseInt(i.tagName.slice(1),10);if(Number.isNaN(s)||s>e)return;const l=i.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=a+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractChatGLMExportMessages(e))}async fetchShareApiMessages(){const e=this.getShareConversationId();if(!e)return null;try{const t=await fetch(`/chatglm/share-api/conversation/info/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`share conversation info failed with ${t.status}`);const n=await t.json(),r=n?.result?.messages;return Array.isArray(r)?r:null}catch(t){return console.warn("[ChatGLMAdapter] Failed to load share export metadata:",t),null}}getShareConversationId(){return new URLSearchParams(window.location.search).get(zs)?.trim()||""}extractChatGLMExportMessages(e){return this.exportApiMessages?.length?this.extractChatGLMApiExportMessages(this.exportApiMessages,e):this.extractChatGLMDomExportMessages(e)}extractChatGLMApiExportMessages(e,t){const n=[];return e.forEach(e=>{const r=this.extractChatGLMApiUserContent(e,t).trim();r&&n.push({role:"user",content:r});const o=this.extractChatGLMApiAssistantContent(e,t).trim();o&&n.push({role:"assistant",content:o});}),n}extractChatGLMApiUserContent(e,t){const n=[],r=[];return e.input?.content?.forEach(e=>{"text"===e.type&&e.text?.trim()&&n.push(e.text.trim()),e.image?.forEach(e=>{const t=this.createChatGLMApiAttachment(e,"image");t&&r.push(t);}),e.file?.forEach(e=>{const t=this.createChatGLMApiAttachment(e,"file");t&&r.push(t);});}),this.formatChatGLMUserExportContent(n.join("\n\n"),r,t)}extractChatGLMApiAssistantContent(e,t){const n=this.shouldIncludeThoughtsInExport(),r=[],o=[],i=[];e.output?.parts?.forEach(e=>{const t=this.extractChatGLMApiThought(e,e);t?n&&r.push(this.formatAsThoughtBlockquote(t)):e.content?.forEach(t=>{const a=this.extractChatGLMApiThought(t,e);if(a)return void(n&&r.push(this.formatAsThoughtBlockquote(a)));t.image?.forEach(e=>{const t=this.createChatGLMGeneratedImageAttachment(e.image_url||"");t&&i.push(t);});const s=this.extractChatGLMApiBodyText(t);s&&o.push(s);});}),e.output?.image_list?.forEach(e=>{const t=this.createChatGLMGeneratedImageAttachment(e);t&&i.push(t);});const a=this.formatChatGLMAssistantImageAttachments(i,t);return [r.join("\n\n"),a.join("\n\n"),o.join("\n\n")].filter(Boolean).join("\n\n")}extractChatGLMApiThought(e,t){const n=this.extractChatGLMApiThoughtText(e);if(!n)return "";const r="type"in e&&e.type||"",o=e.answer_type||"";if(/^(think|text_thinking|advanced_thinking)$/i.test(r||o))return n;const i=e.meta_data?.show_type||t.meta_data?.show_type||"",a=e.meta_data?.engine?.type||t.meta_data?.engine?.type||"";return /think|thought|reason|cot/i.test(`${i} ${a}`)?n:""}extractChatGLMApiBodyText(e){return "tool_calls"===e.type||this.extractChatGLMApiThought(e,{meta_data:e.meta_data})?"":this.extractChatGLMApiContentText(e)}extractChatGLMApiThoughtText(e){const t=e.advancedThinkingData?.map(e=>this.extractChatGLMApiContentText(e)).filter(Boolean).join("\n\n");return t||this.extractChatGLMApiContentText(e)}extractChatGLMApiContentText(e){return e.think?.trim()||e.text?.trim()||e.answer?.trim()||("content"in e&&"string"==typeof e.content?e.content.trim():"")||"intent_original_output"in e&&e.intent_original_output?.trim()||""||"type"in e&&"code"===e.type&&e.code?.trim()||""}createChatGLMApiAttachment(e,t){const n=this.decodeChatGLMAttachmentName(e.file_name||e.file_id||("image"===t?"uploaded image":"file")),r=this.normalizeChatGLMAttachmentSource(e.file_url||e.image_url||""),o=e.file_type||e.type||n.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"",i=this.isChatGLMImageAttachment(n,o,r)?"image":t;return n||r?{kind:i,name:n||("image"===i?"uploaded image":"file"),source:r,type:o,size:e.file_size}:null}createChatGLMGeneratedImageAttachment(e){const t=this.normalizeChatGLMAttachmentSource(e);return t?{kind:"image",name:this.extractChatGLMFilenameFromUrl(t)||"generated image",source:t,type:"image"}:null}extractChatGLMDomExportMessages(e){const t=document.querySelector(Us)||document.body,n=this.collectChatGLMAssistantExportElements(t),r=[...Array.from(t.querySelectorAll(js)).map(e=>({role:"user",element:e})),...n.map(e=>({role:"assistant",element:e}))].filter(({element:e})=>!e.closest(".gh-root, .gh-user-query-markdown")).sort((e,t)=>this.compareDomOrder(e.element,t.element)),o=[];return r.forEach(({role:t,element:n})=>{const r=("user"===t?this.extractChatGLMUserQueryExportContent(n,e):this.extractChatGLMAssistantExportContent(n,e)).trim();if(!r)return;const i=o[o.length-1];i?.role!==t?o.push({role:t,content:r}):i.content=`${i.content}\n\n${r}`;}),o}collectChatGLMAssistantExportElements(e){const t=[],n=new Set;return Array.from(e.querySelectorAll(`${Ws}, ${Qs}`)).forEach(e=>{if(e.closest(".gh-root, .gh-user-query-markdown"))return;const r=this.findChatGLMThoughtRoot(e),o=r?.closest(Ws);if(r&&o&&o!==r)return;const i=r||e;!r&&e.closest(Qs)||n.has(i)||(n.add(i),t.push(i));}),t.sort((e,t)=>this.compareDomOrder(e,t))}findChatGLMThoughtRoot(e){let t=e.matches(Qs)?e:e.closest(Qs);if(!t)return null;let n=t.parentElement?.closest(Qs)||null;for(;n;)t=n,n=t.parentElement?.closest(Qs)||null;return t}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractChatGLMUserQueryExportContent(e,t){const n=this.extractUserQueryMarkdown(e).trim(),r=this.extractChatGLMUserAttachmentsFromDom(e);return this.formatChatGLMUserExportContent(n,r,t)}extractChatGLMAssistantExportContent(e,t){const n=this.shouldIncludeThoughtsInExport(),r=e.matches(Qs),o=e.cloneNode(true),i=this.extractThoughtBlockquotes(o),a=n?i.blocks:[];if(r)return a.join("\n\n");i.removalNodes.forEach(e=>e.remove()),o.querySelectorAll(Qs).forEach(e=>e.remove());const s=this.extractChatGLMAssistantImageMarkdown(e,t),l=(o.matches(Ws)||o.matches(".markdown-body")?o:o.querySelector(".markdown-body")||o).cloneNode(true);l.querySelectorAll(Vs).forEach(e=>e.remove()),l.querySelectorAll("img").forEach(e=>{e instanceof HTMLImageElement&&this.isExportableChatGLMImage(e)&&e.remove();});const c=(Fi(l)||this.extractTextWithLineBreaks(l)).trim();return [a.join("\n\n"),s.join("\n\n"),c].filter(Boolean).join("\n\n")}formatChatGLMUserExportContent(e,t,n){if(0===t.length)return e;const r=this.dedupeChatGLMAttachments(t),o=this.formatChatGLMUserImageAttachments(r,n),i=this.formatChatGLMUserFileAttachments(r,n),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,e].filter(Boolean).join("\n\n")}extractChatGLMUserAttachmentsFromDom(e){const t=e.matches(js)?e:e.closest(js);if(!t)return [];const n=[];Array.from(t.querySelectorAll("img")).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractChatGLMImageSource(e);if(!t)return;const r=this.extractChatGLMAttachmentNameFromElement(e)||e.alt||"uploaded image";n.push({kind:"image",name:r,source:t,type:r.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"image"});});return Array.from(t.querySelectorAll("a[href], button, [class*='file'], [class*='image-with-text']")).forEach(e=>{if(e.closest(".gh-root, .gh-user-query-markdown"))return;const t=this.extractChatGLMDomAttachment(e);t&&n.push(t);}),this.dedupeChatGLMAttachments(n)}extractChatGLMDomAttachment(e){const t=this.extractTextWithLineBreaks(e).replace(/\s+/g," ").trim(),n=this.extractChatGLMDownloadableSource(e),r=this.extractChatGLMAttachmentNameFromText(t)||this.extractChatGLMFilenameFromUrl(n);if(!r)return null;const o=r.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"";return {kind:this.isChatGLMImageAttachment(r,o,n)?"image":"file",name:r,source:n,type:o,size:this.parseChatGLMSizeLabel(t)}}extractChatGLMAttachmentNameFromElement(e){const t=this.extractTextWithLineBreaks(e.closest("button, a, [class*='file']")||e);return this.extractChatGLMAttachmentNameFromText(t)}extractChatGLMAttachmentNameFromText(e){const t=e.replace(/\s+/g," ").trim();return t.match(/[^\s/\\]+\.[A-Za-z0-9]{1,10}/)?.[0]||""}extractChatGLMAssistantImageMarkdown(e,t){const n=Array.from(e.querySelectorAll("img")).filter(e=>e instanceof HTMLImageElement&&this.isExportableChatGLMImage(e)).map(e=>({kind:"image",name:e.alt||this.extractChatGLMFilenameFromUrl(this.extractChatGLMImageSource(e))||"generated image",source:this.extractChatGLMImageSource(e),type:"image"}));return this.formatChatGLMAssistantImageAttachments(n,t)}formatChatGLMUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatChatGLMAssistantImageAttachments(e,t){return _a(this.dedupeChatGLMAttachments(e),t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}formatChatGLMUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),getLabel:e=>{const t=e.size?`, ${this.formatChatGLMFileSize(e.size)}`:"";return e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?`${e.name}${t}`:`${e.name} (${e.type}${t})`:`${e.name}${t}`}})}dedupeChatGLMAttachments(e){const t=new Set,n=[];return e.forEach(e=>{const r=this.getChatGLMAttachmentSourceKey(e.source),o=`${e.kind}:${e.name.trim().toLowerCase()}:${e.type.trim().toLowerCase()}`,i=r?`${e.kind}:source:${r}`:o;t.has(i)||(t.add(i),n.push(e));}),n}extractThoughtBlockquotes(e){const t=[...e.matches(Qs)?[e]:[],...Array.from(e.querySelectorAll(Qs))].filter(e=>!e.parentElement?.closest(Qs)),n=[],r=[];return t.forEach(e=>{const t=(e.querySelector("blockquote[slot='content'], blockquote, .text-advance-thinking-content .markdown-body, .thinking-content .markdown-body, .advance-thinking-area .markdown-body, .markdown-body")||e).cloneNode(true);t.querySelectorAll(Vs).forEach(e=>e.remove());const o=document.createElement("div");Array.from(t.childNodes).forEach(e=>o.appendChild(e.cloneNode(true)));const i=(Fi(o)||this.extractTextWithLineBreaks(t)).trim();i&&n.push(this.formatAsThoughtBlockquote(i)),r.push(e);}),{blocks:n,removalNodes:r}}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> [Thought]",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim()?`> ${e}`:">")].join("\n")}isExportableChatGLMImage(e){const t=this.extractChatGLMImageSource(e);if(!t)return false;if(!ba(t))return false;if(t.startsWith("data:image/svg+xml"))return false;try{const e=new URL(t,window.location.href);if("chatglm.cn"===e.hostname&&/^\/(assets|icon)\//i.test(e.pathname))return !1;if(/image_loading|newLogo|avatar|favicon|icon/i.test(e.pathname))return !1;if(/\/(chat\/image|testpath|file)\//i.test(e.pathname))return !0}catch{return false}const n=e.getBoundingClientRect();return Math.max(e.naturalWidth||0,n.width)>=80&&Math.max(e.naturalHeight||0,n.height)>=80}extractChatGLMImageSource(e){if(this.isChatGLMAvatarImage(e))return "";const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=this.normalizeChatGLMAttachmentSource(n);if(e)return e}return ""}isChatGLMAvatarImage(e){if(e.classList.contains("user-img")||e.classList.contains("avatar"))return true;if(e.closest(".user-img, .avatar, .user-avatar, .userInfoBar-header"))return true;const t=e.currentSrc||e.src||e.getAttribute("src")||"";return /\/wechat_avatar\//i.test(t)}extractChatGLMDownloadableSource(e){const t=Array.from(e.querySelectorAll("img")).find(e=>e instanceof HTMLImageElement&&Boolean(this.extractChatGLMImageSource(e)));if(t)return this.extractChatGLMImageSource(t);const n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of Ks){const t=this.normalizeChatGLMAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeChatGLMAttachmentSource(e){const t=fa(e);if(!t||!ba(t))return "";try{const e=new URL(t,window.location.href);if("chatglm.cn"===e.hostname&&/^\/(assets|icon)\//i.test(e.pathname))return "";if(/wechat_avatar|image_loading|newLogo|avatar|favicon|iconfont/i.test(e.pathname))return ""}catch{return ""}return t}isChatGLMImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}parseChatGLMSizeLabel(e){const t=e.match(/(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)/i);if(!t)return;const n=Number(t[1]);if(!Number.isFinite(n))return;const r=t[2].toUpperCase(),o="TB"===r?1024**4:"GB"===r?1024**3:"MB"===r?1048576:"KB"===r?1024:1;return Math.round(n*o)}formatChatGLMFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?Math.round(n).toString():n.toFixed(1)} ${t[r]}`}extractChatGLMFilenameFromUrl(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname;return this.decodeChatGLMAttachmentName(t.split("/").pop()||"")}catch{return ""}}getChatGLMAttachmentSourceKey(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.hostname}${t.pathname}`.toLowerCase()}catch{return e.split("?")[0].toLowerCase()}}decodeChatGLMAttachmentName(e){try{return decodeURIComponent(e)}catch{return e}}isGenerating(){const e=[".stop-generate",".stop-answer-default",".stop-stream-tip",".answer-content-wrap .generating-icon",".enter-icon-container.stop",".enter.searching",".enter.is-main-chat.searching"];for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return true}return false}getStopButtonSelectors(){return [".stop-generate",".stop-answer-default",".stop-stream-tip",".answer-content-wrap .generating-icon",".enter-icon-container.stop",".enter.searching",".enter.is-main-chat.searching"]}getModelName(){const e=[".wrapper-title .showHideText",".wrapper-title .wrapper-title-innerText",".wrapper-title",".selected-model-info .model-select-name",".model-select-container .model-select-name",".model-select-list .model-select-item.selected .model-select-name",".model-select-name"];for(const t of e){const e=document.querySelectorAll(t);for(const t of Array.from(e)){const e=t.textContent?.trim();if(!e)continue;if(null!==t.offsetParent)return e.split("\n")[0].trim()}}for(const t of e){const e=document.querySelector(t),n=e?.textContent?.trim();if(n)return n.split("\n")[0].trim()}return null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".wrapper-title",".wrapper-title .showHideText",".model-select-icon-container",".selected-model-info",".model-select-container"],menuItemSelector:".model-select-list .model-select-item",menuRenderDelay:150,checkInterval:1e3,maxAttempts:10}}getNetworkMonitorConfig(){return {urlPatterns:["/chatglm/backend-api/assistant/stream"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:".conversation-container",property:"max-width"},{selector:".conversation-inner",property:"max-width"},{selector:".conversation-list",property:"max-width"},{selector:".dialogue .detail .item, .dialogue .detail .item.item, .dialogue .detail .item.item.item",property:"max-width"},{selector:".markdown-body, .markdown-body.markdown-body, .answer-content-wrap .markdown-body",property:"max-width"},{selector:".code-no-artifacts .markdown-body.md-code, .code-no-artifacts .md-code",property:"max-width",value:"100%",extraCss:["width: 100% !important;","margin-left: 0 !important;","margin-right: 0 !important;","box-sizing: border-box !important;"].join(" "),noCenter:true},{selector:".code-no-artifacts .markdown-body.md-code > .language, .code-no-artifacts .markdown-body.md-code pre",property:"max-width",value:"100%",extraCss:"width: 100% !important; box-sizing: border-box !important;",noCenter:true},{selector:".markdown-body table, .answer-content-wrap .markdown-body table",property:"width",value:"100%",extraCss:"table-layout: fixed !important; display: table !important; min-width: 100% !important;",noCenter:true},{selector:".markdown-body table th, .markdown-body table td",property:"min-width",value:"0",noCenter:true},{selector:".conversation-list",property:"width",value:"100%"},{selector:".conversation-bottom[data-v-e5578310]",property:"max-width",extraCss:"flex: 1 !important;"},{selector:".component-box-new[data-v-fb010f38]",property:"max-width"}]}getZenModeConfig(){return {hide:[".el-aside"]}}getCleanModeConfig(){return {hide:[".policy-wrap, .policy-wrap *",".vip-btn",".slogan-banner"]}}},new class extends gs{deleteReloadScheduled=false;loggedMissingDeleteToken=false;fullListSnapshot=[];fullListSnapshotExpiresAt=0;fullListSnapshotUsesLeft=0;exportIncludeThoughts=void 0;match(){const e="www.kimi.com"===window.location.hostname;return e&&this.normalizeThemeStorageValue(),e}getSiteId(){return yo}getName(){return "Kimi"}getThemeColors(){return {primary:"#7C3AED",secondary:"#6D28D9"}}getNativeThemeCss(){return "\n/* =============================================\n * Kimi 站点原生主题适配器 (Kimi Theme Adapter)\n * ============================================= */\n:root {\n /* 1. 主体与大容器背景 */\n // --Bg-Primary: var(--gh-bg) !important;\n // --Bg-Tertiary: var(--gh-bg) !important;\n // --Bg-Quaternary: var(--gh-bg) !important;\n // --BgGp-Secondary: var(--gh-bg-secondary) !important;\n // --Always-White: var(--gh-bg) !important;\n\n /* 2. 灰色次级容器层 (底色画布、侧边栏、交互卡片) */\n --Bg-GroundPC: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n --Bg-Secondary: color-mix(in srgb, var(--gh-primary) 3%, var(--gh-bg)) !important;\n --BgGp-Primary: color-mix(in srgb, var(--gh-primary) 3%, var(--gh-bg)) !important;\n --BgGp-Tertiary: color-mix(in srgb, var(--gh-primary) 4%, var(--gh-bg)) !important;\n --Others-BubbleGray_PC: var(--gh-bg-secondary) !important;\n\n /* 3. 强调与品牌色 (主色系挂载为 Ophel 主题) */\n --Colors-KMBlue: var(--gh-primary) !important;\n --Colors-KMBlue-hover: color-mix(in srgb, var(--gh-primary) 85%, white) !important;\n --Colors-KMBlue-active: color-mix(in srgb, var(--gh-primary) 85%, black) !important;\n --Others-KMBlue10: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n\n /* 4. 辅助状态的高亮 */\n --Others-TextSelected: color-mix(in srgb, var(--gh-primary) 20%, transparent) !important;\n --Others-LightBlueBg: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n\n /* 代码块背景色 */\n --Fills-F1: var(--gh-bg-tertiary) !important;\n\n}\n\n.sidebar {\n background-color: color-mix(in srgb, var(--gh-primary) 1%, var(--gh-bg)) !important;\n}\n\n"}supportsFormulaCopy(){return false}getNewTabUrl(){return "https://www.kimi.com/"}getSessionId(){const e=window.location.pathname;if("/chat/history"===e||e.startsWith("/chat/history/"))return "";const t=e.endsWith("/")?e:`${e}/`;if(hf.some(e=>t.startsWith(e)))return "";const n=e.match(df);if(n?.[1])return n[1];const r=e.match(uf);return r?.[1]||""}isNewConversation(){const e=window.location.pathname;return "/"===e||""===e||"/chat/history"===e||e.startsWith("/chat/history/")}isSharePage(){return window.location.pathname.startsWith("/share/")||window.location.pathname.startsWith("/kimiplus/")}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t||"Kimi"===t)return null;return t.replace(/^Kimi\s*\|\s*/i,"").replace(/\s*-\s*Kimi$/i,"").trim()||null}getCurrentCid(){try{for(let e=0;e{const r=this.extractConversationInfo(e,t);r&&n.push(r);}),this.mergeConversationInfos(n)}getConversationObserverConfig(){return {selector:wf,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(`${kf}, ${Sf}`)||e}}getSidebarScrollContainer(){const e=[document.querySelector(".history .group-list-container"),document.querySelector(xf),document.querySelector(".history .usage-content"),document.querySelector(".history .content"),document.querySelector(".history")].filter(Boolean);for(const t of e){const e=this.findScrollableParent(t);if(e)return e;if(t instanceof HTMLElement&&t.scrollHeight>t.clientHeight)return t}return null}async loadAllConversations(){await this.openMoreHistoryView();try{let e=0,t=0;const n=4;for(;tsetTimeout(e,500));const r=document.querySelectorAll(wf).length;r===e?t++:(e=r,t=0);}this.cacheFullListSnapshot(this.collectConversationListFromDom());}finally{await this.closeMoreHistoryView();}}async deleteConversationOnSite(e){const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),{id:e.id,success:false,method:"api",reason:Of};const n=this.getSessionId(),r=await this.deleteConversationViaApi(e,t);return r.success&&e.id===n&&this.navigateToHomeAfterDelete(),r}async deleteConversationsOnSite(e){if(0===e.length)return [];const t=this.getAuthToken();if(!t)return this.logMissingDeleteTokenOnce(),e.map(e=>({id:e.id,success:false,method:"api",reason:Of}));const n=this.getSessionId(),r=[],o=[];for(const i of e){const e=await this.deleteConversationViaApi(i,t);r.push(e),e.success&&o.push(i.id);}if(o.length>0){n&&o.includes(n)?this.navigateToHomeAfterDelete():this.scheduleReloadAfterBatchDelete();}return r}navigateToConversation(e,t){const n=this.buildConversationUrl(e,t),r=this.findConversationLinkById(e);if(r){const t=this.getSessionId();return r.click(),window.setTimeout(()=>{this.getSessionId()!==e&&this.getSessionId()===t&&this.navigateToKimiConversationRoute(n);},120),true}return !!this.navigateToKimiConversationRoute(n)||super.navigateToConversation(e,n)}getConversationTitle(){const e=document.querySelector(".chat-header-content h2")?.textContent?.trim();if(e)return e;const t=this.getActiveConversationLink();if(t){const e=this.extractConversationTitle(t);if(e)return e}const n=this.getSessionId();if(n){const e=this.findConversationLinkById(n);if(e){const t=this.extractConversationTitle(e);if(t)return t}}return null}getTextareaSelectors(){return ['.chat-input-editor[data-lexical-editor="true"]','.chat-input-editor[contenteditable="true"]','[role="textbox"].chat-input-editor']}isValidTextarea(e){return null!==e.offsetParent&&(!!e.isContentEditable&&(!e.closest(".gh-main-panel")&&!e.closest(".gh-queue-panel")&&!!e.closest(".chat-input-editor-container")))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),document.activeElement!==t&&!t.contains(document.activeElement))return false;if(this.insertByExecCommand(t,e))return true;return this.insertByPasteEvent(t,e)||(t.textContent=e,t.dispatchEvent(new Event("input",{bubbles:true})),t.dispatchEvent(new Event("change",{bubbles:true}))),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=()=>0===(e.textContent||"").replace(/[\u200b\u00a0]/g,"").trim().length,n=()=>{this.selectEditorAll(e);try{document.dispatchEvent(new Event("selectionchange"));}catch{}},r=t=>{try{e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,composed:!0,cancelable:!0,inputType:t}));}catch{}},o=(t,n,r)=>{e.dispatchEvent(new KeyboardEvent("keydown",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:t,code:n,keyCode:r,which:r,bubbles:true,cancelable:true,composed:true}));},i=()=>{if(e.isConnected){e.focus(),n(),r("deleteContentBackward");try{document.execCommand("delete",!1,void 0);}catch{}if(!t())try{document.execCommand("insertText",!1,"");}catch{}if(t()||o("Backspace","Backspace",8),t()||(r("deleteContentForward"),o("Delete","Delete",46)),t()||(()=>{try{const e=window.getSelection();if(!e||0===e.rangeCount)return;e.getRangeAt(0).deleteContents();}catch{}})(),!t()){this.clearByExecCommand(e)&&t()||(e.innerHTML="


");}(t=>{try{e.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,inputType:t}));}catch{e.dispatchEvent(new Event("input",{bubbles:true}));}})("deleteContentBackward"),e.dispatchEvent(new Event("change",{bubbles:true}));}};i();[30,120,240].forEach(n=>{setTimeout(()=>{e.isConnected&&(t()||i());},n);});}getSubmitButtonSelectors(){return [".send-button-container:not(.disabled):not(.stop)"]}findSubmitButton(e){const t=[e?.closest(".chat-editor"),e?.closest(".chat-input-editor-container"),e?.parentElement,document.body].filter(Boolean),n=new Set;for(const r of t){const e=r.querySelectorAll(".send-button-container");for(const t of Array.from(e)){const e=t;if(!n.has(e)&&(n.add(e),null!==e.offsetParent&&!e.classList.contains("disabled")&&!e.classList.contains("stop")))return e}}return null}getScrollContainer(){const e=document.querySelector(".share-detail");if(e&&e.scrollHeight>e.clientHeight)return e;const t=document.querySelector(".chat-detail-content");if(t&&t.scrollHeight>t.clientHeight)return t;const n=document.querySelector(".chat-content-container"),r=this.findScrollableParent(n);return r&&!r.closest(xf)?r:super.getScrollContainer()}getResponseContainerSelector(){return Af}getChatContentSelectors(){return [Rf,Df]}getUserQuerySelector(){return If}extractUserQueryText(e){const t=e.querySelector(".segment-content-box");return this.extractTextWithLineBreaks(t||e).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractKimiUserQueryExportContent(e)}replaceUserQueryContent(e,t){if(e.querySelector(".gh-user-query-markdown"))return false;const n=e.querySelector(".segment-content-box");if(!n)return false;const r=document.createElement("div");r.className=`${n.className} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t;const o=n.getAttribute("style");return o&&r.setAttribute("style",o),n.style.display="none",n.after(r),true}extractAssistantResponseText(e){const t=e.cloneNode(true);t.querySelectorAll(zf).forEach(e=>e.remove());const n=this.shouldIncludeThoughtsInExport()?this.extractThoughtBlockquotes(t):[];t.querySelectorAll(Pf).forEach(e=>e.remove());const r=this.findAssistantBodyMarkdownRoot(t);if(!r)return n.length>0?n.join("\n\n"):"";const o=(Fi(r)||this.extractTextWithLineBreaks(r)).trim();if(n.length>0){const e=n.join("\n\n");return o?`${e}\n\n${o}`:e}return o}getLatestReplyText(){const e=document.querySelectorAll(Rf);if(0===e.length)return null;const t=e[e.length-1];return this.extractAssistantResponseText(t)||null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(Af);if(!r)return [];const o=[],i=this.getChatItems(r);return i.forEach((r,a)=>{if(r.matches(Mf)||r.matches(If)||r.querySelector(If)){if(!t)return;const e=r.querySelector(If)||r,s=this.extractUserQueryMarkdown(e);if(!s)return;let l;if(n){const e=this.findNextAssistantMarkdown(i,a);l=e?.textContent?.trim().length||0;}return void o.push({level:0,text:s.length>80?`${s.slice(0,80)}...`:s,element:e,isUserQuery:true,isTruncated:s.length>80,wordCount:l})}if(!r.matches(_f)&&!r.matches(Lf)&&!r.querySelector(Rf))return;const s=this.findAssistantBodyMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6"));l.forEach((t,r)=>{const i=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(i)||i>e)return;const a=t.textContent?.trim()||"";if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractKimiExportMessages(e))}async prepareConversationExport(e){return this.exportIncludeThoughts=e.includeThoughts,null}async restoreConversationAfterExport(e,t){this.exportIncludeThoughts=void 0;}isGenerating(){const e=document.querySelectorAll(".send-button-container.stop");for(const n of Array.from(e))if(null!==n.offsetParent)return true;const t=document.querySelectorAll('.send-button-container svg[name="stop"]');for(const n of Array.from(t)){const e=n.closest(".send-button-container");if(e&&null!==e.offsetParent)return true}return false}getStopButtonSelectors(){return [".send-button-container.stop",'.send-button-container:has(svg[name="stop"])']}getModelName(){const e=document.querySelector(".current-model .model-name .name");return e?.textContent?.trim()||null}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".current-model.active .model-name",".current-model .model-name"],menuItemSelector:['[role="menuitem"]','[role="option"]',".n-base-select-option",".n-dropdown-option",".model-item",".model-option"].join(", "),checkInterval:1e3,maxAttempts:15,menuRenderDelay:350}}getNetworkMonitorConfig(){return {urlPatterns:["apiv2/kimi.gateway.chat.v1.ChatService/Chat"],silenceThreshold:2e3}}async toggleTheme(e){try{const t=JSON.stringify(e);localStorage.setItem(Bf,t);const n=document.documentElement;return n.classList.remove("light","dark"),n.classList.add(e),window.dispatchEvent(new StorageEvent("storage",{key:Bf,newValue:t,storageArea:localStorage})),!0}catch(t){return console.error("[KimiAdapter] toggleTheme error:",t),false}}getNewChatButtonSelectors(){return ["a.new-chat-btn",'a.new-chat-btn[href="/"]','a.new-chat-btn[href="https://www.kimi.com/"]']}getWidthSelectors(){return [{selector:".chat-detail-content",property:"width",value:"100%",noCenter:true,extraCss:"max-width: 100% !important; min-width: 0 !important;"},{selector:".chat-content-container",property:"max-width",extraCss:"width: 100% !important; min-width: 0 !important;"},{selector:Ef,property:"max-width",value:"100%",noCenter:true,extraCss:"width: 100% !important; min-width: 0 !important; padding-left: 0 !important; padding-right: 0 !important;"},{selector:Ef,property:"width",value:"100%",noCenter:true},{selector:".chat-editor",property:"max-width"}]}getUserQueryWidthSelectors(){const e=["margin-left: auto !important; margin-right: 0 !important;","max-width: 100% !important;","box-sizing: border-box !important;"].join(" "),t=["max-width: 100% !important;","margin-left: 0 !important;","margin-right: 0 !important;","box-sizing: border-box !important;"].join(" "),n=["max-width: 100% !important;","box-sizing: border-box !important;","overflow-wrap: anywhere !important;"].join(" ");return [{selector:Nf,property:"width",extraCss:e,noCenter:true},{selector:Df,property:"width",value:"100%",extraCss:t,noCenter:true},{selector:qf,property:"width",value:"100%",extraCss:n,noCenter:true}]}getZenModeConfig(){return {hide:[".sidebar-placeholder"],rootClass:{selector:".app.has-sidebar",className:"fold"}}}getCleanModeConfig(){return {hide:[".chat-bottom .legal-footer, .legal-footer",".membership-upgrade",".download-app-btn",".activity-area"]}}getMarkdownFixerConfig(){return {selector:".segment-assistant .markdown p",fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(".segment-assistant");if(!t)return false;const n=document.querySelectorAll(`${_f} .segment-assistant`);return t===n[n.length-1]}}}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];let n=false;for(const r of t)try{"function"==typeof PointerEvent?e.dispatchEvent(new PointerEvent(r,{bubbles:!0,cancelable:!0,pointerId:1})):e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{try{e.dispatchEvent(new MouseEvent(r,{bubbles:!0,cancelable:!0})),n=!0;}catch{}}n||e.click();}normalizeThemeStorageValue(){const e=localStorage.getItem(Bf);if(!e)return;const t=e.trim();if(t)if("light"!==t&&"dark"!==t)try{const e=JSON.parse(t);if("light"===e||"dark"===e)return}catch{}else localStorage.setItem(Bf,JSON.stringify(t));}async deleteConversationViaApi(e,t){try{const n=new URL("/apiv2/kimi.chat.v1.ChatService/DeleteChat",window.location.origin).toString(),r=await fetch(n,{method:"POST",headers:this.buildDeleteHeaders(t),body:JSON.stringify({chat_id:e.id}),credentials:"include"});if(!r.ok)return {id:e.id,success:!1,method:"api",reason:this.toDeleteApiHttpReason(r.status)};const o=await this.safeParseJson(r);return this.isDeleteSuccessPayload(o,e.id)?{id:e.id,success:!0,method:"api"}:{id:e.id,success:!1,method:"api",reason:this.toDeleteApiPayloadReason(o)}}catch{return {id:e.id,success:false,method:"api",reason:Ff}}}buildDeleteHeaders(e){const t=this.parseJwtPayload(e),n={accept:"*/*",authorization:`Bearer ${e}`,"connect-protocol-version":"1","content-type":"application/json","x-language":this.getClientLanguage(),"r-timezone":this.getClientTimezone(),"x-msh-platform":"web","x-msh-version":"1.0.0"},r="string"==typeof t.device_id?t.device_id.trim():"",o="string"==typeof t.ssid?t.ssid.trim():"",i="string"==typeof t.sub?t.sub.trim():"";return r&&(n["x-msh-device-id"]=r),o&&(n["x-msh-session-id"]=o),i&&(n["x-traffic-id"]=i),n}getAuthToken(){const e=this.getCookieToken(pf);if(e)return e;const t=this.findAuthTokenInStorage(localStorage);if(t)return t;try{const e=this.findAuthTokenInStorage(sessionStorage);if(e)return e}catch{}return null}getCookieToken(e){const t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=document.cookie.match(new RegExp(`(?:^|;\\s*)${t}=([^;]*)`));return n?.[1]?this.extractTokenFromRaw(n[1]):null}findAuthTokenInStorage(e){for(const t of mf){const n=e.getItem(t),r=this.extractTokenFromRaw(n);if(r)return r}for(let t=0;t6||null==e)return null;if("string"==typeof e)return this.extractTokenFromRaw(e);if(Array.isArray(e)){for(const r of e){const e=this.findTokenInUnknown(r,t+1,n);if(e)return e}return null}if("object"!=typeof e)return null;if(n.has(e))return null;n.add(e);const r=e;for(const o of ff){if(!(o in r))continue;const e=this.findTokenInUnknown(r[o],t+1,n);if(e)return e}for(const[o,i]of Object.entries(r)){if(ff.includes(o)||t>0&&!yf.test(o)&&"object"!=typeof i)continue;const e=this.findTokenInUnknown(i,t+1,n);if(e)return e}return null}logMissingDeleteTokenOnce(){this.loggedMissingDeleteToken||(this.loggedMissingDeleteToken=true,console.warn("[KimiAdapter] DeleteChat skipped: auth token not found in cookie/storage."));}parseJwtPayload(e){try{const t=e.split(".");if(t.length<2)return {};const n=t[1].replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(4*Math.ceil(n.length/4),"="),o=atob(r),i=JSON.parse(o);return i&&"object"==typeof i?i:{}}catch{return {}}}getClientLanguage(){return document.documentElement.lang||navigator.language||"en-US"}getClientTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return "UTC"}}isDeleteSuccessPayload(e,t){if(!e||"object"!=typeof e)return false;const n=e,r=n.chatId,o=n.chat_id;return r===t||o===t}toDeleteApiPayloadReason(e){if(!e||"object"!=typeof e)return $f;const t=e,n="string"==typeof t.message&&t.message.trim()||"string"==typeof t.msg&&t.msg.trim()||"string"==typeof t.error&&t.error.trim()||"";return n?`${Uf}:${n}`:Uf}toDeleteApiHttpReason(e){switch(e){case 401:case 403:return "delete_api_unauthorized";case 404:return "delete_api_not_found";case 429:return "delete_api_rate_limited";default:return `delete_api_http_${e||0}`}}async safeParseJson(e){try{return await e.json()}catch{return null}}scheduleReloadAfterBatchDelete(){this.deleteReloadScheduled||(this.deleteReloadScheduled=true,window.setTimeout(()=>{window.location.reload();},120));}navigateToHomeAfterDelete(){const e=window.location.pathname;"/"!==e&&""!==e?window.location.href=this.getNewTabUrl():this.scheduleReloadAfterBatchDelete();}extractConversationInfo(e,t){const n=e.getAttribute("href")||"",r=this.extractConversationIdFromHref(n);if(!r)return null;return {id:r,cid:t,title:this.extractConversationTitle(e),url:`https://www.kimi.com/chat/${r}`,isActive:e.classList.contains("router-link-active")||e.classList.contains("router-link-exact-active"),isPinned:!!e.querySelector("svg.pinned, .pinned")}}extractConversationTitle(e){const t=e.querySelector(kf)?.textContent?.trim()||e.querySelector(Sf)?.textContent?.trim()||"";if(t)return t;const n=e.textContent?.replace(/\s+/g," ").trim()||"";return n.length>120?`${n.slice(0,120)}...`:n}extractConversationIdFromHref(e){if(!e)return null;try{const t=new URL(e,window.location.origin).pathname.match(df);return t?t[1]:null}catch{return null}}buildConversationUrl(e,t){if(t)try{const n=new URL(t,window.location.origin);if(this.extractConversationIdFromHref(n.href)===e)return n.search||n.searchParams.set("chat_enter_method","history"),n.toString()}catch{}return new URL(`/chat/${e}?chat_enter_method=history`,window.location.origin).toString()}findConversationLinkById(e){const t=document.querySelectorAll(wf);for(const n of Array.from(t)){const t=n.getAttribute("href")||"";if(this.extractConversationIdFromHref(t)===e)return n}return null}navigateToKimiConversationRoute(e){let t;try{t=new URL(e,window.location.origin);}catch{return false}if(t.origin!==window.location.origin)return false;if(!this.extractConversationIdFromHref(t.href))return false;const n=`${t.pathname}${t.search}${t.hash}`;if(n===`${window.location.pathname}${window.location.search}${window.location.hash}`)return true;try{window.history.pushState(window.history.state,"",n);const e="function"==typeof PopStateEvent?new PopStateEvent("popstate",{state:window.history.state}):new Event("popstate");return window.dispatchEvent(e),!0}catch{return false}}findScrollableParent(e){let t=e;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if(("auto"===e.overflowY||"scroll"===e.overflowY)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}getActiveConversationLink(){const e=document.querySelector(`${vf}.router-link-active, ${vf}.router-link-exact-active`);if(e)return e;if("/"===window.location.pathname||""===window.location.pathname)return null;const t=this.getSessionId();return t?this.findConversationLinkById(t):null}isHistoryPath(e=window.location.pathname){return "/chat/history"===e||e.startsWith("/chat/history/")}async openMoreHistoryView(){if(this.isHistoryPath())return;const e=document.querySelector('a.more-history[href*="/chat/history"], a.nav-item.more-history[href*="/chat/history"]');if(!e)return;const t=window.location.pathname,n=document.querySelectorAll(vf).length;e.click();const r=Date.now()+3e3;for(;Date.now()n)return;await new Promise(e=>setTimeout(e,120));}}async closeMoreHistoryView(){if(!this.isHistoryPath())return;const e=document.querySelector([".header-right .close-button-container",".header-right .close-button",".history .header-right .close-button-container",".history .header-right .close-button"].join(", "));if(!e)return;const t=e.closest(".close-button-container")||e;if(this.simulateClick(t),!(await this.waitForHistoryClosed(900))&&(t.click(),!(await this.waitForHistoryClosed(1200)))){try{window.history.back();}catch{}await this.waitForHistoryClosed(1500);}}async waitForHistoryClosed(e){const t=Date.now()+e;for(;Date.now()setTimeout(e,80));}return !this.isHistoryPath()}cacheFullListSnapshot(e){e.length&&(this.fullListSnapshot=e.map(e=>({...e})),this.fullListSnapshotExpiresAt=Date.now()+15e3,this.fullListSnapshotUsesLeft=6);}getFreshFullListSnapshot(){if(!this.fullListSnapshot.length)return [];const e=Date.now()>this.fullListSnapshotExpiresAt,t=this.fullListSnapshotUsesLeft<=0;return e||t?(this.fullListSnapshot=[],this.fullListSnapshotExpiresAt=0,this.fullListSnapshotUsesLeft=0,[]):this.fullListSnapshot.map(e=>({...e}))}mergeConversationInfos(...e){const t=new Map;return e.forEach(e=>{e.forEach(e=>{const n=t.get(e.id);n?t.set(e.id,{...n,title:n.title||e.title,isActive:n.isActive||e.isActive,isPinned:n.isPinned||e.isPinned}):t.set(e.id,e);});}),Array.from(t.values())}selectEditorAll(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.selectNodeContents(e),t.removeAllRanges(),t.addRange(n);}insertByExecCommand(e,t){try{this.selectEditorAll(e);if(document.execCommand("insertText",!1,t))return !0}catch{}return false}insertByPasteEvent(e,t){try{if("undefined"==typeof DataTransfer)return !1;const n=e.textContent||"",r=new DataTransfer;r.setData("text/plain",t);if(!e.dispatchEvent(new ClipboardEvent("paste",{clipboardData:r,bubbles:!0,cancelable:!0,composed:!0})))return !0;return (e.textContent||"")!==n||0===t.length}catch{return false}}clearByExecCommand(e){try{return this.selectEditorAll(e),document.execCommand("delete",!1,void 0)}catch{return false}}extractKimiExportMessages(e){const t=document.querySelector(Af);if(!t)return [];const n=[],r=this.getChatItems(t);for(const o of r){const t=this.findKimiUserMessageRoot(o);if(t){const r=this.extractKimiUserQueryExportContent(t,e).trim();r&&n.push({role:"user",content:r});continue}const r=this.findKimiAssistantMessageRoot(o);if(r){const e=this.extractAssistantResponseText(r).trim();e&&n.push({role:"assistant",content:e});}}return n}findKimiUserMessageRoot(e){return e.matches(If)?e:e.querySelector(If)}findKimiAssistantMessageRoot(e){if(e.matches(Lf))return e;const t=e.querySelector(Lf);if(t)return t;const n=this.findAssistantBodyMarkdownRoot(e);return n?.closest(Lf)||null}extractKimiUserQueryExportContent(e,t){const n=this.extractKimiUserImageMarkdown(e,t),r=this.extractKimiUserFileMarkdown(e,t),o=this.extractKimiUserBodyMarkdown(e);if(0===n.length&&0===r.length)return o;const i=r.length>0?`${se("exportAttachmentsLabel")}:\n${r.join("\n")}`:"";return [n.join("\n\n"),i,o].filter(Boolean).join("\n\n")}extractKimiUserBodyMarkdown(e){const t=e.cloneNode(true);t.querySelectorAll(".attachment-list").forEach(e=>e.remove()),t.querySelectorAll(zf).forEach(e=>e.remove());const n=t.querySelector(".segment-content-box");return this.extractTextWithLineBreaks(n||t).trim()}extractKimiUserImageMarkdown(e,t){const n=Array.from(e.querySelectorAll(".attachment-list-image img, .image-thumbnail img.image-main, .image-wrapper img.image-main")).filter(e=>e instanceof HTMLImageElement),r=new Set,o=[];for(const i of n){const e=this.getKimiImageExportSource(i);if(!e||r.has(e))continue;r.add(e);const n=this.extractKimiImageAlt(i,e),a=Ta({source:e,alt:n,extensionHint:n},t,{siteId:this.getSiteId(),role:"user",category:"image",fallbackAlt:"uploaded image"});a&&o.push(a);}return o}getKimiImageExportSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||""];for(const n of t){const e=fa(n);if(e&&(!e.startsWith("data:image/svg+xml")&&ba(e)))return e}return ""}extractKimiImageAlt(e,t){return [e.alt||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",this.extractKimiFilenameFromUrl(t),"uploaded image"].map(e=>e.replace(/\s+/g," ").trim()).find(Boolean)||"uploaded image"}extractKimiUserFileMarkdown(e,t){const n=Array.from(e.querySelectorAll(".attachment-list-file .file-card-container")),r=new Set,o=[];for(const i of n){const e=this.extractKimiFileName(i);if(!e)continue;const n=this.extractKimiFileType(i),a=this.extractKimiFileSize(i),s=this.formatKimiFileLabel(e,n,a),l=Ia([{kind:"file",name:e,source:this.extractKimiFileHref(i),type:n,sizeLabel:a}],t,{siteId:this.getSiteId(),getLabel:()=>s})[0];r.has(l)||(r.add(l),o.push(l));}return o}extractKimiFileName(e){const t=[e.querySelector(".file-card-info-name")?.textContent||"",e.getAttribute("download")||"",e.getAttribute("title")||"",e.getAttribute("aria-label")||"",e.textContent||""].map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=t.find(e=>/[^/\\]+\.[A-Za-z0-9]{1,10}(\s|$)/.test(e));return n?n.match(/[^/\\]+?\.[A-Za-z0-9]{1,10}/)?.[0]||"":t[0]||""}extractKimiFileType(e){return e.querySelector(".file-ext")?.textContent?.replace(/\s+/g," ").trim()||""}extractKimiFileSize(e){return e.querySelector(".file-size")?.textContent?.replace(/\s+/g," ").trim()||""}formatKimiFileLabel(e,t,n){const r=[t&&!this.fileNameEndsWithExtension(e,t)?t:"",n].filter(Boolean);return r.length>0?`${e} (${r.join(", ")})`:e}fileNameEndsWithExtension(e,t){const n=t.toLowerCase().replace(/^\./,"").trim();return !!n&&e.toLowerCase().endsWith(`.${n}`)}extractKimiFileHref(e){const t=Array.from(e.querySelectorAll("a[href]")),n=e.closest("a[href]");n&&t.unshift(n);for(const r of t){if(!(r instanceof HTMLAnchorElement))continue;const e=fa(r.getAttribute("href")||r.href||"");if(ba(e))return e}return ""}extractKimiFilenameFromUrl(e){try{const t=new URL(e,window.location.href),n=t.searchParams.get("filename");if(n?.trim())return n.trim();const r=decodeURIComponent(t.pathname);return r.split("/").pop()?.trim()||""}catch{return ""}}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}findAssistantBodyMarkdownRoot(e){if(e.matches(".markdown")&&!this.isInsideAssistantToolcall(e))return e;const t=e.querySelector(Rf);return t&&!this.isInsideAssistantToolcall(t)?t:Array.from(e.querySelectorAll(".markdown")).find(e=>!this.isInsideAssistantToolcall(e))||null}isInsideAssistantToolcall(e){return null!==e.closest(Pf)||null!==e.closest(".markdown-container.toolcall-content-text")}extractThoughtBlockquotes(e){const t=this.collectTopLevelBlocks(Array.from(e.querySelectorAll(".toolcall-container.thinking-container, .thinking-container"))),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(zf).forEach(e=>e.remove());const t=Array.from(e.querySelectorAll(".markdown")),o=(t.length>0?t.map(e=>Fi(e)||this.extractTextWithLineBreaks(e)).join("\n\n"):Fi(e)||this.extractTextWithLineBreaks(e)).trim();o&&n.push(this.formatAsThoughtBlockquote(o));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}getChatItems(e){const t=Array.from(e.querySelectorAll(Tf)).filter(e=>!e.parentElement?.closest(Tf));return t.length>0?t:Array.from(e.children).filter(e=>e.matches(Mf)||e.matches(_f)||e.matches(If)||e.matches(Lf)||null!==e.querySelector(If)||null!==e.querySelector(Rf))}findNextAssistantMarkdown(e,t){for(let n=t+1;nt.id===e);if(t?.title)return t.title;this.refreshConversationSnapshot();}return this.getSessionName()}getConversationList(){const e=this.collectConversationListFromDom(),t=this.getFreshConversationSnapshot();return 0===e.length?(0===t.length&&this.refreshConversationSnapshot(),t):0===t.length?(this.refreshConversationSnapshot(),e):this.mergeConversationInfos(t,e)}getConversationObserverConfig(){return {selector:yb,shadow:false,extractInfo:e=>this.extractSidebarConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(vb)||e}}getSidebarScrollContainer(){return document.querySelector(`${fb} ${bb}`)||document.querySelector(bb)||document.querySelector(fb)}async loadAllConversations(){await this.refreshConversationSnapshot({force:true,fetchAllPages:true});}navigateToConversation(e,t){const n=this.getCurrentCid()||void 0,r=document.querySelectorAll(yb);for(const o of Array.from(r)){const t=this.extractSidebarConversationInfo(o,n);if(!t||t.id!==e)continue;const r=o.querySelector("a, button, [role='button']")||o;return this.simulateClick(r),true}return super.navigateToConversation(e,t||`https://chat.qwen.ai/c/${e}`)}getTextareaSelectors(){return ["textarea.message-input-textarea","textarea"]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${Eb}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Eb);return this.isVisibleActionElement(e)?e.hasAttribute("disabled")||this.isStopLikeButton(e)?null:e:null}getNewChatButtonSelectors(){return [".sidebar-entry-fixed-list-content"]}getScrollContainer(){const e=document.querySelector(wb);return e instanceof HTMLElement?e:null}getResponseContainerSelector(){return xb}getAssistantMermaidSupportMode(){return "native"}extractFormulaCopySource(e,t){const n=e.closest(Qb)||t.closest(Qb);if(!n)return null;const r=n.querySelector("math");if(!r)return null;const o=this.extractQwenLatexFromMath(r),i=this.serializeQwenMathml(r);return o||i?{latex:o,mathml:i,isBlock:!!n.closest(".katex-display")||"block"===r.getAttribute("display")}:null}getChatContentSelectors(){return [kb,Sb]}getUserQuerySelector(){return kb}getLatestReplyText(){const e=document.querySelectorAll(Sb),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}extractAssistantMarkdown(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=this.shouldIncludeThoughtsInExport(),r=n?this.getThoughtBlocksForElement(e):[],o=t.cloneNode(true);this.normalizeQwenCodeBlocks(o),o.querySelectorAll(`${Pb}, ${Ob}`).forEach(e=>e.remove());const i=(Fi(o)||this.extractTextWithLineBreaks(o)).trim();if(n&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatQwenAssistantImages(this.extractQwenAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}getLastCodeBlockText(){const e=document.querySelectorAll(Sb);for(let t=e.length-1;t>=0;t-=1){const n=this.findAssistantContentRoot(e[t]);if(!n)continue;const r=Array.from(n.querySelectorAll(Mb));for(let e=r.length-1;e>=0;e-=1){const t=this.extractQwenCodeBlockText(r[e]);if(t)return t}}return super.getLastCodeBlockText()}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(xb)||document.querySelector(wb);if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${kb}, ${Sb}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(kb)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Sb));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(Nb)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t!e.closest(".gh-root"));for(const r of n)await this.captureThoughtBlocksForMessage(r);return {shouldCloseThoughtPanel:!t&&null!==this.getVisibleThoughtPanel()}}async restoreConversationAfterExport(e,t){try{this.parseThoughtExportState(t)?.shouldCloseThoughtPanel&&await this.closeThoughtPanelIfNeeded(),await this.restoreMermaidBlocksAfterExport();}finally{this.exportIncludeThoughtsOverride=null,this.clearThoughtExportCache();}}async extractExportMessages(e){const t=this.extractQwenExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractQwenExportMessages(e))}async toggleTheme(e){try{const t=this.resolveThemeMode(e);return !!(await this.updateThemePreference(e))&&(this.syncThemeState(t,e),!0)}catch(t){return console.error("[QwenAiAdapter] toggleTheme error:",t),false}}getModelName(){const e=document.querySelector(Ub),t=e?.innerText?.trim()||e?.textContent?.trim()||"";return t?t.split("\n")[0].trim():null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}clickModelSelector(){const e=this.findModelTrigger();return !!e&&(this.simulateClick(e),true)}lockModel(e,t){const n=this.normalizeModelKeyword(e);if(!n)return;let r=0;const o=async()=>{r++;const i=this.findModelTrigger();if(!i)return r>=12?void this.showQwenModelLockFailure(e,"button_not_found"):void window.setTimeout(o,1e3);if(this.normalizeModelKeyword(this.getModelLockCheckText(i)).includes(n))return void t?.();const a=await this.selectQwenModel(n);a.success?t?.():this.showQwenModelLockFailure(e,a.reason||"not_found");};o();}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[$b,Ub],menuItemSelector:Gb,checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:Wb,subMenuTriggers:["展开更多模型","更多模型","view more","more models"]}}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [...Tb]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/v2/chat/completions"],urlPathEndsWith:["/chat/completions"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:".qwen-chat-message",property:"max-width",extraCss:"width: 100% !important; box-sizing: border-box !important;"},{selector:".message-input-wrapper",property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:".chat-user-message-container .chat-user-message-wrapper .chat-user-message",property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:[fb]}}getCleanModeConfig(){return {hide:[".chat-container-statement"]}}getMarkdownFixerConfig(){return {selector:`${Sb} .qwen-markdown-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(Sb);if(!t)return false;const n=document.querySelectorAll(Sb);return t===n[n.length-1]}}}getFreshConversationSnapshot(){return this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4||this.conversationSnapshotPromise||this.refreshConversationSnapshot(),this.conversationSnapshot.map(e=>({...e}))}async refreshConversationSnapshot(e={}){const{force:t=false,fetchAllPages:n=false}=e,r=this.conversationSnapshot.length>0&&Date.now()-this.conversationSnapshotFetchedAt<3e4;return !t&&r?this.conversationSnapshot.map(e=>({...e})):(this.conversationSnapshotPromise||(this.conversationSnapshotPromise=(async()=>{try{const e=await this.fetchConversationSnapshot(n);e.length>0&&(this.conversationSnapshot=e,this.conversationSnapshotFetchedAt=Date.now());}catch(e){console.warn("[QwenAiAdapter] Failed to refresh conversation snapshot:",e);}finally{this.conversationSnapshotPromise=null;}return this.conversationSnapshot.map(e=>({...e}))})()),this.conversationSnapshotPromise)}async fetchConversationSnapshot(e){const t=this.getSessionId(),n=e?100:5,r=[],o=new Set;for(let i=1;i<=n;i++){const n=await this.fetchConversationPage(i);if(0===n.length)break;let a=0;for(const e of n)o.has(e.id)||(o.add(e.id),r.push(e),a++);if(0===a)break;if(!e&&t&&o.has(t))break}return r}async fetchConversationPage(e){const t=new URL("/api/v2/chats/",window.location.origin);t.searchParams.set("page",String(e)),t.searchParams.set("exclude_project","true");const n=await fetch(t.toString(),{method:"GET",credentials:"include",cache:"no-store",headers:{Accept:"application/json, text/plain, */*","X-Request-Id":crypto.randomUUID(),source:"web"}});if(!n.ok)throw new Error(`fetch conversations failed: ${n.status}`);const r=await n.json();if(false===r.success)return [];const o=Array.isArray(r.data)?r.data:[],i=this.getCurrentCid()||void 0,a=[];return o.forEach(e=>{const t=this.normalizeConversationApiItem(e,i);t&&a.push(t);}),a}normalizeConversationApiItem(e,t){if(!e||"object"!=typeof e)return null;const n=e,r="string"==typeof n.id?n.id.trim():"",o="string"==typeof n.title?n.title.trim():"";return r&&o?{id:r,cid:t,title:o,url:`https://chat.qwen.ai/c/${r}`,isPinned:Boolean(n.pinned),isActive:r===this.getSessionId()}:null}collectConversationListFromDom(){const e=document.querySelectorAll(yb);if(0===e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractSidebarConversationInfo(e,t);r&&n.push(r);}),n}extractSidebarConversationInfo(e,t){const n=this.extractConversationIdFromElement(e);if(!n)return null;const r=e.querySelector(vb),o=r?.textContent?.trim()||"";return o?{id:n,cid:t,title:o,url:`https://chat.qwen.ai/c/${n}`,isPinned:!!e.querySelector(".chat-item-title-pined-icon"),isActive:n===this.getSessionId()}:null}extractConversationIdFromElement(e){const t=e.querySelector('a[href*="/c/"]'),n=t?.getAttribute("href"),r=this.extractConversationIdFromText(n);if(r)return r;const o=[e,...Array.from(e.querySelectorAll("*"))];for(const i of o){const e=i.getAttributeNames?.()||[];for(const t of e){const e=i.getAttribute(t),n=this.extractConversationIdFromText(e);if(n)return n}}return null}extractQwenLatexFromMath(e){return Array.from(e.childNodes).filter(e=>e.nodeType===Node.TEXT_NODE).map(e=>e.textContent?.trim()||"").filter(Boolean).join(" ").trim()}serializeQwenMathml(e){const t=e.cloneNode(true);Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.TEXT_NODE&&e.remove();});try{return (new XMLSerializer).serializeToString(t).trim()}catch{return t instanceof HTMLElement?t.outerHTML.trim():""}}extractConversationIdFromText(e){if(!e)return null;const t=e.match(pb);if(t?.[1])return t[1];const n=e.match(/\b[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\b/i);return n?.[0]||null}mergeConversationInfos(...e){const t=new Map;for(const n of e)for(const e of n){const n=t.get(e.id);t.set(e.id,{...n,...e});}return Array.from(t.values())}extractQwenExportMessages(e){const t=this.getQwenExportRoot();return this.getOrderedQwenMessages(t).map(({role:t,element:n})=>({role:t,content:("user"===t?this.extractUserQueryExportContentWithAssets(n,e):this.extractAssistantResponseTextWithAssets(n,e)).trim()})).filter(e=>e.content.length>0)}getQwenExportRoot(){return document.querySelector(xb)||document.querySelector(wb)||document.body}getOrderedQwenMessages(e){const t=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,kb)).filter(e=>!this.shouldSkipExportElement(e)),n=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,Sb)).filter(e=>!this.shouldSkipExportElement(e));return [...t.map(e=>({role:"user",element:e})),...n.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element))}extractUserQueryExportContentWithAssets(e,t){const n=this.extractQwenUserTextParts(e).join("\n\n").trim()||this.extractUserQueryText(e),r=this.extractQwenUserAttachments(e);if(0===r.length)return n;const o=this.formatQwenUserImageAttachments(r,t),i=this.formatQwenUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractQwenUserTextParts(e){const t=this.findUserMessageScope(e),n=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,Cb)),r=[],o=new Set;return n.forEach(e=>{if(e.closest(".gh-user-query-markdown"))return;const t=e.cloneNode(true);t.querySelectorAll(Pb).forEach(e=>e.remove());const n=this.extractTextWithLineBreaks(t).trim();n&&!o.has(n)&&(o.add(n),r.push(n));}),r}extractQwenUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getQwenAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,zb)).forEach(e=>o(this.extractQwenUserImageAttachment(e))),this.collectTopLevelBlocks(this.queryElementsIncludingSelf(t,".fileitem-btn, [class*='file-message-document'], .file-content-info")).forEach(e=>o(this.extractQwenUserFileAttachment(e))),n}extractQwenUserImageAttachment(e){const t=e instanceof HTMLImageElement?e:e.querySelector("img");if(!(t instanceof HTMLImageElement))return null;const n=this.extractQwenImageSource(t);if(!n)return null;const r=t.alt?.trim()||t.getAttribute("title")?.trim()||da(n)||"uploaded image";return {kind:"image",name:r,source:n,type:ua(r)||ha(n)||"image"}}extractQwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=ga(t),i=this.extractQwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||da(i)||"attachment";return {kind:"file",name:a,source:i,type:r||ua(a)||ha(i),sizeLabel:o}}formatQwenUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatQwenUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId()})}extractQwenAssistantImages(e){const t=e.closest(Sb)||e,n=[],r=new Set;return this.queryElementsIncludingSelf(t,Bb).forEach(e=>{if(!(e instanceof HTMLImageElement))return;if(e.closest(".gh-root, .gh-user-query-markdown"))return;if(e.closest(".response-message-footer, .copy-response-button"))return;const t=this.extractQwenImageSource(e);t&&!r.has(t)&&(r.add(t),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`}));}),n}formatQwenAssistantImages(e,t){return Ma(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}findUserMessageScope(e){const t=e.closest(".qwen-chat-message-user");return t||(e.matches(kb)?e:e.closest(kb)||e)}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractQwenImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeQwenExportSource(n,{allowDataImage:true});if(e)return this.preferOriginalQwenImageUrl(e)}return ""}extractQwenDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractQwenImageSource(e)),Fb.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeQwenExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeQwenExportSource(e,t){const n=e.trim();if(!n||n.startsWith("#")||/^javascript:/i.test(n))return "";const r=fa(n);if(!r)return "";if(/^data:image\/svg\+xml/i.test(r))return "";if(/^data:image\//i.test(r))return t.allowDataImage?r:"";if(/^data:/i.test(r))return r;if(!ba(r))return "";try{const e=new URL(r,window.location.href);if(e.hostname===window.location.hostname&&(pb.test(e.pathname)||/^\/(?:c|s)(?:\/|$)/i.test(e.pathname)))return "";if(/^img\.alicdn\.com$/i.test(e.hostname)&&/\.(?:apng|svg)(?:$|[?#])/i.test(e.pathname))return "";if(/\/(?:static|assets)\//i.test(e.pathname)&&!/\.(png|jpe?g|webp|gif|avif|pdf|docx?|xlsx?|pptx?|json|txt|csv)(?:$|[?#])/i.test(e.pathname))return ""}catch{return ""}return r}preferOriginalQwenImageUrl(e){if(!/^https?:\/\//i.test(e))return e;try{const t=new URL(e);if(t.searchParams.has("x-oss-process"))return t.searchParams.delete("x-oss-process"),t.toString()}catch{return e}return e}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getQwenAttachmentKeys(e){const t=ca(e.source),n=e.name.trim().toLowerCase(),r=e.type.trim().toLowerCase(),o=e.sizeLabel?.trim().toLowerCase()||"";return t?[`${e.kind}:source:${t}`]:[`${e.kind}:meta:${n}:${r}:${o}`]}normalizeQwenCodeBlocks(e){Array.from(e.querySelectorAll(Mb)).forEach(e=>{const t=this.extractQwenCodeBlockText(e);if(!t)return;const n=this.extractQwenCodeLanguage(e),r=document.createElement("pre"),o=document.createElement("code");n&&(o.className=`language-${n}`),o.textContent=t,r.appendChild(o),e.replaceWith(r);});}extractQwenCodeBlockText(e){const t=this.extractQwenMermaidSource(e);if(t)return t;const n=Array.from(e.querySelectorAll(".view-lines .view-line")).map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(n.length>0){const e=n.join("\n").replace(/\n+$/,"");return e.trim()?e:null}const r=e.querySelector(".qwen-markdown-code-body")||e.querySelector("[data-mode-id]")||e,o=this.normalizeQwenCodeLineText(r.textContent||"");return o.trim()?o:null}extractQwenMermaidSource(e){if(!this.isQwenMermaidCodeBlock(e))return null;const t=[],n=e=>{e&&(t.includes(e)||t.push(e));},r=e.querySelector(".qwen-markdown-code-body.mermaid");n(r),Array.from(e.querySelectorAll(".qwen-markdown-code-body.mermaid > div")).forEach(e=>n(e)),Array.from(e.querySelectorAll("[data-mode-id='mermaid']")).forEach(e=>n(e));let o=null;for(const i of t){const e=this.extractQwenCodeLinesFromRoot(i);e&&((!o||e.length>o.length)&&(o=e));}return o}isQwenMermaidCodeBlock(e){if("mermaid"===this.extractQwenCodeHeaderLabel(e).toLowerCase())return true;const t=e.querySelector(".qwen-markdown-code-body");return !!t?.classList.contains("mermaid")||null!==e.querySelector(".qwen-markdown-mermaid-chart-wrapper")}extractQwenCodeLanguage(e){const t=this.extractQwenCodeHeaderLabel(e).toLowerCase();if(t)return t;const n=e.querySelector(".qwen-markdown-code-body");if(!n)return "";const r=Array.from(n.classList).find(e=>"qwen-markdown-code-body"!==e&&!["monaco","editor","body"].includes(e.toLowerCase()));return r?.trim().toLowerCase()||""}extractQwenCodeHeaderLabel(e){const t=e.querySelector(".qwen-markdown-code-header");if(!t)return "";const n=Array.from(t.children);for(const o of n){if(!(o instanceof HTMLElement))continue;if(o.classList.contains("qwen-markdown-code-header-actions"))continue;const e=o.textContent?.trim()||"";if(e)return e}const r=t.firstElementChild;return r?.textContent?.trim()||""}extractQwenCodeLinesFromRoot(e){const t=Array.from(e.querySelectorAll(".view-lines .view-line"));if(0===t.length)return null;const n=t.map(e=>this.normalizeQwenCodeLineText(e.textContent||"")).filter((e,t,n)=>!(t===n.length-1&&""===e&&n.length>1));if(0===n.length)return null;const r=n.join("\n").replace(/\n+$/,"");return r.trim()?r:null}normalizeQwenCodeLineText(e){return e.replace(/\u00a0/g," ").replace(/\u200b/g,"").replace(/\r\n/g,"\n").replace(/\n/g,"").replace(/\s+$/g,"")}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}getThoughtBlocksForElement(e){const t=e.closest(Sb);return this.exportThoughtBlocks.get(e)||(t?this.exportThoughtBlocks.get(t):void 0)||[]}clearThoughtExportCache(){this.exportThoughtBlocks=new WeakMap;}async prepareMermaidBlocksForExport(){this.clearMermaidExportMarkers();const e=Array.from(document.querySelectorAll(Mb)).filter(e=>this.isQwenMermaidCodeBlock(e));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.getQwenMermaidActiveView(t),n=this.findQwenMermaidViewTab(t,"code"),r=this.findQwenMermaidViewTab(t,"preview");if("code"!==e&&n){try{n.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(n);}let o=await this.waitForMermaidCodeViewReady(t);!o&&"code"===e&&r&&n&&(this.simulateClick(r),await this.sleep(100),this.simulateClick(n),o=await this.waitForMermaidCodeViewReady(t)),o&&"code"!==e&&t.setAttribute(Lb,"true");}}async restoreMermaidBlocksAfterExport(){const e=Array.from(document.querySelectorAll(`${Mb}[${Lb}]`));for(const t of e){if(!(t instanceof HTMLElement))continue;const e=this.findQwenMermaidViewTab(t,"preview");e&&"preview"!==this.getQwenMermaidActiveView(t)&&(this.simulateClick(e),await this.sleep(80)),t.removeAttribute(Lb);}}clearMermaidExportMarkers(){document.querySelectorAll(`${Mb}[${Lb}]`).forEach(e=>e.removeAttribute(Lb));}getQwenMermaidActiveView(e){const t=e.querySelector(_b);if(!(t instanceof HTMLElement))return null;const n=Array.from(t.querySelectorAll(Ib));for(const r of n){if(!(r instanceof HTMLElement))continue;const e=r.textContent?.trim().toLowerCase()||"";if(e&&r.className.includes("switch-active")){if(e.includes("code"))return "code";if(e.includes("preview"))return "preview"}}return null}findQwenMermaidViewTab(e,t){const n=e.querySelector(_b);if(!(n instanceof HTMLElement))return null;const r=Array.from(n.querySelectorAll(Ib));for(const o of r){if(!(o instanceof HTMLElement))continue;if((o.textContent?.trim().toLowerCase()||"").includes(t))return o}return null}async waitForMermaidCodeViewReady(e,t=2200){const n=Date.now();let r="",o=0;const i=this.getQwenMermaidExpectedLineCount(e);for(;Date.now()-nr.length?(r=t,o=0):t.length>0&&(o+=1);const n=r?r.split("\n").length:0;if((i>1?n>=i:n>0)&&o>=2)return true}await this.sleep(80);}const a=r?r.split("\n").length:0;return i>1?a>=i:r.length>0}getQwenMermaidExpectedLineCount(e){const t=Array.from(e.querySelectorAll(".margin-view-overlays .line-numbers")).map(e=>parseInt(e.textContent?.trim()||"",10)).filter(e=>Number.isFinite(e)&&e>0);return 0===t.length?0:Math.max(...t)}parseThoughtExportState(e){if(!e||"object"!=typeof e)return null;return {shouldCloseThoughtPanel:Boolean(e.shouldCloseThoughtPanel)}}async captureThoughtBlocksForMessage(e){const t=this.findThoughtTriggerForMessage(e);if(!t)return;const n=this.getThoughtPanelSignature();try{t.scrollIntoView({block:"center",behavior:"auto"});}catch{}this.simulateClick(t);const r=await this.waitForThoughtPanelUpdate(n)||this.getVisibleThoughtPanel();if(!r||!this.isThoughtPanelForMessage(r,e))return;const o=this.extractThoughtBlockquotesFromPanel(r);o.length>0&&this.exportThoughtBlocks.set(e,o),await this.sleep(60);}findThoughtTriggerForMessage(e){const t=Array.from(e.querySelectorAll(".qwen-chat-thinking-tool-status-card-wraper .qwen-chat-tool-status-card, .qwen-chat-thinking-tool-status-card-wraper .qwen-chat-thinking-status-card-completed"));for(const n of t){if(!(n instanceof HTMLElement))continue;if(!this.isQwenElementVisible(n))continue;const e=n.querySelector(Db)?.textContent?.trim()||n.textContent?.trim()||"";if(e&&/已.*完成思考|已经完成思考/i.test(e))return n}return null}isThoughtPanelForMessage(e,t){const n=this.extractQwenAssistantMessageId(t);if(!n)return true;const r=Array.from(e.querySelectorAll("[data-phase-id]")).map(e=>e.getAttribute("data-phase-id")?.trim()||"").filter(Boolean);return 0===r.length||r.some(e=>e.includes(n))}extractQwenAssistantMessageId(e){const t=[e.id||"",e.querySelector("[id^='chat-response-message-']")?.id||"",e.querySelector("[id^='qwen-chat-message-assistant-']")?.id||""];for(const n of t){const e=n.match(/(?:qwen-chat-message-assistant|chat-response-message)-(.+)$/);if(e?.[1])return e[1]}return ""}getVisibleThoughtPanel(){const e=document.querySelectorAll(qb);for(const t of Array.from(e))if(this.isQwenElementVisible(t))return t;return null}getThoughtPanelSignature(e){const t=e||this.getVisibleThoughtPanel();if(!t)return null;const n=Array.from(t.querySelectorAll("[data-phase-id]")).map(e=>e.getAttribute("data-phase-id")?.trim()||"").filter(Boolean);if(n.length>0)return n.join("|");const r=this.extractThoughtBlockquotesFromPanel(t);return 0===r.length?null:r.join("\n\n")}async waitForThoughtPanelUpdate(e,t=2200){const n=Date.now();for(;Date.now()-ne.remove());const i=(Fi(n)||this.extractTextWithLineBreaks(n)).trim();i&&r.push(this.formatAsThoughtBlockquote(i,t));}return r}formatAsThoughtBlockquote(e,t){const n=e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">"),r=(t||"").trim();return ["> [Thoughts]",...r&&!/已.*完成思考|已经完成思考/i.test(r)?[`> **${r}**`,">"]:[],...n].join("\n")}async closeThoughtPanelIfNeeded(e=1500){const t=this.getVisibleThoughtPanel();if(!t)return;const n=t.querySelector(".qwen-chat-thinking-and-sources-header .anticon, .qwen-chat-thinking-and-sources-header [role='img']");if(!n||!this.isQwenElementVisible(n))return;this.simulateClick(n);const r=Date.now();for(;Date.now()-r [class*="model-item___"]')).filter(e=>e instanceof HTMLElement&&this.isQwenElementVisible(e))}findBestQwenModelItem(e,t){const n=this.normalizeModelKeyword(t);if(!n)return null;for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r))===n)return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).endsWith(n))return r}for(const r of e){if(this.normalizeModelKeyword(this.getQwenModelItemName(r)).includes(n))return r}return null}getQwenModelItemName(e){return ((e.querySelector('[class*="model-item-name"] > span')||e.querySelector('[class*="model-item-name"]')||e).textContent||"").trim()}findQwenMoreTrigger(e){const t=e.querySelector(Wb);return t instanceof HTMLElement&&this.isQwenElementVisible(t)?t:null}async openQwenMoreMenu(e){const t=[e];[e.querySelector('[class*="view-more___"]'),e.querySelector('[class*="view-more-text"]'),e.querySelector('[class*="view-more-icon"]')].forEach(e=>{e instanceof HTMLElement&&!t.includes(e)&&t.push(e);});for(const n of t){this.dispatchQwenMoreMenuHover(n);let t=await this.waitForVisibleQwenSecondaryPopup(e,3,100);if(t)return t;if(this.simulateClick(n),t=await this.waitForVisibleQwenSecondaryPopup(e,4,120),t)return t}return this.waitForVisibleQwenSecondaryPopup(e,4,150)}async waitForVisibleQwenSecondaryPopup(e,t=8,n=150){for(let r=0;r{try{if(t.startsWith("pointer")&&"undefined"!=typeof PointerEvent)return void e.dispatchEvent(new PointerEvent(t,{...n,pointerType:"mouse",isPrimary:!0}));e.dispatchEvent(new MouseEvent(t,n));}catch{}});}clickQwenModelItem(e){this.simulateClick(e),window.setTimeout(()=>{document.body.click();},100);}normalizeModelKeyword(e){return (e||"").toLowerCase().replace(/\s+/g," ").trim()}isQwenElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}sleep(e){return new Promise(t=>window.setTimeout(t,e))}async showQwenModelLockFailure(e,t){try{const{showToast:n}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Di);return {showToast:e}},void 0),{t:o}=await r(async()=>{const{t:e}=await Promise.resolve().then(()=>de);return {t:e}},void 0);let i;switch(t){case "button_not_found":i=o("modelLockFailedNoButton");break;case "menu_empty":i=o("modelLockFailedMenuEmpty");break;default:i=o("modelLockFailedNotFound").replace("{model}",e);}n(i,3e3);}catch(n){console.error("[QwenAiAdapter] Failed to show model lock error:",n);}}readCookieValue(e){const t=new RegExp(`(?:^|; )${e}=([^;]+)`),n=document.cookie.match(t);if(!n?.[1])return null;try{return decodeURIComponent(n[1]).trim()||null}catch{return n[1].trim()||null}}extractUidFromToken(e){if(!e)return null;try{const t=e.split(".")[1];if(!t)return null;const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(n.padEnd(4*Math.ceil(n.length/4),"=")),o=JSON.parse(r).id;return "string"==typeof o&&o.trim()?o.trim():null}catch{return null}}findUserContentRoot(e){return e.matches(Cb)?e:e.querySelector(Cb)||e}findAssistantContentRoot(e){return e.matches(Ab)?e:e.querySelector(Ab)||e}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return this.normalizeQwenCodeBlocks(n),n.querySelectorAll(`${Nb}, ${Rb}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}findModelTrigger(){const e=document.querySelector($b);if(e instanceof HTMLElement&&this.isVisibleActionElement(e))return e;const t=document.querySelector(Ub);if(!t)return null;const n=t.closest(".ant-dropdown-trigger, [role='button'], button, [tabindex]");return n instanceof HTMLElement?n:t}isStopLikeButton(e){if(!e)return false;const t=e.querySelector("use"),n=t?.getAttribute("xlink:href")||t?.getAttribute("href")||"",r=(e.innerText||e.textContent||"").trim().toLowerCase();return /stop/i.test(n)||r.includes("stop")||r.includes("停止")}findStopButton(){const e=this.findVisibleElementBySelectors(this.getStopButtonSelectors());if(e&&!this.isDisabledActionElement(e))return e;const t=document.querySelector(Eb);return this.isVisibleActionElement(t)&&!this.isDisabledActionElement(t)&&this.isStopLikeButton(t)?t:null}isVisibleActionElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}isDisabledActionElement(e){return !(e instanceof HTMLElement)||(e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/\bdisabled\b/i.test(e.className||""))}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends gs{exportIncludeThoughts=void 0;match(){const e=window.location.hostname;return "www.qianwen.com"===e||"qianwen.com"===e}getSiteId(){return vo}getName(){return "Qianwen"}getThemeColors(){return {primary:"#615ced",secondary:"#4b45c0"}}getNativeThemeCss(){return "\n/* =============================================\n * Qianwen (通义千问) 站点原生主题适配器 (Qianwen Theme Adapter)\n * ============================================= */\nbody {\n /* 主要背景 */\n --color-canvas-default: var(--gh-bg) !important;\n\n /* 次要/浮动层背景 (混入极低浓度主题色) */\n --color-canvas-subtle: color-mix(in srgb, var(--gh-primary) 2%, var(--gh-bg)) !important;\n\n /* 代码块与表格背景 */\n --color-inline-code-bg: var(--gh-bg-tertiary) !important;\n --color-table-head-th-bg: var(--gh-bg-secondary) !important;\n\n /* 边框体系 */\n --color-border-muted: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-table-row-border: color-mix(in srgb, var(--gh-primary) 10%, transparent) !important;\n --color-border-default: color-mix(in srgb, var(--gh-primary) 15%, transparent) !important;\n\n /* 主色调/链接色 */\n --color-link: var(--gh-primary) !important;\n --color-link-border: var(--gh-primary) !important;\n --color-qk-link-border: var(--gh-primary) !important;\n}\n\n.bg-pc-sidebar {\n background-color: var(--color-canvas-subtle) !important;\n}\n\n"}getSessionId(){const e=window.location.pathname.match(jf);return e?.[1]||super.getSessionId()}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,"")||"/";return "/"===e||"/chat"===e}isSharePage(){return window.location.pathname.startsWith("/share/")}isUserConversationPage(){return !this.isSharePage()&&jf.test(window.location.pathname)}getCurrentCid(){const e=localStorage.getItem("qianwen-uniq-id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getSessionName(){const e=this.getDocumentConversationTitle()||"";if(!e)return null;const t=e.replace(/\s*[-|]\s*通义千问$/i,"").replace(/\s*[-|]\s*Qwen$/i,"").replace(/\s*[-|]\s*Qianwen$/i,"").trim();return !t||/^(通义千问|Qwen|Qianwen)$/i.test(t)?null:t}getNewTabUrl(){return "https://www.qianwen.com"}getCurrentConversationInfo(){return Hf.test(window.location.pathname)?null:super.getCurrentConversationInfo()}getConversationTitle(){return this.getSessionName()}getTextareaSelectors(){return ['[class*="chatTextarea"]',`${ab} [contenteditable="true"]`,'[data-slate-editor="true"][contenteditable="true"]','div[role="textbox"][contenteditable="true"]',"textarea"]}isValidTextarea(e){return !!super.isValidTextarea(e)&&(!e.closest(db)&&(!!(e.isContentEditable||e instanceof HTMLTextAreaElement)&&!(!e.closest(ab)&&!e.matches('[data-slate-editor="true"]'))))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;if(t.focus(),t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement){const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),true}try{if(document.execCommand("selectAll",!1),document.execCommand("insertText",!1,e))return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{}return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){if(e.focus(),e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement){const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),void e.dispatchEvent(new Event("change",{bubbles:true}))}try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{}e.textContent="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}getSubmitButtonSelectors(){return ['[class*="operateBtn"]','[data-icon-type="qwpcicon-sendChat"]',"button[type='submit']"]}findSubmitButton(e){const t=[e?.closest(ab),e?.parentElement,e?.closest("div"),document.body].filter(Boolean);for(const n of t){const e=n.querySelectorAll('[class*="operateBtn"], [data-icon-type="qwpcicon-sendChat"]');for(const t of Array.from(e)){const e=t.closest('[class*="operateBtn"], button, [role="button"]');if(e&&this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e}}return super.findSubmitButton(e)}getNewChatButtonSelectors(){return ['[class*="newChatButton"]']}getScrollContainer(){const e=[sb,lb];for(const r of e){const e=document.querySelectorAll(r);for(const t of Array.from(e)){const e=t;if(e.scrollHeight>e.clientHeight)return e}}const t=document.querySelector(lb);if(!t)return null;let n=t;for(;n&&n!==document.body;){if(n.scrollHeight>n.clientHeight)return n;n=n.parentElement;}return null}getResponseContainerSelector(){return `${lb}, ${sb}`}getChatContentSelectors(){return [Qf,Kf]}getUserQuerySelector(){return Qf}getLatestReplyText(){const e=document.querySelectorAll(Kf),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractUserQueryText(e){const t=this.extractUserTextParts(e);if(t.length>0)return t.join("\n\n");const n=this.findUserQueryContentRoot(e);if(!n)return "";const r=n.cloneNode(true);return r.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove()),this.normalizeUserQueryText(this.extractTextWithLineBreaks(r)).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserQueryContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-user-query-markdown-qianwen gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}async prepareConversationExport(e){return this.exportIncludeThoughts=e.includeThoughts,null}async restoreConversationAfterExport(e,t){this.exportIncludeThoughts=void 0;}async extractExportMessages(e){const t=this.extractQianwenExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractQianwenExportMessages(e))}extractOutline(e=6,t=false,n=false){const r=[],o=document.querySelector(lb)||document.querySelector(this.getResponseContainerSelector());if(!o)return r;const i=this.collectTopLevelBlocks(Array.from(o.querySelectorAll(`${Qf}, ${Kf}`)).filter(e=>!e.closest(".gh-root")));return i.forEach((o,a)=>{if(o.matches(Qf)){if(!t)return;const e=this.extractUserQueryText(o);if(!e)return;let s;if(n){const e=i.slice(a+1).find(e=>e.matches(Kf));s=e?this.extractAssistantPlainText(e).length:0;}return void r.push({level:0,text:this.truncateText(e,80),element:o,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=Array.from(o.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!e.closest(db)&&!this.isInRenderedMarkdownContainer(e));s.forEach((t,i)=>{const a=parseInt(t.tagName[1],10);if(a>e)return;const l=t.textContent?.trim()||"";if(!l)return;let c;if(n){let e=null;for(let t=i+1;t{r++;const i=this.findModelSelectorTrigger();if(!i)return void(r<10?setTimeout(o,500):console.warn(`Ophel: Qianwen model selector not found for "${e}".`));if(this.normalizeText(this.getModelName()||"").includes(n))t?.();else {try{localStorage.setItem(Gf,"1");}catch{}this.simulateClick(i),setTimeout(async()=>{let i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n);!a&&this.expandMoreModels()&&(await new Promise(e=>setTimeout(e,400)),i=this.findVisibleModelDialogItems(),a=this.findBestMatchingDialogItem(i,n)),a?(this.simulateClick(a),setTimeout(()=>{document.body.click(),t?.();},150)):r<10?setTimeout(o,500):(document.body.click(),console.warn(`Ophel: Qianwen model "${e}" not found.`));},300);}};o();}simulateClick(e){const t=["pointerdown","mousedown","pointerup","mouseup","click"];for(const n of t)e.dispatchEvent(new PointerEvent(n,{bubbles:true,cancelable:true,view:window,pointerId:1}));}getWidthSelectors(){const e=["width: 100% !important;","min-width: 0 !important;","--max-message-list-width: 100% !important;","--min-message-list-width: 0px !important;"].join(" ");return [{selector:'[class*="scrollOutWrapper"]',property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:`${lb}`,property:"max-width",extraCss:"width: 100% !important;",noCenter:true},{selector:'[class*="auto-center-wrapper"]',property:"max-width",extraCss:e},{selector:'[class*="inputMotionCarrier"]',property:"max-width",extraCss:"width: 100% !important;"},{selector:'[class*="inputOutWrap"]',property:"max-width",value:"100%",extraCss:"width: 100% !important;"},{selector:'[class*="answerItem"] [class*="containerWrap"]',property:"max-width"},{selector:'[class*="questionItem"], .chat-question-wrap',property:"width",extraCss:"margin-right: 0 !important"},{selector:Yf,property:"width",value:"100%",extraCss:"max-width: 100% !important; box-sizing: border-box !important;",noCenter:true}]}getUserQueryWidthSelectors(){const e="margin-left: auto !important; margin-right: 0 !important;";return [{selector:`${Qf} ${Zf}`,property:"max-width",extraCss:e,noCenter:true},{selector:Vf,property:"max-width",extraCss:e,noCenter:true}]}getZenModeConfig(){return {hide:[cb]}}getCleanModeConfig(){return {hide:["#ice-container .root-G6nVVr"]}}getMarkdownFixerConfig(){return {selector:`${Kf} .qk-md-paragraph`,fixSpanContent:false,shouldSkip:e=>{if(!this.isGenerating())return false;const t=e.closest(Kf);if(!t)return false;const n=document.querySelectorAll(Kf);return t===n[n.length-1]}}}extractQianwenExportMessages(e){const t=this.getExportRoot(),n=this.collectQianwenExportTurns(t),r=n.length>0?n:[t],o=[];return r.forEach(t=>{this.getOrderedQianwenMessages(t).forEach(({role:t,element:n})=>{const r=("user"===t?this.extractUserQueryExportContentWithAssets(n,e):this.extractAssistantResponseTextWithAssets(n,e)).trim();r&&o.push({role:t,content:r});});}),o}getExportRoot(){return document.querySelector(lb)||document.querySelector(sb)||document.body}collectQianwenExportTurns(e){const t=this.queryElementsIncludingSelf(e,".chat-round[data-chat], [data-chat-list-key]");return this.collectTopLevelBlocks(t).filter(e=>this.getOrderedQianwenMessages(e).length>0)}getOrderedQianwenMessages(e){const t=[],n=new Set,r=(e,r)=>{!r||n.has(r)||this.shouldSkipExportElement(r)||(n.add(r),t.push({role:e,element:r}));},o=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,`${Qf}, [data-chat-question-wrap]`)),i=this.collectTopLevelBlocks(this.queryElementsIncludingSelf(e,Kf));return [...o.map(e=>({role:"user",element:e})),...i.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element)).forEach(({role:e,element:t})=>r(e,t)),t}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserTextParts(e).join("\n\n").trim(),r=this.extractQianwenUserAttachments(e);if(0===r.length)return n||this.extractUserQueryText(e);const o=this.formatQianwenUserImageAttachments(r,t),i=this.formatQianwenUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatQianwenAssistantImages(this.extractQianwenAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport()?this.extractThoughtBlockquotes(e):[],n=this.findAssistantContentRoot(e).cloneNode(true);n.querySelectorAll([ob,rb,"picture","img"].join(", ")).forEach(e=>e.remove());const r=`${db}, [class*="thinkingTitle"]`;n.querySelectorAll(r).forEach(e=>e.remove());const o=(Fi(n)||this.extractTextWithLineBreaks(n)).trim();if(t.length>0){const e=t.join("\n\n");return o?`${e}\n\n${o}`:e}return o}extractUserTextParts(e){const t=this.findUserMessageScope(e),n=this.queryElementsIncludingSelf(t,".question-text-card"),r=[],o=new Set;return n.forEach(e=>{if(e.closest(".gh-user-query-markdown"))return;const t=e.cloneNode(true);t.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true']").forEach(e=>e.remove());const n=this.normalizeUserQueryText(this.extractTextWithLineBreaks(t)).trim();n&&!o.has(n)&&(o.add(n),r.push(n));}),r}extractQianwenUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=[e.kind,ca(e.source),e.name.trim().toLowerCase(),e.type.trim().toLowerCase(),e.sizeLabel||""].join(":");r.has(t)||(r.add(t),n.push(e));};return this.queryElementsIncludingSelf(t,Xf).forEach(e=>o(this.extractQianwenUserImageAttachment(e))),this.queryElementsIncludingSelf(t,eb).forEach(e=>o(this.extractQianwenUserFileAttachment(e))),n}extractQianwenUserImageAttachment(e){const t=e.querySelector("img");if(!(t instanceof HTMLImageElement))return null;const n=this.extractQianwenImageSource(t);if(!n)return null;const r=t.alt?.trim()||t.getAttribute("title")?.trim()||da(n)||"uploaded image";return {kind:"image",name:r,source:n,type:ua(r)||ha(n)}}extractQianwenUserFileAttachment(e){const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=ga(t),i=this.extractQianwenDownloadableSource(e,{allowDataImage:false,includeImages:false}),a=n||da(i)||"attachment";return {kind:"file",name:a,source:i,type:r||ua(a)||ha(i),sizeLabel:o}}formatQianwenUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatQianwenUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId()})}extractQianwenAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,nb).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractQianwenImageSource(e);t&&!r.has(t)&&(r.add(t),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`}));}),n}formatQianwenAssistantImages(e,t){return Ma(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}findUserMessageScope(e){return e.matches(Qf)||e.matches("[data-chat-question-wrap]")?e:e.closest(Qf)||e.closest("[data-chat-question-wrap]")||e}findAssistantContentRoot(e){return e.matches(tb)?e:e.querySelector(tb)||e}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractQianwenImageSource(e){const t=[e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeQianwenExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractQianwenDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractQianwenImageSource(e)),ib.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeQianwenExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeQianwenExportSource(e,t){const n=fa(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!ba(n))return "";try{const e=new URL(n);if(/^g\.alicdn\.com$/i.test(e.hostname))return "";if(/\/static\//i.test(e.pathname)&&!/\.(png|jpe?g|webp|gif|avif)$/i.test(e.pathname))return ""}catch{return ""}return n}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}shouldIncludeThoughtsInExport(){return void 0!==this.exportIncludeThoughts&&this.exportIncludeThoughts}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll('[class*="thinkingContent"]')),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll('[class*="thinkingTitle"], [class*="thinkingHeader"], .qc-thinking-header, button, svg, [aria-hidden="true"]').forEach(e=>e.remove());const t=(Fi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractAssistantPlainText(e){const t=e.cloneNode(true);return t.querySelectorAll(`${db}, .qc-thinking-header, [class*="thinkingWrap"], [class*="thinkingContent"], button, [role='button'], svg, .qk-md-table-action, .qk-md-copy-icon, [aria-hidden='true'], [class*="answerToolsContent"], [class*="functionArea"]`).forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findUserQueryContentRoot(e){if(e.matches(".question-text-card"))return e;const t=e.querySelector(".question-text-card");return t instanceof HTMLElement?t:e.matches(Zf)?e:e.querySelector(Zf)||e}normalizeUserQueryText(e){return e.replace(/\u00a0/g," ")}findModelSelectorTrigger(){return Array.from(document.querySelectorAll('[aria-haspopup="dialog"][aria-controls], [aria-haspopup="dialog"][data-state]')).filter(e=>{const t=e;if(!this.isVisibleElement(t))return false;if(t.closest(cb))return false;if(t.closest(ab))return false;const n=t.getBoundingClientRect(),r=t.innerText?.trim()||t.textContent?.trim()||"";return n.top<180&&n.width>0&&n.height>0&&r.length>0})[0]||null}findVisibleModelDialogItems(){const e=Array.from(document.querySelectorAll(hb)).filter(e=>this.isVisibleElement(e));if(0===e.length)return [];const t=[];return e.forEach(e=>{const n=e.querySelectorAll(gb);for(const r of Array.from(n)){const e=r;this.isVisibleElement(e)&&(e.innerText?.trim()&&t.push(e));}}),t}findBestMatchingDialogItem(e,t){if(0===e.length)return null;const n=this.normalizeText(t);for(const r of e){const e=this.normalizeText(r.innerText||r.textContent||"");if(!e)continue;if(e.split("\n")[0].trim()===n)return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").split("\n")[0].trim().endsWith(n))return r}for(const r of e){if(this.normalizeText(r.innerText||r.textContent||"").includes(n))return r}return null}expandMoreModels(){const e=Array.from(document.querySelectorAll(hb)).filter(e=>this.isVisibleElement(e));for(const t of e){const e=t.querySelectorAll("button, div, span");for(const t of Array.from(e)){const e=t;if(!this.isVisibleElement(e))continue;const n=this.normalizeText(e.innerText||e.textContent||"");if(n&&((n.includes(this.normalizeText("查看更多模型"))||n.includes(this.normalizeText("view more models"))||n.includes(this.normalizeText("更多模型")))&&!n.includes(this.normalizeText("收起"))&&!n.includes(this.normalizeText("collapse"))))return this.simulateClick(e),true}}return false}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}normalizeText(e){return (e||"").replace(/\s+/g," ").trim().toLowerCase()}isDisabledActionButton(e){const t=this.getElementClassName(e);return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}getElementClassName(e){return "string"==typeof e.className?e.className:""}},new class extends gs{exportIncludeThoughtsOverride=null;match(){return window.location.hostname===Vb}getSiteId(){return xo}getName(){return "元宝"}getThemeColors(){return {primary:"#1677ff",secondary:"#0b5bd3"}}supportsFormulaCopy(){return false}getTextareaSelectors(){return ['.agent-dialogue__content--common__input .ql-editor[contenteditable="true"], #search-bar .ql-editor[contenteditable="true"], .ql-editor[contenteditable="true"]']}isValidTextarea(e){return !!super.isValidTextarea(e)&&("true"===e.getAttribute("contenteditable")&&!!e.closest(".agent-dialogue__content--common__input"))}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();try{if(document.execCommand("selectAll",!1),!document.execCommand("insertText",!1,e))throw new Error("execCommand returned false");return t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,data:e,inputType:"insertText"})),!0}catch{return t.textContent=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e,inputType:"insertText"})),t.dispatchEvent(new Event("change",{bubbles:true})),true}}clearTextarea(){const e=this.getTextareaElement();if(e&&e.isConnected){e.focus();try{document.execCommand("selectAll",!1),document.execCommand("delete",!1);}catch{e.textContent="";}e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:"",inputType:"deleteContentBackward"})),e.dispatchEvent(new Event("change",{bubbles:true}));}}simulateClick(e){const t=e.getBoundingClientRect(),n=t.left+Math.max(1,Math.min(t.width/2,Math.max(t.width-1,1))),r=t.top+Math.max(1,Math.min(t.height/2,Math.max(t.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:1,clientX:n,clientY:r},i=t=>"function"==typeof PointerEvent&&e.dispatchEvent(new PointerEvent(t,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));i("pointerenter"),i("pointerover"),i("pointermove"),e.dispatchEvent(new MouseEvent("mouseenter",o)),e.dispatchEvent(new MouseEvent("mouseover",o)),e.dispatchEvent(new MouseEvent("mousemove",o)),i("pointerdown"),e.dispatchEvent(new MouseEvent("mousedown",o)),i("pointerup"),e.dispatchEvent(new MouseEvent("mouseup",o)),e.dispatchEvent(new MouseEvent("click",o));}getSubmitButtonSelectors(){return [Yb]}findSubmitButton(){const e=document.querySelector("#yuanbao-send-btn");if(this.isVisibleElement(e)&&!this.isDisabledActionButton(e))return e;const t=Array.from(document.querySelectorAll(Yb));for(const n of t){const e=n;if(this.isVisibleElement(e)&&(!this.isDisabledActionButton(e)&&!this.isStopLikeButton(e)))return e}return null}getSessionId(){const e=window.location.pathname.match(Kb);return e?.[2]||""}isNewConversation(){const e=window.location.pathname.replace(/\/+$/,""),t=e.match(Kb);return t?!t[2]:""===e||"/"===e}isSharePage(){return window.location.pathname.startsWith("/s/")}getNewTabUrl(){const e=this.getAgentId();return e?`https://${Vb}/chat/${e}`:`https://${Vb}/`}getSessionName(){const e=this.getConversationTitle();if(e)return e;const t=this.getDocumentConversationTitle()||"";if(!t)return null;const n=t.replace(/\s*[-|]\s*(腾讯元宝|元宝)$/i,"").trim();return !n||/^(腾讯元宝|元宝)$/i.test(n)?null:n}getCurrentCid(){const e=localStorage.getItem("yb_user_id");if(!e)return null;try{const t=JSON.parse(e);if("string"==typeof t&&t.trim())return t.trim();if(t&&"object"==typeof t)for(const e of ["uid","id","cid","userId"]){const n=t[e];if("string"==typeof n&&n.trim())return n.trim()}}catch{}return e.trim()||null}getConversationTitle(){const e=document.querySelector(ey);return e?this.extractConversationTitle(e):null}getCurrentConversationInfo(){const e=super.getCurrentConversationInfo();if(!e)return null;const t=document.querySelector(ey),n=t?this.extractConversationInfo(t,this.getCurrentCid()||void 0):null;return n&&n.id===e.id?{...e,title:n.title||e.title,url:n.url||e.url,cid:n.cid??e.cid,isActive:n.isActive??e.isActive,isPinned:n.isPinned??e.isPinned}:e}getConversationList(){const e=this.getCurrentCid()||void 0,t=document.querySelectorAll(Xb),n=new Map;return t.forEach(t=>{const r=this.extractConversationInfo(t,e);r&&n.set(r.id,r);}),Array.from(n.values())}getConversationObserverConfig(){return {selector:Xb,shadow:false,extractInfo:e=>this.extractConversationInfo(e,this.getCurrentCid()||void 0),getTitleElement:e=>e.querySelector(ty)||e}}getSidebarScrollContainer(){return document.querySelector(".yb-nav__content")}async loadAllConversations(){const e=this.getSidebarScrollContainer();if(!(e instanceof HTMLElement))return;let t=0,n=0;for(;n<4;){e.scrollTop=e.scrollHeight,e.dispatchEvent(new Event("scroll",{bubbles:true})),await new Promise(e=>window.setTimeout(e,500));const r=document.querySelectorAll(Xb).length;r===t?n+=1:(t=r,n=0);}}navigateToConversation(e,t){const n=this.captureConversationNavigationState(),r=this.findConversationRowById(e);if(r){const o=r.querySelector(ty),i=this.resolveClickableTarget(o)||r.querySelector("a[href]")||this.resolveClickableTarget(r)||r;return this.simulateClick(i),window.setTimeout(()=>{this.hasConversationNavigationChanged(n)||super.navigateToConversation(e,t||this.buildConversationUrl(e));},800),true}return super.navigateToConversation(e,t||this.buildConversationUrl(e))}async deleteConversationOnSite(e){try{const t=await this.deleteConversationViaUi(e.id);return {id:e.id,success:t,method:t?"ui":"none",reason:t?void 0:Ay}}catch(t){return console.error(`[YuanbaoAdapter] deleteConversationOnSite error for "${e.id}":`,t),{id:e.id,success:false,method:"none",reason:Ey}}}async deleteConversationsOnSite(e){const t=[];for(let n=0;nt.clientHeight)return t;const e=this.findScrollableParent(t);if(e)return e}return super.getScrollContainer()}getResponseContainerSelector(){return ny}getChatContentSelectors(){return [ry,oy]}getUserQuerySelector(){return ry}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, input, label").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractUserQueryExportContentWithAssets(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e),n.style.display="none";}return n.after(r),true}extractAssistantResponseText(e){return this.extractAssistantResponseTextWithAssets(e)}getLatestReplyText(){const e=document.querySelectorAll(oy),t=e[e.length-1];return t?this.extractAssistantResponseText(t):null}extractOutline(e=6,t=false,n=false){const r=document.querySelector(ny)||this.getScrollContainer()||document,o=Array.from(r.querySelectorAll(`${ry}, ${oy}`)).filter(e=>!e.closest(".gh-root")),i=[];return o.forEach((r,a)=>{if(r.matches(ry)){if(!t)return;const e=this.extractUserQueryText(r);if(!e)return;let s;if(n){const e=o.slice(a+1).find(e=>e.matches(oy));s=e?this.extractAssistantPlainText(e).length:0;}return void i.push({level:0,text:this.truncateText(e,80),element:r,isUserQuery:true,isTruncated:e.length>80,wordCount:s})}const s=this.findAssistantMarkdownRoot(r);if(!s)return;const l=Array.from(s.querySelectorAll("h1, h2, h3, h4, h5, h6")).filter(e=>!this.isInRenderedMarkdownContainer(e));l.forEach((t,r)=>{const o=Number.parseInt(t.tagName.slice(1),10);if(Number.isNaN(o)||o>e)return;const a=this.extractHeadingText(t);if(!a)return;let c;if(n){let e=null;for(let t=r+1;t0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractYuanbaoExportMessages(e))}isGenerating(){return null!==this.findStopButton()}getStopButtonSelectors(){return [Jb]}stopGeneration(){const e=this.findStopButton();return !!e&&(this.simulateClick(e),true)}getNetworkMonitorConfig(){return {urlPatterns:["/api/chat/"],silenceThreshold:2e3}}getWidthSelectors(){return [{selector:":root",property:xy,noCenter:true},{selector:":root",property:"--hunyuan-chat-list-width",value:`min(100%, var(${xy}))`,noCenter:true}]}async toggleTheme(e){try{return localStorage.setItem(Zb,e),window.dispatchEvent(new StorageEvent("storage",{key:Zb,newValue:e,storageArea:localStorage})),document.documentElement.style.colorScheme=e,!0}catch(t){return console.error("[YuanbaoAdapter] toggleTheme error:",t),false}}getModelName(){const e=document.querySelector(gy);return e?.textContent?.trim()||""||null}getModelLockCheckText(e){return this.getModelName()||super.getModelLockCheckText(e)}getModelSwitcherConfig(e){return {targetModelKeyword:e,selectorButtonSelectors:[".ybc-model-select-button",gy],menuItemSelector:".ybc-model-select-dropdown-popup .t-dropdown__item, .ybc-model-select-dropdown .t-dropdown__item, .t-popup .t-dropdown__item",checkInterval:1e3,maxAttempts:10,menuRenderDelay:200}}getNewChatButtonSelectors(){return ['.yb-common-nav__trigger[data-desc="new-chat"]']}getZenModeConfig(){return {hide:[".yb-nav__content-wrapper",".yb-nav-fixed.yb-nav-fixed--pc-ctx"],styles:[{selector:".agent-dialogue__content--common__input-box",property:"padding-bottom",value:"0"},{selector:".yb-nav--push.yb-nav--open~.yb-layout__content, .yb-nav--push.yb-nav--open~.yb-layout__content-skeleton",property:"margin-left",value:"0"}]}}getCleanModeConfig(){return {hide:[".agent-dialogue__content-copyright",".yb__pc_download",".agent-dialogue__tool"]}}getAgentId(){const e=window.location.pathname.match(Kb);if(e?.[1])return e[1];const t=document.querySelector(`${Xb}[dt-agent-id]`)?.getAttribute("dt-agent-id")||document.querySelector("[dt-agent-id]")?.getAttribute("dt-agent-id");return t?.trim()||null}buildConversationUrl(e){const t=this.getAgentId();return t?`https://${Vb}/chat/${t}/${e}`:`https://${Vb}/`}extractConversationInfo(e,t){const n=e.closest(Xb)||(e.matches(Xb)?e:null);if(!n)return null;const r=n.getAttribute("dt-cid")||n.querySelector("[data-item-id]")?.getAttribute("data-item-id")||"";if(!r)return null;return {id:r,title:this.extractConversationTitle(n),url:this.buildConversationUrl(r),cid:t,isActive:n.classList.contains("active"),isPinned:this.isPinnedConversation(n)}}extractConversationTitle(e){const t=e.querySelector(ty);return (t?.getAttribute("data-item-name")||t?.dataset?.itemName||t?.textContent||"").trim()}isPinnedConversation(e){return null!==e.querySelector(".yb-recent-conv-list__item-name.isTop, .yb-recent-conv-list__chat-top .icon-yb-ic_pin_16")}findScrollableParent(e){let t=e?.parentElement||null;for(;t;){const e=window.getComputedStyle(t);if(/(auto|scroll)/i.test(e.overflowY)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement;}return null}findUserContentRoot(e){return e.querySelector(".agent-chat__bubble--human .hyc-content-text, .agent-chat__bubble--human .agent-chat__bubble__content")||e.querySelector(".agent-chat__bubble__content")||e}findAssistantContentRoot(e){const t=this.findAssistantBodyRoot(e);if(t)return t;const n=this.findAssistantMarkdownRoot(e);return n||(e.querySelector(".agent-chat__speech-text")||e.querySelector(".agent-chat__bubble__content")||e)}findAssistantMarkdownRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,fy.slice(0,2));if(t)return t;if(e.matches(iy)&&!this.isThoughtElement(e))return e;const n=Array.from(e.querySelectorAll(iy));return n.find(e=>!this.isThoughtElement(e))||n[0]||null}extractYuanbaoExportMessages(e){const t=document.querySelector(ny)||this.getScrollContainer()||document.body;return this.collectTopLevelBlocks(Array.from(t.querySelectorAll(`${ry}, ${oy}`))).filter(e=>!this.shouldSkipExportElement(e)).sort((e,t)=>this.compareDomOrder(e,t)).map(t=>{const n=t.matches(ry)?"user":"assistant";return {role:n,content:("user"===n?this.extractUserQueryExportContentWithAssets(t,e):this.extractAssistantResponseTextWithAssets(t,e)).trim()}}).filter(e=>e.content.length>0)}extractUserQueryExportContentWithAssets(e,t){const n=this.extractUserQueryText(e),r=this.extractYuanbaoUserAttachments(e);if(0===r.length)return n;const o=this.formatYuanbaoUserImageAttachments(r,t),i=this.formatYuanbaoUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractAssistantResponseTextWithAssets(e,t){return [this.extractAssistantMarkdown(e),this.formatYuanbaoAssistantImages(this.extractYuanbaoAssistantImages(e),t).join("\n\n")].filter(Boolean).join("\n\n")}extractAssistantMarkdown(e){const t=this.shouldIncludeThoughtsInExport(),n=e.cloneNode(true);n.querySelectorAll([sy,ay,uy].join(", ")).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove());const r=t?this.extractThoughtBlockquotes(n):[];n.querySelectorAll(my).forEach(e=>e.remove());const o=this.findAssistantBodyRoot(n)||n,i=Fi(o).trim()||this.extractTextWithLineBreaks(o).trim();if(t&&r.length>0){const e=r.join("\n\n");return i?`${e}\n\n${i}`:e}return i}extractYuanbaoUserAttachments(e){const t=this.findUserMessageScope(e),n=[],r=new Set,o=e=>{if(!e)return;const t=this.getYuanbaoAttachmentKeys(e);t.some(e=>r.has(e))||(t.forEach(e=>r.add(e)),n.push(e));};return t.querySelectorAll(ly).forEach(e=>{e instanceof HTMLImageElement&&o(this.extractYuanbaoUserImageAttachment(e));}),this.queryElementsIncludingSelf(t,cy).forEach(e=>{o(this.extractYuanbaoUserFileAttachment(e));}),n}extractYuanbaoUserImageAttachment(e){const t=this.extractYuanbaoImageSource(e);if(!t)return null;const n=e.alt?.trim()||e.getAttribute("title")?.trim()||da(t,{ignoreGenericDownload:true})||"uploaded image";return {kind:"image",name:n,source:t,type:ua(n)||ha(t)||"image"}}extractYuanbaoUserFileAttachment(e){if(e.closest(".hyc-component-multi-modal__image, .hyc-content-img"))return null;const t=this.extractCleanTextParts(e),{name:n,type:r,sizeLabel:o}=ga(t),i=this.extractYuanbaoDownloadableSource(e,{allowDataImage:false,includeImages:false});if(!n&&!i)return null;const a=n||da(i,{ignoreGenericDownload:true})||this.extractResourceIdFilename(i)||"attachment";return {kind:"file",name:a,source:i,type:r||ua(a)||ha(i),sizeLabel:o}}formatYuanbaoUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatYuanbaoUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId()})}extractYuanbaoAssistantImages(e){const t=this.findAssistantContentRoot(e),n=[],r=new Set;return this.queryElementsIncludingSelf(t,dy).forEach(e=>{if(!(e instanceof HTMLImageElement))return;const t=this.extractYuanbaoImageSource(e),o=ca(t);t&&!r.has(o)&&(r.add(o),n.push({source:t,alt:e.alt?.trim()||e.getAttribute("aria-label")?.trim()||`generated image ${n.length+1}`,extensionHint:this.extractYuanbaoImageExtensionHint(e)}));}),n}formatYuanbaoAssistantImages(e,t){return Ma(e,t,{siteId:this.getSiteId(),role:"assistant",category:"generated-image",fallbackAlt:"generated image"})}extractYuanbaoImageSource(e){const t=[e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.getAttribute("data-image-url")||"",e.getAttribute("data-original-url")||"",e.getAttribute("data-origin-url")||""];for(const n of t){const e=this.normalizeYuanbaoExportSource(n,{allowDataImage:true});if(e)return e}return ""}extractYuanbaoDownloadableSource(e,t){const n=[];[e,...Array.from(e.querySelectorAll("*"))].forEach(e=>{e instanceof HTMLAnchorElement&&n.push(e.href||e.getAttribute("href")||""),t.includeImages&&e instanceof HTMLImageElement&&n.push(this.extractYuanbaoImageSource(e)),hy.forEach(r=>{!t.includeImages&&e instanceof HTMLImageElement&&"src"===r||n.push(e.getAttribute(r)||"");});});for(const r of n){const e=this.normalizeYuanbaoExportSource(r,{allowDataImage:t.allowDataImage});if(e)return e}return ""}normalizeYuanbaoExportSource(e,t){const n=fa(e);if(!n)return "";if(/^data:image\/svg\+xml/i.test(n))return "";if(/^data:image\//i.test(n))return t.allowDataImage?n:"";if(!ba(n))return "";try{const e=new URL(n,window.location.href);if(e.hostname===Vb&&/\/(?:static|assets)\//i.test(e.pathname))return "";if(/\.(?:svg|ico)$/i.test(e.pathname)&&/(?:icon|logo|sprite)/i.test(e.pathname))return ""}catch{return ""}return n}extractYuanbaoImageExtensionHint(e){return [e.currentSrc||"",e.src||"",e.getAttribute("src")||"",e.getAttribute("data-src")||"",e.closest("[data-card-url]")?.getAttribute("data-card-url")||"",e.alt||""].map(e=>ha(e)||ua(e)).find(Boolean)||""}findUserMessageScope(e){return e.matches(ry)?e:e.closest(ry)||e}shouldSkipExportElement(e){return !!e.closest(".gh-root")||!!e.closest(".gh-user-query-markdown")}queryElementsIncludingSelf(e,t){const n=[];return e instanceof Element&&e.matches(t)&&n.push(e),e.querySelectorAll(t).forEach(e=>{n.includes(e)||n.push(e);}),n}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}extractCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll(".gh-user-query-markdown, button, [role='button'], svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}getYuanbaoAttachmentKeys(e){const t=[],n=ca(e.source),r=e.name.trim().toLowerCase(),o=e.type.trim().toLowerCase(),i=e.sizeLabel?.trim().toLowerCase()||"";return n&&t.push(`${e.kind}:source:${n}`),r&&o&&t.push(`${e.kind}:name-type:${r}:${o}`),r&&i&&t.push(`${e.kind}:name-size:${r}:${i}`),t.length>0?t:[`${e.kind}:fallback:${r}:${o}`]}extractResourceIdFilename(e){if(!e)return "";try{const t=new URL(e,window.location.href).searchParams.get("resourceId");return t?`attachment-${t.slice(0,12)}`:""}catch{return ""}}extractAssistantPlainText(e){const t=this.findAssistantContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(`${sy}, ${ay}`).forEach(e=>e.remove()),n.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractHeadingText(e){const t=e.cloneNode(true);return t.querySelectorAll("button, [role='button'], svg").forEach(e=>e.remove()),this.extractTextWithLineBreaks(t).trim()}findAssistantBodyRoot(e){const t=this.findFirstAssistantNodeOutsideThoughts(e,fy);if(t)return t;const n=this.findAssistantMarkdownRoot(e);if(n instanceof HTMLElement)return n;const r=e.querySelector(".agent-chat__speech-text");if(r&&!this.isThoughtElement(r))return r;const o=e.querySelector(".agent-chat__bubble__content");return o&&!this.isThoughtElement(o)?o:e instanceof HTMLElement?e:null}shouldIncludeThoughtsInExport(){return "boolean"==typeof this.exportIncludeThoughtsOverride&&this.exportIncludeThoughtsOverride}extractThoughtBlockquotes(e){const t=Array.from(e.querySelectorAll(py)).filter(e=>!e.parentElement?.closest(py)),n=[];for(const r of t){const e=r.cloneNode(true);e.querySelectorAll(`${ay}, button, [role='button'], svg, [aria-hidden='true']`).forEach(e=>e.remove());const t=(Fi(e)||this.extractTextWithLineBreaks(e)).trim();t&&n.push(this.formatAsThoughtBlockquote(t));}return n}formatAsThoughtBlockquote(e){return ["> [Thoughts]",...e.replace(/\r\n/g,"\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}findFirstAssistantNodeOutsideThoughts(e,t){for(const n of t){if(e.matches(n)&&!this.isThoughtElement(e))return e;const t=Array.from(e.querySelectorAll(n)).find(e=>e instanceof HTMLElement&&!this.isThoughtElement(e));if(t)return t}return null}isThoughtElement(e){return null!==e.closest(my)}findConversationRowById(e){const t=document.querySelector(`${Xb}[dt-cid="${e}"]`);if(t)return t;const n=Array.from(document.querySelectorAll(Xb));for(const r of n){const t=this.extractConversationInfo(r,this.getCurrentCid()||void 0);if(t?.id===e)return r}return null}async deleteConversationViaUi(e){let t=this.findConversationRowById(e);if(t||(await this.loadAllConversations(),t=this.findConversationRowById(e)),!t)return false;const n=this.captureConversationNavigationState();t.scrollIntoView({block:"center",behavior:"auto"}),this.revealConversationActions(t);let r=this.findConversationMenuTrigger(t);if(!r)return false;const o=await this.openConversationAction(t,r);if(!o)return false;let i="dialog"===o.kind?o.dialog:null;if("menu"===o.kind){const e=await this.waitForDeleteMenuItem(o.menu,2e3);if(!e)return document.body.click(),false;this.simulateClick(e),i=await this.waitForDialogOpen(1200);}if(i){const e=await this.waitForDeleteConfirmButton(i,2e3);if(!e)return false;this.simulateClick(e);}return !!(await this.waitForConversationDeleteResult(e,n,4500))||!!i&&(await this.waitForDialogClosed(1200),this.waitForConversationDeleteResult(e,n,800))}revealConversationActions(e){const t=e.querySelector(ty),n=[e,t].filter(e=>e instanceof HTMLElement);for(const r of n){const e=r.getBoundingClientRect(),t=e.left+Math.max(1,Math.min(e.width/2,Math.max(e.width-1,1))),n=e.top+Math.max(1,Math.min(e.height/2,Math.max(e.height-1,1))),o={bubbles:true,cancelable:true,composed:true,view:window,clientX:t,clientY:n};if("function"==typeof PointerEvent)for(const i of ["pointerenter","pointerover","pointermove"])r.dispatchEvent(new PointerEvent(i,{...o,pointerId:1,pointerType:"mouse",isPrimary:true}));for(const i of ["mouseenter","mouseover","mousemove"])r.dispatchEvent(new MouseEvent(i,o));}}findConversationMenuTrigger(e){return this.getConversationActionCandidates(e)[0]||null}getConversationActionCandidates(e,t){const n=Array.from(e.querySelectorAll(vy)),r=[],o=new Set,i=(e,t=0)=>{if(!(e instanceof HTMLElement)||o.has(e))return;o.add(e);const n=this.getConversationActionScore(e);Number.isFinite(n)&&r.push({element:e,score:n+t});};i(t,25);for(const a of n)i(a);return r.sort((e,t)=>t.score-e.score),r.map(({element:e})=>e)}getConversationActionScore(e){if(e.closest(ty))return Number.NEGATIVE_INFINITY;if(e.closest(".t-checkbox, [role='checkbox']"))return Number.NEGATIVE_INFINITY;if(e.matches("input, label"))return Number.NEGATIVE_INFINITY;const t=this.getConversationActionSignal(e),n=window.getComputedStyle(e);let r=0;return e.matches('[aria-haspopup="menu"], [aria-haspopup="listbox"]')&&(r+=120),/(ellipsis|more[_-]?vert|icon-more|icon-menu|menu)/i.test(t)&&(r+=70),/(delete|删除)/i.test(t)&&(r+=45),/(action|operate|dropdown|popup)/i.test(t)&&(r+=15),e.matches("button, [role='button']")&&(r+=10),e.querySelector(".iconfont-yb, .yb-icon, svg")&&(r+=5),"none"!==n.pointerEvents&&(r+=5),this.isVisibleElement(e)&&(r+=30),r}async openConversationAction(e,t){let n=t;for(let r=0;r<4;r+=1){document.body.click(),await this.sleep(80),this.revealConversationActions(e);const t=this.getConversationActionCandidates(e,n);if(0===t.length)return null;n=t[0]||null;for(const e of t){if(!e.isConnected)continue;this.simulateClick(e);const t=await this.waitForConversationActionOpen(e,1e3);if(t)return t}}return null}async waitForConversationActionOpen(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)&&this.isDropdownMenuContainer(e));return n.length>0?n[n.length-1]:null}isDropdownMenuContainer(e){return !!e.matches(yy)||!!e.querySelector(yy)}async waitForDeleteMenuItem(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>e.className.includes("theme-error"))||t.find(e=>ky.test(this.getElementText(e)));if(n)return n;await this.sleep(80);}return null}async waitForDialogOpen(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e))||null}async waitForDeleteConfirmButton(e,t){const n=Date.now();for(;Date.now()-ne instanceof HTMLElement&&this.isVisibleElement(e)),n=t.find(e=>{const t=this.getElementText(e);return Sy.test(t)&&!Cy.test(t)})||t.find(e=>/primary|danger/i.test(e.className));if(n)return n;await this.sleep(80);}return null}async waitForDialogClosed(e){const t=Date.now();for(;Date.now()-te instanceof HTMLElement&&this.isVisibleElement(e)))return true;await this.sleep(80);}return false}async waitForConversationDeleteResult(e,t,n){const r=Date.now(),o=t.sessionId===e;for(;Date.now()-rwindow.setTimeout(t,e))}findStopButton(){const e=Array.from(document.querySelectorAll(Jb));for(const t of e){const e=t;if(this.isVisibleElement(e)&&this.isStopLikeButton(e))return e}return null}isDisabledActionButton(e){if(!(e instanceof HTMLElement))return true;const t="string"==typeof e.className?e.className:"";return e.hasAttribute("disabled")||"true"===e.getAttribute("aria-disabled")||/disabled/i.test(t)}isStopLikeButton(e){if(!(e instanceof HTMLElement))return false;if(e.querySelector("span.icon-send, .icon-send"))return false;if(e.querySelector("rect"))return true;const t=e.innerText?.trim()||e.textContent?.trim()||"";return /停止|stop/i.test(t)}isVisibleElement(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}truncateText(e,t){return e.length>t?`${e.slice(0,t)}...`:e}},new class extends gs{exportIncludeThoughtsOverride=null;exportUserAttachmentsByMessageId=new Map;exportShareTitle=null;match(){return window.location.hostname===My}getSiteId(){return ko}getName(){return "Z.ai"}getThemeColors(){return {primary:"#0881F0",secondary:"#0B6ED8"}}getTextareaSelectors(){return [...Ly]}insertPrompt(e){const t=this.getTextareaElement();if(!t||!t.isConnected)return false;t.focus();const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;return n?n.call(t,e):t.value=e,t.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:e})),t.dispatchEvent(new Event("change",{bubbles:true})),t.setSelectionRange(e.length,e.length),true}clearTextarea(){const e=this.getTextareaElement();if(!e||!e.isConnected)return;const t=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;t?t.call(e,""):e.value="",e.dispatchEvent(new InputEvent("input",{bubbles:true,composed:true,data:""})),e.dispatchEvent(new Event("change",{bubbles:true})),e.setSelectionRange(0,0);}getSubmitButtonSelectors(){return [`${Ny}:not([disabled])`]}findSubmitButton(){const e=document.querySelector(Ny);return !e||e.hasAttribute("disabled")||null===e.offsetParent?null:e}getResponseContainerSelector(){return Py}getConversationContentContainer(e){const t=document.querySelector(this.getResponseContainerSelector())||document.querySelector(Ry);if(t)return t;const n=this.getScrollContainer();if(n)return n;return Boolean(document.body.querySelector(`${zy}, ${Oy}`))&&(this.isSharePage()||e?.allowBodyFallback)||e?.allowBodyFallback?document.body:null}getChatContentSelectors(){return [zy,Oy]}getUserQuerySelector(){return zy}extractUserQueryText(e){const t=this.findUserContentRoot(e);if(!t)return "";const n=t.cloneNode(true);return n.querySelectorAll(".gh-user-query-markdown, button, [role=button], svg, [aria-hidden=true]").forEach(e=>e.remove()),this.extractTextWithLineBreaks(n).trim()}extractUserQueryMarkdown(e){return this.extractUserQueryText(e)}extractUserQueryExportContent(e){return this.extractZaiUserQueryExportContent(e)}replaceUserQueryContent(e,t){const n=this.findUserContentRoot(e);if(!n)return false;if(e.querySelector(".gh-user-query-markdown"))return false;const r=document.createElement("div");if(r.className=`${n instanceof HTMLElement?n.className:""} gh-user-query-markdown gh-markdown-preview`.trim(),r.innerHTML=t,n instanceof HTMLElement){const e=n.getAttribute("style");e&&r.setAttribute("style",e);}if(n===e){const t=document.createElement("div");for(t.className="gh-user-query-raw";e.firstChild;)t.appendChild(e.firstChild);return t.style.display="none",e.appendChild(t),e.appendChild(r),true}return n.style.display="none",n.after(r),true}getExportConfig(){return {userQuerySelector:$y,assistantResponseSelector:Uy,turnSelector:null,useShadowDOM:false}}async prepareConversationExport(e){this.exportIncludeThoughtsOverride=e.includeThoughts,this.clearExportMarkers(),this.clearExportAttachmentCache();const t=this.getConversationContentContainer({allowBodyFallback:true})||document.body;return this.markExportMessages(t),await this.prepareExportAttachmentCache(t),null}async restoreConversationAfterExport(e,t){this.clearExportMarkers(),this.exportIncludeThoughtsOverride=null,this.clearExportAttachmentCache();}async extractExportMessages(e){const t=this.extractZaiExportMessages();return t.length>0?t:null}async extractExportBundle(e){return this.createExportBundleFromMessages(e=>this.extractZaiExportMessages(e))}clearExportMarkers(){document.querySelectorAll(`[${Fy}]`).forEach(e=>e.removeAttribute(Fy));}shouldSkipExportElement(e){return !!e.closest(".gh-root")||(!!e.closest(".gh-user-query-markdown")||!!e.closest(jy))}collectExportMessages(e){const t=Array.from(e.querySelectorAll(zy)),n=this.collectTopLevelBlocks(t).filter(e=>!this.shouldSkipExportElement(e)),r=Array.from(e.querySelectorAll(Oy));return {users:n,assistants:this.collectTopLevelBlocks(r).filter(e=>!this.shouldSkipExportElement(e)&&!e.closest(zy))}}markExportMessages(e){const{users:t,assistants:n}=this.collectExportMessages(e);t.forEach(e=>e.setAttribute(Fy,"user")),n.forEach(e=>e.setAttribute(Fy,"assistant"));}extractZaiExportMessages(e){const t=this.getConversationContentContainer({allowBodyFallback:true})||document.body,{users:n,assistants:r}=this.collectExportMessages(t);return [...n.map(e=>({role:"user",element:e})),...r.map(e=>({role:"assistant",element:e}))].sort((e,t)=>this.compareDomOrder(e.element,t.element)).map(({role:t,element:n})=>({role:t,content:("user"===t?this.extractZaiUserQueryExportContent(n,e):this.extractAssistantResponseText(n)).trim()})).filter(e=>e.content.length>0)}compareDomOrder(e,t){if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0}shouldIncludeThoughtsInExport(){return "boolean"!=typeof this.exportIncludeThoughtsOverride||this.exportIncludeThoughtsOverride}formatAsThoughtBlockquote(e){return ["> **💭 思考过程**",">",...e.replace(/\r\n/g,"\n").replace(/\n{3,}/g,"\n\n").split("\n").map(e=>e.trim().length>0?`> ${e}`:">")].join("\n")}extractThoughtBlockquotesFromElement(e){const t=[],n=[],r=e=>{const t=document.createElement("div");return Array.from(e.childNodes).forEach(e=>t.appendChild(e.cloneNode(true))),Fi(t)||this.extractTextWithLineBreaks(e)},o=Array.from(e.querySelectorAll("blockquote[slot='content'], .thinking-block blockquote, .thinking-chain-container blockquote"));if(o.length>0){const e=this.collectTopLevelBlocks(o);for(const o of e){const e=r(o).trim();e&&t.push(this.formatAsThoughtBlockquote(e));const i=o.closest(".thinking-chain-container")||o.closest(".thinking-block")||o;n.push(i);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}const i=Array.from(e.querySelectorAll(jy)),a=this.collectTopLevelBlocks(i);for(const s of a){const e=r(s.querySelector("blockquote[slot='content']")||s.querySelector("blockquote")||s).trim();e&&t.push(this.formatAsThoughtBlockquote(e)),n.push(s);}return {blocks:t,removalNodes:this.collectTopLevelBlocks(n)}}extractAssistantResponseText(e){const t=e.cloneNode(true),n=this.shouldIncludeThoughtsInExport(),r=this.extractThoughtBlockquotesFromElement(t),o=n?r.blocks:[];r.removalNodes.length>0&&r.removalNodes.forEach(e=>e.remove()),t.querySelectorAll(jy).forEach(e=>e.remove());const i=this.findAssistantBodyRoot(t).cloneNode(true);i.querySelectorAll(Wy).forEach(e=>e.remove());const a=(Fi(i)||this.extractTextWithLineBreaks(i)).trim();if(o.length>0){const e=o.join("\n\n");return a?`${e}\n\n${a}`:e}return a}findAssistantBodyRoot(e){if(this.isAssistantBodyElement(e))return e;const t=Array.from(e.querySelectorAll(By)).filter(e=>!e.closest(zy)&&!e.closest(jy)&&!e.closest(".gh-root"));return this.collectTopLevelBlocks(t)[0]||e}isAssistantBodyElement(e){return e.matches(By)&&!e.closest(zy)&&!e.closest(jy)}extractOutline(e=6,t=false,n=false){const r=[],o=this.getConversationContentContainer();if(!o)return r;const i=this.getUserQuerySelector();if(!i)return r;const a=[];for(let g=1;g<=e;g++)a.push(`h${g}`);const s=`${i}, ${a.join(", ")}`,l=Array.from(o.querySelectorAll(i)),c=this.collectTopLevelBlocks(l).filter(e=>!this.shouldSkipOutlineElement(e)),d=new Set(c),u=Array.from(o.querySelectorAll(s)).filter(e=>e.matches(i)?d.has(e):!this.shouldSkipOutlineElement(e)),h=(e,t,n)=>{if(!e)return 0;try{if(n){const n=o.querySelectorAll(Oy);let r="";for(const o of Array.from(n)){const n=e.compareDocumentPosition(o);if(!(n&Node.DOCUMENT_POSITION_FOLLOWING))continue;if(t){const e=t.compareDocumentPosition(o);if(!(e&Node.DOCUMENT_POSITION_PRECEDING))continue}const i=o.cloneNode(!0);i.querySelectorAll(`${jy}, .gh-user-query-markdown`).forEach(e=>e.remove()),r+=i.textContent||"";}return r.trim().length}if(t)return this.calculateRangeWordCount(e,t,o);const r=o.querySelectorAll(i);let a=!1,s=null;for(const t of Array.from(r)){if(a){s=t;break}(t===e||t.contains(e)||e.contains(t))&&(a=!0);}if(s)return this.calculateRangeWordCount(e,s,o);const l=o.querySelectorAll(Oy);if(l.length>0){const t=l[l.length-1];return this.calculateRangeWordCount(e,null,t)}return this.calculateRangeWordCount(e,null,o)}catch{return 0}};return u.forEach((o,a)=>{const s=o.tagName.toLowerCase(),l=o.matches(i),c=/^h[1-6]$/.test(s);let d,g=false;if(t&&l&&(g=true),c&&!this.shouldSkipOutlineElement(o)){const t=parseInt(s.charAt(1),10);!Number.isNaN(t)&&t<=e&&(g=true);}if(g){if(l){let e=this.extractUserQueryText(o),t=false;e.length>200&&(e=e.substring(0,200),t=true),d={level:0,text:e,element:o,isUserQuery:true,isTruncated:t};}else {d={level:parseInt(s.charAt(1),10),text:o.textContent?.trim()||"",element:o,isUserQuery:false};}if(n){let e=null;for(let t=a+1;tt.id===e);return t?.title||null}getConversationList(){const e=document.querySelectorAll(Vy);if(!e.length)return [];const t=this.getCurrentCid()||void 0,n=[];return e.forEach(e=>{const r=this.extractConversationId(e);if(!r)return;const o=this.extractConversationTitle(e);o&&n.push({id:r,cid:t,title:o,url:`https://chat.z.ai/c/${r}`,isActive:r===this.getSessionId()});}),n}getConversationObserverConfig(){return {selector:Vy,shadow:false,extractInfo:e=>{const t=this.extractConversationId(e);if(!t)return null;const n=this.extractConversationTitle(e);return n?{id:t,title:n,url:`https://chat.z.ai/c/${t}`,cid:this.getCurrentCid()||void 0,isActive:t===this.getSessionId()}:null},getTitleElement:e=>e.querySelector(Ky)||e}}getSidebarScrollContainer(){return document.querySelector("#sidebar .overflow-y-auto")}getScrollContainer(){const e=this.collectScrollAnchorRoots(),t=this.pickBestScrollableAncestor(e);if(t)return t;const n=Array.from(document.querySelectorAll("[data-pane-id]"));return this.pickBestScrollableAncestor(n)}navigateToConversation(e,t){const n=document.querySelectorAll(Vy);for(const r of Array.from(n)){if(this.extractConversationId(r)!==e)continue;const t=r.querySelector("button");if(t)return t.click(),true}return super.navigateToConversation(e,t||`https://chat.z.ai/c/${e}`)}getModelName(){const e=this.getSelectedModelFromStorage();if(e)return e;const t=this.findElementBySelectors(qy),n=t?.textContent?.trim();return n||null}lockModel(e,t){this.isNewConversation()&&super.lockModel(e,t);}getModelSwitcherConfig(e){return this.isNewConversation()?{targetModelKeyword:e,selectorButtonSelectors:[...qy],menuItemSelector:'button[aria-label="model-item"], button[data-melt-collapsible-trigger]',checkInterval:1e3,maxAttempts:12,menuRenderDelay:400,subMenuSelector:"button[data-melt-collapsible-trigger]",subMenuTriggers:["更多模型","more"]}:null}async toggleTheme(e){try{const t="undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,n="system"===e?t?"dark":"light":e;localStorage.setItem(Zy,e),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(n),document.documentElement.style.colorScheme=n,document.body.style.colorScheme=n;const r=document.querySelector('meta[name="theme-color"]');return r&&r.setAttribute("content",Yy[n]),window.dispatchEvent(new StorageEvent("storage",{key:Zy,newValue:e,storageArea:localStorage})),!0}catch(t){return console.error("[ZaiAdapter] toggleTheme error:",t),false}}getWidthSelectors(){return [{selector:`${Ry} [class*="max-w-[1000px]"]`,property:"max-width"},{selector:`${Ry} [class*="max-w-[960px]"]`,property:"max-width"}]}getUserQueryWidthSelectors(){return [{selector:`${Ry} .chat-user [class*="max-w-[90%]"]`,property:"max-width",noCenter:true}]}getZenModeConfig(){return {hide:["#sidebar"]}}extractConversationTitle(e){const t=e.querySelector(Ky);return t?.textContent?.trim()||""}getSharePageTitle(){const e=this.getDocumentConversationTitle()||"";if(!e)return this.getSessionName();const t=e.split(" | ")[0]?.trim();return t||this.getSessionName()}collectScrollAnchorRoots(){const e=Array.from(document.querySelectorAll(`${zy}, ${Oy}`));return this.collectTopLevelBlocks(e).filter(e=>!e.closest(".gh-root, .gh-table-container"))}pickBestScrollableAncestor(e){const t=new Map;for(const o of e){const e=this.findScrollableAncestor(o);if(!e)continue;const n=t.get(e)||0;t.set(e,n+this.scoreScrollContainer(e));}let n=null,r=-1;for(const[o,i]of t.entries())i>r&&(n=o,r=i);return r>0?n:null}findScrollableAncestor(e){let t=e instanceof HTMLElement?e:e?.parentElement||null;for(;t&&t!==document.body;){if(this.isPrimaryScrollContainer(t))return t;t=t.parentElement;}return null}isPrimaryScrollContainer(e){if(!e.isConnected)return false;const t=window.getComputedStyle(e);if("auto"!==t.overflowY&&"scroll"!==t.overflowY)return false;if(e.scrollHeight<=e.clientHeight)return false;if(e.clientHeight<220)return false;const n=e.getBoundingClientRect();return !(n.width<320||n.height<220)}scoreScrollContainer(e){const t=window.innerHeight||document.documentElement.clientHeight||0,n=window.innerWidth||document.documentElement.clientWidth||0,r=e.getBoundingClientRect(),o=e.querySelectorAll(zy).length,i=e.querySelectorAll(Oy).length;let a=0;return a+=160*Math.min(o,60),a+=160*Math.min(i,60),o>0&&i>0&&(a+=700),e.scrollTop>0&&(a+=900),r.height>=.35*t&&(a+=500),r.width>=.45*n&&(a+=350),e.closest("[data-pane-id]")&&(a+=300),e.querySelector("textarea, #chat-input")&&(a-=700),e.matches(".scrollbar-none")&&e.scrollWidth>e.clientWidth&&(a-=400),a}shouldSkipOutlineElement(e){return !this.isOutlineElementVisible(e)||(!!e.closest(".gh-root")||(!!this.isInRenderedMarkdownContainer(e)||!!e.closest(jy)))}isOutlineElementVisible(e){if(!(e instanceof HTMLElement))return false;if(!e.isConnected)return false;if(e.closest("[hidden], [aria-hidden='true']"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===Number(t.opacity))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}clearExportAttachmentCache(){this.exportUserAttachmentsByMessageId.clear(),this.exportShareTitle=null;}async prepareExportAttachmentCache(e){const t=this.getSessionId();if(t)try{const n=await this.collectExportMessageIds(e);if(0===n.length)return;const r=await fetch(`/api/v1/chats/${encodeURIComponent(t)}/messages/batch`,{method:"POST",credentials:"include",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({ids:n})});if(!r.ok)throw new Error(`messages/batch failed with ${r.status}`);const o=await r.json(),i=o?.data||{};Object.values(i).forEach(e=>{if(!e?.id||"user"!==e.role)return;const t=this.extractZaiApiUserAttachments(e.files||[]);t.length>0&&this.exportUserAttachmentsByMessageId.set(e.id,t);});}catch(n){console.warn("[ZaiAdapter] Failed to load export attachment metadata:",n);}}async collectExportMessageIds(e){const t=this.isSharePage()?await this.fetchShareMessageIds():[],n=this.collectDomMessageIds(e);return Array.from(new Set([...t,...n]))}async fetchShareMessageIds(){const e=this.getSessionId();if(!e)return [];const t=await fetch(`/api/v1/chats/share/${encodeURIComponent(e)}`,{credentials:"include",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`share metadata failed with ${t.status}`);const n=await t.json();this.exportShareTitle=n?.title||null;const r=n?.chat?.history?.messages||{};return Object.keys(r)}collectDomMessageIds(e){const t=[];return Array.from(e.querySelectorAll('[id^="message-"]')).forEach(e=>{const n=this.extractZaiMessageId(e);n&&t.push(n);}),t}extractZaiMessageId(e){const t=e.id?.startsWith("message-")?e:e.closest('[id^="message-"]'),n=(t?.id||"").match(Xy);return n?.[1]||""}extractZaiApiUserAttachments(e){return e.map(e=>this.extractZaiApiUserAttachment(e)).filter(e=>Boolean(e))}extractZaiApiUserAttachment(e){const t=e.file?.meta,n=t?.name||e.file?.filename||e.name||e.id||"attachment",r=this.decodeZaiAttachmentName(n)||"attachment",o=t?.content_type||e.media||e.type||"",i=fa(t?.cdn_url||e.url||"");return {kind:this.isZaiImageAttachment(r,o,i)?"image":"file",name:r,source:ba(i)?i:"",type:o,size:t?.size||e.size}}extractZaiUserQueryExportContent(e,t){const n=this.extractUserQueryText(e),r=this.extractZaiUserAttachments(e);if(0===r.length)return n;const o=this.formatZaiUserImageAttachments(r,t),i=this.formatZaiUserFileAttachments(r,t),a=i.length>0?`${se("exportAttachmentsLabel")}:\n${i.join("\n")}`:"";return [o.join("\n\n"),a,n].filter(Boolean).join("\n\n")}extractZaiUserAttachments(e){const t=this.extractZaiMessageId(e),n=t&&this.exportUserAttachmentsByMessageId.get(t)||[],r=this.extractZaiUserAttachmentsFromDom(e),o=[],i=new Set,a=e=>{const t=this.getZaiAttachmentKeys(e);t.some(e=>i.has(e))||(t.forEach(e=>i.add(e)),o.push(e));};return n.forEach(a),r.forEach(a),o}getZaiAttachmentKeys(e){const t=[],n=e.kind,r=e.name.trim().toLowerCase(),o=this.getZaiAttachmentTypeKey(e),i=e.size?this.formatZaiFileSize(e.size).toLowerCase():"",a=this.getZaiAttachmentSourceKey(e.source);return a&&t.push(`${n}:source:${a}`),r&&o&&t.push(`${n}:name-type:${r}:${o}`),r&&i&&t.push(`${n}:name-size:${r}:${i}`),t.length>0?t:[`${n}:fallback:${r}:${o}`]}getZaiAttachmentTypeKey(e){const t=e.name.match(/\.([a-z0-9]{1,10})$/i)?.[1];if(t)return t.toLowerCase();const n=e.type.trim().toLowerCase(),r=n.match(/\/([a-z0-9.+-]+)$/i)?.[1];return r?r.replace(/^plain$/,"txt").replace(/^jpeg$/,"jpg"):n}getZaiAttachmentSourceKey(e){if(!e)return "";if(/^(blob:|data:)/i.test(e))return e;try{const t=new URL(e,window.location.href);return `${t.hostname}${t.pathname}`.toLowerCase()}catch{return e.split("?")[0].toLowerCase()}}extractZaiUserAttachmentsFromDom(e){const t=e.matches(zy)?e:e.closest(zy);if(!t)return [];const n=Array.from(t.querySelectorAll("button")).filter(e=>{const t=e.textContent?.replace(/\s+/g," ").trim()||"";return !!t&&(!!this.looksLikeZaiAttachmentCard(e,t)&&!e.closest(".gh-root, .gh-user-query-markdown"))}),r=[],o=new Set;return n.forEach(e=>{const t=this.extractZaiDomUserAttachment(e);if(!t)return;const n=this.getZaiAttachmentKeys(t);n.some(e=>o.has(e))||(n.forEach(e=>o.add(e)),r.push(t));}),r}looksLikeZaiAttachmentCard(e,t){return !!e.querySelector("img[data-cy='image'], img.not-prose")||!!/\.[A-Za-z0-9]{1,10}\b/.test(t)&&(/\b(?:B|KB|MB|GB|TB)\b/i.test(t)||Boolean(e.querySelector("img[src*='/icons/']")))}extractZaiDomUserAttachment(e){const t=this.extractZaiCleanTextParts(e),{name:n,type:r,sizeLabel:o}=this.parseZaiAttachmentLabel(t),i=this.extractZaiDownloadableSource(e),a=n||this.extractZaiFilenameFromUrl(i)||"attachment";return {kind:this.isZaiImageAttachment(a,r,i)?"image":"file",name:a,source:i,type:r,size:this.parseZaiSizeLabel(o)}}parseZaiAttachmentLabel(e){const t=e.map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean),n=t.find(e=>/\.[A-Za-z0-9]{1,10}$/.test(e))||t[0]||"",r=t.find(e=>/^[A-Za-z0-9.+-]{1,16}$/.test(e)&&!/\d/.test(e))||n.match(/\.([A-Za-z0-9]{1,10})$/)?.[1]||"";return {name:n,type:r,sizeLabel:t.find(e=>/^\d+(?:\.\d+)?\s*(?:B|KB|MB|GB|TB)$/i.test(e))||""}}extractZaiCleanTextParts(e){const t=e.cloneNode(true);t.querySelectorAll("svg, [aria-hidden='true'], style, script").forEach(e=>e.remove());const n=[],r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let o=r.nextNode();for(;o;){const e=o.textContent?.replace(/\s+/g," ").trim();e&&n[n.length-1]!==e&&n.push(e),o=r.nextNode();}return n}extractZaiDownloadableSource(e){const t=Array.from(e.querySelectorAll("img")).find(e=>e instanceof HTMLImageElement&&Boolean(this.normalizeZaiAttachmentSource(e.currentSrc||e.src||e.getAttribute("src")||"")));if(t){const e=this.normalizeZaiAttachmentSource(t.currentSrc||t.src||t.getAttribute("src")||"");if(e)return e}const n=[e,...Array.from(e.querySelectorAll("*"))];for(const r of n)for(const e of Gy){const t=this.normalizeZaiAttachmentSource(r.getAttribute(e)||"");if(t)return t}return ""}normalizeZaiAttachmentSource(e){const t=fa(e);if(!t||!ba(t))return "";try{const e=new URL(t,window.location.href);if(e.hostname===My&&/^\/icons\//i.test(e.pathname))return "";if("z-cdn.chatglm.cn"===e.hostname&&/\/z-ai\/static\/logo\.svg$/i.test(e.pathname))return ""}catch{return ""}return t}isZaiImageAttachment(e,t,n){const r=`${e} ${t} ${n}`.toLowerCase();return /\bimage\b/.test(r)||/图片|圖像|图像/.test(r)||/\.(png|jpe?g|webp|gif|avif|svg)(?:$|[?#\s])/.test(r)||/^data:image\//i.test(n)}formatZaiUserImageAttachments(e,t){return _a(e,t,{siteId:this.getSiteId()})}formatZaiUserFileAttachments(e,t){return Ia(e,t,{siteId:this.getSiteId(),getLabel:e=>{const t=e.size?`, ${this.formatZaiFileSize(e.size)}`:"";return e.type?e.name.toLowerCase().endsWith(e.type.toLowerCase())?`${e.name}${t}`:`${e.name} (${e.type}${t})`:`${e.name}${t}`}})}parseZaiSizeLabel(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)$/i);if(!t)return;const n=Number(t[1]);if(!Number.isFinite(n))return;const r=t[2].toUpperCase(),o="TB"===r?1024**4:"GB"===r?1024**3:"MB"===r?1048576:"KB"===r?1024:1;return Math.round(n*o)}formatZaiFileSize(e){if(!Number.isFinite(e)||e<=0)return "";const t=["B","KB","MB","GB","TB"];let n=e,r=0;for(;n>=1024&&r=10||0===r?Math.round(n).toString():n.toFixed(1)} ${t[r]}`}extractZaiFilenameFromUrl(e){if(!e)return "";try{const t=new URL(e,window.location.href).pathname;return decodeURIComponent(t.split("/").pop()||"")}catch{return ""}}decodeZaiAttachmentName(e){try{return decodeURIComponent(e)}catch{return e}}findUserContentRoot(e){const t=(e.matches(zy)?e:e.closest(zy))||e;for(const n of Hy){const e=t.querySelector(n);if(!e)continue;if(e.closest(".gh-user-query-markdown"))continue;if(e.closest("button, [role=button]"))continue;const r=e.textContent?.trim();if(r)return e}return t}collectTopLevelBlocks(e){return e.length<=1?e:e.filter(t=>!e.some(e=>e!==t&&e.contains(t)))}extractConversationId(e){const t=["data-conversation-id","data-chat-id","data-session-id","data-cid","data-id"];for(const o of t){const t=this.matchConversationId(e.getAttribute(o));if(t)return t;const n=e.querySelector(`[${o}]`),r=this.matchConversationId(n?.getAttribute(o));if(r)return r}const n=e.getAttribute("aria-controls"),r=this.matchConversationId(n);return r||""}matchConversationId(e){if(!e)return "";const t=e.match(Jy);return t?.[0]||""}getSelectedModelFromStorage(){try{const e=localStorage.getItem("selectedModels");if(!e)return null;const t=JSON.parse(e);return Array.isArray(t)&&"string"==typeof t[0]?t[0]:"string"==typeof t?t:null}catch{return null}}}];function tv(){for(const e of ev)if(e.match())return e;return null}const nv=Object.freeze(Object.defineProperty({__proto__:null,SiteAdapter:gs,getAdapter:tv,getAllAdapters:function(){return [...ev]}},Symbol.toStringTag,{value:"Module"}));let rv=null;const ov=Bo()($o((e,t)=>(rv=()=>e({_hasHydrated:true}),{conversations:{},lastUsedFolderId:"inbox",_hasHydrated:false,addConversation:t=>e(e=>({conversations:{...e.conversations,[t.id]:t}})),updateConversation:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],...n,updatedAt:Date.now()}}}:e),deleteConversation:t=>e(e=>{const{[t]:n,...r}=e.conversations;return {conversations:r}}),moveToFolder:(t,n)=>e(e=>e.conversations[t]?{conversations:{...e.conversations,[t]:{...e.conversations[t],folderId:n,updatedAt:Date.now()}}}:e),togglePin:n=>{const r=t();if(!r.conversations[n])return false;const o=!r.conversations[n].pinned;return e(e=>({conversations:{...e.conversations,[n]:{...e.conversations[n],pinned:o,updatedAt:Date.now()}}})),o},setConversationTags:(t,n)=>e(e=>{if(!e.conversations[t])return e;const r={...e.conversations[t]};return n.length>0?r.tagIds=n:delete r.tagIds,{conversations:{...e.conversations,[t]:r}}}),removeTagFromAll:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))if(i.tagIds?.includes(t)){const e=i.tagIds.filter(e=>e!==t);n[o]={...i,tagIds:e.length>0?e:void 0},r=true;}else n[o]=i;return r?{conversations:n}:e}),moveConversationsToInbox:t=>e(e=>{const n={};let r=false;for(const[o,i]of Object.entries(e.conversations))i.folderId===t?(n[o]={...i,folderId:"inbox"},r=true):n[o]=i;return r?{conversations:n}:e}),setLastUsedFolderId:t=>e({lastUsedFolderId:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"conversations",storage:Oo(()=>di),partialize:e=>({conversations:e.conversations,lastUsedFolderId:e.lastUsedFolderId}),onRehydrateStorage:()=>()=>{rv?.();}})),iv=()=>ov.getState(),av=Object.freeze(Object.defineProperty({__proto__:null,getConversationsStore:iv,useConversationsStore:ov},Symbol.toStringTag,{value:"Module"})),sv=(e,t)=>{const n=(e||"").trim(),r=(t||"").trim();return r&&n.startsWith(r)?n.slice(r.length).trim():n},lv=e=>({...e,name:sv(e.name,e.icon)});let cv=null;const dv=Bo()($o((e,t)=>(cv=()=>e({_hasHydrated:true}),{folders:ro,_hasHydrated:false,addFolder:(t,n)=>{const r={id:"folder_"+Date.now(),name:sv(t,n),icon:n};return e(e=>({folders:[...e.folders,r]})),r},updateFolder:(t,n)=>e(e=>({folders:e.folders.map(e=>{if(e.id!==t)return e;const r={...e,...n};return {...r,name:sv(r.name,r.icon)}})})),deleteFolder:t=>{"inbox"!==t&&e(e=>({folders:e.folders.filter(e=>e.id!==t)}));},moveFolder:(t,n)=>e(e=>{const r=e.folders.findIndex(e=>e.id===t);if(-1===r||0===r)return e;const o="up"===n?r-1:r+1;if(o<=0||o>=e.folders.length)return e;const i=[...e.folders];return [i[r],i[o]]=[i[o],i[r]],{folders:i}}),reorderFolders:t=>e(e=>{const n=e.folders.find(e=>"inbox"===e.id||!!e.isDefault),r=e.folders.filter(e=>"inbox"!==e.id&&!e.isDefault);return {folders:[...n?[n]:[],...t.map(e=>r.find(t=>t.id===e)).filter(Boolean),...r.filter(e=>!t.includes(e.id))]}}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"folders",storage:Oo(()=>di),partialize:e=>({folders:e.folders}),merge:(e,t)=>{const n=e;return n?.folders?{...t,...n,folders:(r=n.folders,r.map(lv))}:t;var r;},onRehydrateStorage:()=>()=>{cv?.();}})),uv=()=>dv.getState(),hv=Object.freeze(Object.defineProperty({__proto__:null,getFoldersStore:uv,useFoldersStore:dv},Symbol.toStringTag,{value:"Module"}));let gv=null;const pv=Bo()($o((e,t)=>(gv=()=>e({_hasHydrated:true}),{tags:[],_hasHydrated:false,addTag:(n,r)=>{if(t().tags.some(e=>e.name.toLowerCase()===n.toLowerCase()))return null;const o={id:"tag_"+Date.now()+"_"+Math.random().toString(36).substr(2,5),name:n,color:r};return e(e=>({tags:[...e.tags,o]})),o},updateTag:(n,r,o)=>{if(t().tags.some(e=>e.id!==n&&e.name.toLowerCase()===r.toLowerCase()))return null;let i=null;return e(e=>({tags:e.tags.map(e=>e.id===n?(i={...e,name:r,color:o},i):e)})),i},deleteTag:t=>e(e=>({tags:e.tags.filter(e=>e.id!==t)})),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"tags",storage:Oo(()=>di),partialize:e=>({tags:e.tags}),onRehydrateStorage:()=>()=>{gv?.();}})),mv=()=>pv.getState(),fv=Object.freeze(Object.defineProperty({__proto__:null,getTagsStore:mv,useTagsStore:pv},Symbol.toStringTag,{value:"Module"}));class bv{siteAdapter;observerConfig=null;sidebarObserverStop=null;observerContainer=null;titleWatcher=null;pollInterval=null;geminiMigrationTimer=null;geminiMigrationRetryCount=0;syncUnpin=false;syncDelete=true;onChangeCallbacks=[];onExportProgressCallbacks=[];constructor(e){this.siteAdapter=e;}get folders(){return uv().folders}get conversations(){return iv().conversations}get lastUsedFolderId(){return iv().lastUsedFolderId}get tags(){return mv().tags} /** * 订阅数据变更事件 * @returns 取消订阅函数 */onDataChange(e){return this.onChangeCallbacks.push(e),()=>{this.onChangeCallbacks=this.onChangeCallbacks.filter(t=>t!==e);}}onExportProgress(e){return this.onExportProgressCallbacks.push(e),()=>{this.onExportProgressCallbacks=this.onExportProgressCallbacks.filter(t=>t!==e);}}notifyDataChange(){this.onChangeCallbacks.forEach(e=>e());}notifyExportProgress(e){this.onExportProgressCallbacks.forEach(t=>t(e));}async init(){await this.waitForHydration();"pending_email"===this.tryMigrateGeminiLegacyCidToEmail()&&this.startGeminiMigrationRetry();const e=await(si||(si=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(ai,t=>{const n=t?.[ai];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=1e4?e(true):chrome.storage.local.remove(ai,()=>e(false)):e(true);}):e(false);}),si));if(0===Object.keys(this.getAllConversations()).length&&this.siteAdapter.loadAllConversations&&!e)try{await this.waitForSidebarReady()&&await this.autoFullSync();}catch{}this.startSidebarObserver();}tryMigrateGeminiLegacyCidToEmail(){if(this.siteAdapter.getSiteId()!==lo)return "noop";const e=this.conversations,t=Object.entries(e).filter(([e,t])=>this.isGeminiConversation(t));if(0===t.length)return "noop";const n=t.filter(([e,t])=>this.isLegacyGeminiCid(t.cid));if(0===n.length)return "noop";const r=this.siteAdapter.getCurrentCid?.();if(!this.isEmailCid(r))return "pending_email";const o=this.getGeminiUserIndexFromPath(),i=n.some(([e,t])=>(t.cid||"0")===o),a=t.some(([e,t])=>t.cid===r),s=new Set(n.map(([e,t])=>t.cid||"0"));let l=null;if(i?l=o:a||1!==s.size||(l=Array.from(s)[0]),!l)return "noop";const c=n.filter(([e,t])=>(t.cid||"0")===l);if(0===c.length)return "noop";const d={...e},u=this.getGeminiUserPathPrefix();return c.forEach(([e,t])=>{d[e]={...t,cid:r,url:this.buildGeminiConversationUrl(e,u)};}),ov.setState({conversations:d}),this.notifyDataChange(),console.warn(`[ConversationManager] Gemini legacy cid migrated: ${l} -> ${r}, updated ${c.length} conversations.`),"migrated"}startGeminiMigrationRetry(){if(this.siteAdapter.getSiteId()!==lo)return;if(this.geminiMigrationTimer)return;this.geminiMigrationRetryCount=0,this.geminiMigrationTimer=setInterval(()=>{const e=this.tryMigrateGeminiLegacyCidToEmail();this.geminiMigrationRetryCount+=1,("pending_email"!==e||this.geminiMigrationRetryCount>=120)&&this.stopGeminiMigrationRetry();},1500);}stopGeminiMigrationRetry(){this.geminiMigrationTimer&&(clearInterval(this.geminiMigrationTimer),this.geminiMigrationTimer=null),this.geminiMigrationRetryCount=0;}isEmailCid(e){return "string"==typeof e&&e.includes("@")}isLegacyGeminiCid(e){return !e||/^\d+$/.test(e)}getGeminiUserIndexFromPath(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?e[1]:"0"}getGeminiUserPathPrefix(){const e=window.location.pathname.match(/^\/u\/(\d+)(?:\/|$)/);return e?`/u/${e[1]}`:""}isGeminiConversation(e){return e.siteId===lo||(!e.siteId||e.siteId===lo)&&("string"==typeof e.url&&e.url.includes("gemini.google.com"))}buildGeminiConversationUrl(e,t){return `https://gemini.google.com${t}/app/${e}`}async waitForHydration(){const e=[dv,pv,ov];await Promise.all(e.map(e=>new Promise(t=>{if(e.getState()._hasHydrated)return void t();const n=e.subscribe(e=>{e._hasHydrated&&(n(),t());});})));}async waitForSidebarReady(e=1e4){const t=Date.now();for(;Date.now()-tsetTimeout(e,250));}return false}async autoFullSync(){await this.siteAdapter.loadAllConversations(),await new Promise(e=>setTimeout(e,400));let e=0,t=this.siteAdapter.getConversationList().length;for(let n=0;n<10;n++){if(n>0){const e=this.siteAdapter.getSidebarScrollContainer();if(!e)break;const t=e;t.scrollTop=t.scrollHeight,await new Promise(e=>setTimeout(e,400));}const{newCount:r,updatedCount:o}=this.syncConversations(null,true);(r>0||o>0)&&this.notifyDataChange(),await new Promise(e=>setTimeout(e,300));const i=this.siteAdapter.getConversationList().length;if(r>0||i>t?(t=Math.max(t,i),e=0):e++,e>=2)break}}destroy(){this.stopGeminiMigrationRetry(),this.stopSidebarObserver();}updateSettings(e){this.syncUnpin=e.syncUnpin,"boolean"==typeof e.syncDelete&&(this.syncDelete=e.syncDelete);}startSidebarObserver(){if(this.sidebarObserverStop)return;const e=this.siteAdapter.getConversationObserverConfig();if(!e)return;this.observerConfig=e;const t=(n=0)=>{const r=this.siteAdapter.getSidebarScrollContainer()||document;if(e.shadow&&n<5){if(!this.siteAdapter.getSidebarScrollContainer())return void setTimeout(()=>t(n+1),1e3)}this.observerContainer=r,this.sidebarObserverStop=os.each(e.selector,(t,n)=>{this.handleObservedElement(t,n,e);},{parent:r,shadow:e.shadow});};t(),e.shadow&&this.startPolling();}stopSidebarObserver(){this.sidebarObserverStop&&(this.sidebarObserverStop(),this.sidebarObserverStop=null),this.observerContainer=null,this.titleWatcher&&("function"==typeof this.titleWatcher.stop&&this.titleWatcher.stop(),this.titleWatcher=null),this.stopPolling();}handleObservedElement(e,t,n){const r=(o=5)=>{const i=n.extractInfo(e);i?.id?(this.updateConversationFromObservation(i,t),this.monitorConversationTitle(e,i.id)):o>0&&setTimeout(()=>r(o-1),500);};r();}updateConversationFromObservation(e,t){const n=this.conversations[e.id];if(t&&!n)iv().addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:this.lastUsedFolderId,pinned:e.isPinned||false,createdAt:Date.now(),updatedAt:Date.now()}),this.notifyDataChange();else if(n){let t=false;const r={};e.title&&e.title!==n.title&&(r.title=e.title,t=true),e.url&&e.url!==n.url&&(r.url=e.url,t=true),void 0!==e.cid&&e.cid!==n.cid&&(r.cid=e.cid,t=true),void 0!==e.isPinned&&e.isPinned!==n.pinned&&(e.isPinned?(r.pinned=true,t=true):!e.isPinned&&this.syncUnpin&&(r.pinned=false,t=true)),t&&(iv().updateConversation(e.id,r),this.notifyDataChange());}}startPolling(){this.pollInterval||(this.pollInterval=setInterval(()=>{if(!this.observerConfig)return;const e=this.observerConfig,t=os.query(e.selector,{all:true,shadow:e.shadow});Array.isArray(t)&&t.forEach(t=>{const n=e.extractInfo(t);if(!n?.id)return;const r=this.conversations[n.id];r?n.title&&n.title!==r.title&&(iv().updateConversation(n.id,{title:n.title}),this.notifyDataChange()):(this.updateConversationFromObservation(n,true),this.monitorConversationTitle(t,n.id));});},3e3));}stopPolling(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null);}monitorConversationTitle(e,t){if(!e.dataset.ghTitleObserver){if(e.dataset.ghTitleObserver="true",!this.titleWatcher){const e=this.siteAdapter.getSidebarScrollContainer()||document.body;this.titleWatcher=os.watchMultiple(e,{debounce:500});}this.titleWatcher.add(e,()=>{const n=this.observerConfig;if(!n)return;const r=n.extractInfo(e),o=r?.id;if(!o||o!==t)return;const i=this.conversations[t];if(!i)return;let a=false;const s={};r.title&&r.title!==i.title&&(s.title=r.title,a=true),void 0!==r.isPinned&&r.isPinned!==i.pinned&&(r.isPinned?(s.pinned=true,a=true):!r.isPinned&&this.syncUnpin&&(s.pinned=false,a=true)),a&&(iv().updateConversation(t,s),this.notifyDataChange());});}}getFolders(){return this.folders}getConversations(e){const t=this.siteAdapter.getCurrentCid?.()||null;let n=Object.values(this.conversations).filter(e=>this.matchesCid(e,t));return e&&(n=n.filter(t=>t.folderId===e)),n}createFolder(e,t){return uv().addFolder(e,t)}updateFolder(e,t){uv().updateFolder(e,t);}deleteFolder(e){"inbox"!==e&&(iv().moveConversationsToInbox(e),uv().deleteFolder(e));}moveFolder(e,t){uv().moveFolder(e,t);}reorderFolders(e){uv().reorderFolders(e);}async deleteConversation(e){const t=await this.deleteConversations([e]);return t.results.length>0?t.results[0]:{id:e,localDeleted:false,remoteEnabled:this.syncDelete,remoteAttempted:false,remoteSuccess:false,remoteMethod:"none",reason:"not_found"}}async deleteConversations(e){const t=Array.from(new Set(e.filter(Boolean)));if(0===t.length)return {total:0,localDeletedCount:0,remoteAttemptedCount:0,remoteSuccessCount:0,remoteFailedCount:0,failedIds:[],results:[]};const n=t.map(e=>{const t=this.conversations[e];return t?t.siteId&&t.siteId!==this.siteAdapter.getSiteId()?null:{id:t.id,title:t.title,url:t.url}:null}).filter(e=>Boolean(e)),r=new Map;if(this.syncDelete&&n.length>0)try{(await this.siteAdapter.deleteConversationsOnSite(n)).forEach(e=>{r.set(e.id,e);});}catch(c){console.error(`[ConversationManager] deleteConversationsOnSite failed on ${this.siteAdapter.getName()}:`,c);const e=c instanceof Error&&c.message||"remote_delete_failed";n.forEach(t=>{r.set(t.id,{id:t.id,success:false,method:"api",reason:e});});}let o=0,i=0,a=0,s=0;const l=[];return t.forEach(e=>{const t=Boolean(this.conversations[e]),n=this.syncDelete,c=r.get(e),d=c?.method||"none",u=n&&r.has(e)&&"none"!==d,h=u&&(c?.success||false);u&&(i++,h?a++:s++),t&&(iv().deleteConversation(e),o++),l.push({id:e,localDeleted:t,remoteEnabled:n,remoteAttempted:u,remoteSuccess:h,remoteMethod:d,reason:c?.reason||(t?void 0:"not_found")});}),o>0&&this.notifyDataChange(),{total:t.length,localDeletedCount:o,remoteAttemptedCount:i,remoteSuccessCount:a,remoteFailedCount:s,failedIds:l.filter(e=>!e.localDeleted).map(e=>e.id),results:l}}moveConversation(e,t){iv().moveToFolder(e,t);}setLastUsedFolder(e){iv().setLastUsedFolderId(e);}getTags(){return this.tags}createTag(e,t){return mv().addTag(e,t)}updateTag(e,t,n){return mv().updateTag(e,t,n)}deleteTag(e){mv().deleteTag(e),iv().removeTagFromAll(e);}setConversationTags(e,t){iv().setConversationTags(e,t);}togglePin(e){return iv().togglePin(e)}renameConversation(e,t){t&&iv().updateConversation(e,{title:t});}updateConversation(e,t){iv().updateConversation(e,t);}getConversation(e){return this.conversations[e]}getLastUsedFolderId(){return this.lastUsedFolderId}getAllConversations(){const e=this.siteAdapter.getCurrentCid?.()||null,t={};for(const[n,r]of Object.entries(this.conversations))this.matchesCid(r,e)&&(t[n]=r);return t}syncConversations(e=null,t=false,n={}){const r=this.siteAdapter.getConversationList();if(!r||0===r.length)return {newCount:0,updatedCount:0,deletedCount:0};const o=this.conversations;let i=0,a=0,s=0;const l=Date.now(),c=e||this.lastUsedFolderId||"inbox",d=iv(),u=new Set(r.map(e=>e.id));if(r.forEach(e=>{const t=e.id,n=o[t];if(n){const r={};let o=false;n.title!==e.title&&(r.title=e.title,o=true),e.isPinned&&!n.pinned?(r.pinned=true,o=true):!e.isPinned&&n.pinned&&this.syncUnpin&&(r.pinned=false,o=true),n.siteId||(r.siteId=this.siteAdapter.getSiteId(),o=true),e.cid&&!n.cid&&(r.cid=e.cid,o=true),o&&(d.updateConversation(t,r),a++);}else d.addConversation({id:e.id,siteId:this.siteAdapter.getSiteId(),cid:e.cid,title:e.title,url:e.url,folderId:c,pinned:e.isPinned||false,createdAt:l,updatedAt:l}),i++;}),n.syncDeleted){const e=this.siteAdapter.getSiteId(),t=this.siteAdapter.getCurrentCid?.()||null;Object.entries(o).forEach(([n,r])=>{r.siteId===e&&this.matchesCid(r,t)&&(u.has(n)||(d.deleteConversation(n),s++));});}return e&&d.setLastUsedFolderId(e),{newCount:i,updatedCount:a,deletedCount:s}}matchesCid(e,t){const n=this.siteAdapter.getSiteId();return (!e.siteId||e.siteId===n)&&(t?!e.cid||e.cid===t:!e.cid)}getSidebarConversationOrder(){const e=this.siteAdapter.getConversationObserverConfig?.();if(!e)return [];const t=os.query(e.selector,{all:true,shadow:e.shadow});return Array.from(t||[]).map(t=>e.extractInfo?.(t)?.id).filter(e=>Boolean(e))}sanitizeConversationTitleForUse(e,t={}){const n=Ai.getState().settings,r={privacyTitle:n.tab?.privacyTitle||"Google",siteName:this.siteAdapter.getName(),titleFormat:n.tab?.titleFormat};let o=Oa(e,r);const i=Oa(t.managedTitleReference,r);if(i){const t=Oa(e,{...r,hasManagedTitleSignal:true});t&&t!==o&&t===i&&(o=t);}return t.dropLocalizedFallback&&this.isLocalizedFallbackConversationTitle(o)?null:o}isLocalizedFallbackConversationTitle(e){const t=e?.replace(/\s+/g," ").trim();if(!t)return false;return le("untitledConversation").map(e=>e.replace(/\s+/g," ").trim()).includes(t)}formatTime(e){if(!e)return "";const t=new Date(e),n=(new Date).getTime()-t.getTime();return n<6e4?se("justNow"):n<36e5?Math.floor(n/6e4)+se("minutesAgo"):n<864e5?Math.floor(n/36e5)+se("hoursAgo"):n<6048e5?Math.floor(n/864e5)+se("daysAgo"):t.toLocaleDateString()}resolveConversationForExport(e){const t=this.conversations[e],n=this.siteAdapter.getCurrentConversationInfo();if(!n||n.id!==e)return t||null;const r=this.sanitizeConversationTitleForUse(t?.title,{dropLocalizedFallback:true,managedTitleReference:n.title})||this.sanitizeConversationTitleForUse(n.title)||se("untitledConversation"),o=n.url||t?.url||window.location.href,i=n.cid??t?.cid,a=n.isPinned??t?.pinned??false;if(t){const n={};let s=false;if(t.title?.trim()||r===t.title||(n.title=r,s=true),o!==t.url&&(n.url=o,s=true),void 0!==i&&i!==t.cid&&(n.cid=i,s=true),a!==t.pinned&&(n.pinned=a,s=true),s){iv().updateConversation(e,n),this.notifyDataChange();const o={...t,...n,updatedAt:Date.now()};return o.title===r?o:{...o,title:r}}return t.title===r?t:{...t,title:r}}const s=Date.now(),l={id:e,siteId:this.siteAdapter.getSiteId(),cid:i,title:r,url:o,folderId:this.lastUsedFolderId||"inbox",pinned:a,createdAt:s,updatedAt:s};return this.siteAdapter.isSharePage()||(iv().addConversation(l),this.notifyDataChange()),l}async exportConversation(e,t){if(this.siteAdapter.getSessionId()!==e)return Li(se("exportNeedOpenFirst")),false;const n=this.resolveConversationForExport(e);if(!n)return console.error("[ConversationManager] Conversation not found:",e),false;const r=this.siteAdapter.getScrollContainer?.()||null,o=r?.scrollTop??null,i=window.scrollY,a=Ai.getState().settings,s="zip"===a.export?.packaging?"zip":"markdown",l={conversationId:e,format:t,includeThoughts:a.export?.includeThoughts??true,packaging:s};let c=false,d=null;const u=n=>{this.notifyExportProgress({conversationId:e,format:t,stage:n});};try{if(u("loading-history"),r){let e=0,t=0;const n=50;for(;tsetTimeout(e,500));const n=r.scrollHeight;if(n===e){if(t++,t>=3)break}else t=0,e=n;}}u("preparing"),c=!0,d=await this.siteAdapter.prepareConversationExport(l),u("extracting");const e="markdown"===t&&"zip"===s,o=e?await this.siteAdapter.extractExportBundle(l):null,i=o?.messages||await this.extractConversationMessages(l);if(0===i.length)return console.error("[ConversationManager] No messages found"),!1;const f=se("untitledConversation"),b=this.sanitizeConversationTitleForUse(n.title)||f,y=b.replace(/[<>:"/\\|?*]/g,"_").substring(0,50),v=(h=b,g=this.siteAdapter.getName(),p=n.id,m={customUserName:a.export?.customUserName,customModelName:a.export?.customModelName},{title:h||se("exportUntitled"),id:p,url:window.location.href,exportTime:(new Date).toLocaleString(),source:g,customUserName:m?.customUserName,customModelName:m?.customModelName});let w,x,k,S="";if(a.export?.exportFilenameTimestamp){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0");S=`_${t}-${n}-${r}_${o}-${i}-${String(e.getSeconds()).padStart(2,"0")}`;}const C=this.siteAdapter.getName(),A=`${C.replace(/[<>:"/\\|?*]/g,"_")} - `;if("clipboard"===t)return u("copying"),w=$i(v,i),await navigator.clipboard.writeText(w),Li(se("copySuccess")),!0;if("markdown"===t){if(w=$i(v,i),x=`${A}${y}${S}.md`,k="text/markdown;charset=utf-8",e){u("packaging");return !!(await async function(e){const t=new Set,n=Yi(Zi(e.markdownFilename,"conversation.md"),t),r=[{path:n,data:e.markdownContent,mimeType:"text/markdown;charset=utf-8"}],o=[];for(const a of e.assets){const e=Ji(a.relativePath||Xi(a),t);try{const t=await ea(a);r.push({path:e,data:t,mimeType:a.mimeType}),o.push({name:a.name,path:e,kind:a.kind,mimeType:a.mimeType,sourceUrl:a.sourceUrl,description:a.description,included:!0});}catch(i){console.warn("[Exporter] Failed to include export asset:",a.name,i),o.push({name:a.name,path:e,kind:a.kind,mimeType:a.mimeType,sourceUrl:a.sourceUrl,description:a.description,included:!1,error:ta(i)});}}r.push({path:Yi("manifest.json",t),data:JSON.stringify({version:1,metadata:{title:e.metadata.title,id:e.metadata.id,url:e.metadata.url,exportTime:e.metadata.exportTime,source:e.metadata.source},markdown:n,assets:o},null,2),mimeType:"application/json;charset=utf-8"});try{const t=await na(r);return await oa(t,e.packageFilename)}catch(i){return console.error("[Exporter] Package download failed:",i),Li(se("exportFailed")),!1}}({markdownFilename:x,markdownContent:w,assets:this.normalizeExportAssets(o),packageFilename:`${A}${y}${S}.zip`,metadata:v}))&&(Li(se("exportSuccess")),!0)}}else "json"===t?(w=function(e,t){const n={metadata:{title:e.title,id:e.id,url:e.url,exportTime:e.exportTime,source:e.source},messages:t.map(e=>({role:e.role,content:e.content}))};return JSON.stringify(n,null,2)}(v,i),x=`${A}${y}${S}.json`,k="application/json;charset=utf-8"):(w=function(e,t){const n=[];return n.push(`${se("exportMetaConvTitle")}: ${e.title}`),n.push(`${se("exportMetaTime")}: ${e.exportTime}`),n.push(`${se("exportMetaSource")}: ${e.source}`),n.push(`${se("exportMetaUrl")}: ${e.url}`),n.push(""),n.push("=".repeat(50)),n.push(""),t.forEach(t=>{if("user"===t.role){const t=e.customUserName||se("exportUserLabel");n.push(`[${t}]`);}else {const t=e.customModelName||e.source;n.push(`[${t}]`);}n.push(t.content),n.push(""),n.push("-".repeat(50)),n.push("");}),n.join("\n")}(v,i),x=`${A}${y}${S}.txt`,k="text/plain;charset=utf-8");u("downloading");return !!(await ra(w,x,k))&&(Li(se("exportSuccess")),!0)}catch(f){return console.error("[ConversationManager] Export failed:",f),false}finally{if(u("restoring"),c)try{await this.siteAdapter.restoreConversationAfterExport(l,d);}catch(b){console.warn("[ConversationManager] Export state restore failed:",b);}r&&null!==o?r.scrollTop=o:window.scrollTo({top:i,behavior:"auto"}),this.notifyExportProgress(null);}var h,g,p,m;}async extractConversationMessages(e){const t=await this.siteAdapter.extractExportMessages(e);if(null!==t)return t;const n=[],r=this.siteAdapter.getExportConfig?.();if(!r)return console.warn("[ConversationManager] Export config not available"),n;const{userQuerySelector:o,assistantResponseSelector:i,turnSelector:a,useShadowDOM:s}=r;if(a){const e=os.query(a,{all:true,shadow:s})||[];if(e.length>0){const t=(e,t)=>{const n=[];e.matches?.(t)&&n.push(e);return (os.query(t,{parent:e,all:true,shadow:s})||[]).forEach(e=>{n.includes(e)||n.push(e);}),n},r=(e,t)=>{if(e===t)return 0;const n=e.compareDocumentPosition(t);return n&Node.DOCUMENT_POSITION_FOLLOWING?-1:n&Node.DOCUMENT_POSITION_PRECEDING?1:0},a=(e,t)=>{if("user"===e){const r=this.siteAdapter.extractUserQueryExportContent(t);return void n.push({role:e,content:r})}const r=this.siteAdapter.extractAssistantResponseText,o=gs.prototype.extractAssistantResponseText;let i="";r&&r!==o&&(i=r.call(this.siteAdapter,t)),i||(i=Fi(t)||t.textContent?.trim()||""),n.push({role:e,content:i});};return e.forEach(e=>{[...t(e,o).map(e=>({role:"user",element:e})),...t(e,i).map(e=>({role:"assistant",element:e}))].sort((e,t)=>r(e.element,t.element)).forEach(({role:e,element:t})=>{a(e,t);});}),n}}const l=os.query(o,{all:true,shadow:s})||[],c=os.query(i,{all:true,shadow:s})||[],d=Math.max(l.length,c.length);for(let u=0;u!!e.name?.trim()&&(void 0!==e.content||Boolean(e.sourceUrl))):[]}}const yv={getItem:async e=>{const t=await di.getItem("bookmarks");return t?JSON.stringify({state:{bookmarks:JSON.parse(t)},version:0}):null},setItem:async(e,t)=>{const n=JSON.parse(t),r=n.state?.bookmarks||[];await di.setItem("bookmarks",JSON.stringify(r));},removeItem:async e=>{await di.removeItem("bookmarks");}},vv=Bo()($o((e,t)=>({bookmarks:[],addBookmark:(t,n,r,o,i,a)=>{const s={id:crypto.randomUUID(),sessionId:t,siteId:n,cid:r,title:o.text,level:o.level,signature:i,scrollTop:a,timestamp:Date.now()};e(e=>({bookmarks:[...e.bookmarks,s]}));},removeBookmark:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.id!==t)}));},updateBookmark:(t,n)=>{e(e=>({bookmarks:e.bookmarks.map(e=>e.id===t?{...e,...n}:e)}));},toggleBookmark:(e,n,r,o,i,a)=>{const s=t(),l=s.getBookmarkId(e,i);l?s.removeBookmark(l):s.addBookmark(e,n,r,o,i,a);},getBookmarksBySession:e=>t().bookmarks.filter(t=>t.sessionId===e),getBookmarkId:(e,n)=>{const r=t().bookmarks.find(t=>t.sessionId===e&&t.signature===n);return r?r.id:null},clearSessionBookmarks:t=>{e(e=>({bookmarks:e.bookmarks.filter(e=>e.sessionId!==t)}));},clearAllBookmarks:()=>{e({bookmarks:[]});}}),{name:"bookmarks",storage:Oo(()=>yv)})),wv="gh-inline-bookmark",xv="gh-inline-bookmark--bookmarked",kv="gh-inline-bookmark-global-styles",Sv="gh-inline-bookmark-scoped-styles";class Cv{outlineManager;adapter;displayMode="always";unsubscribe=null;unsubscribeBookmarks=null;observer=null;injectDebounceTimer=null;injectedSignatures=new WeakMap;injectedRoots=new WeakSet;constructor(e,t,n="always"){this.outlineManager=e,this.adapter=t,this.displayMode=n,this.injectGlobalStyles(),this.setDisplayMode(n),this.unsubscribe=e.subscribe(()=>{this.injectBookmarkIcons();}),this.unsubscribeBookmarks=vv.subscribe(()=>{this.updateAllIconStates();}),this.startDomObserver(),this.injectBookmarkIcons();}injectGlobalStyles(){if(document.getElementById(kv))return;const e=document.createElement("style");e.id=kv,e.textContent="\n :root {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.5;\n }\n\n body.gh-inline-bookmark-mode-always {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0.3;\n --gh-icon-opacity-parent-hover: 0.3;\n }\n\n body.gh-inline-bookmark-mode-hover {\n --gh-icon-display: flex;\n --gh-icon-opacity-default: 0; /* 默认隐藏 */\n --gh-icon-opacity-parent-hover: 0.5; /* 父元素悬停时显示 */\n }\n\n body.gh-inline-bookmark-mode-hidden {\n --gh-icon-display: none;\n --gh-icon-opacity-default: 0;\n }\n ",document.head.appendChild(e);}injectScopedStyles(e){if(this.injectedRoots.has(e))return;if(e instanceof Document){if(document.getElementById(Sv))return void this.injectedRoots.add(e)}else if(e.querySelector(`#${Sv}`))return void this.injectedRoots.add(e);const t=document.createElement("style");t.id=Sv,t.textContent=`\n .${wv} {\n position: absolute;\n left: var(--gh-icon-left, -24px); /* 支持通过 CSS 变量调整位置 */\n top: 50%;\n transform: translateY(-50%);\n cursor: pointer;\n transition: opacity 0.2s, transform 0.2s;\n align-items: center;\n justify-content: center;\n width: 20px;\n height: 20px;\n z-index: 10;\n color: var(--gh-primary, #f59e0b);\n\n /* 使用 CSS 变量控制显示 */\n display: var(--gh-icon-display, flex);\n opacity: var(--gh-icon-opacity-default, 0.3);\n }\n\n /* Hover Effects depend on local structure, so must be in scoped css */\n .${wv}:hover {\n opacity: 1 !important;\n transform: translateY(-50%) scale(1.1);\n }\n\n .${wv}.${xv} {\n opacity: 1 !important;\n }\n\n /* Parent Hover Effect */\n .gh-has-inline-bookmark:hover .${wv}:not(.${xv}) {\n opacity: var(--gh-icon-opacity-parent-hover, 0.5);\n }\n\n /* Ensure parent relative positioning */\n .gh-has-inline-bookmark {\n position: relative !important;\n }\n `,e instanceof Document?document.head.appendChild(t):e.appendChild(t),this.injectedRoots.add(e);}setDisplayMode(e){this.displayMode=e,document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden"),document.body.classList.add(`gh-inline-bookmark-mode-${e}`),"hidden"===e&&this.removeInjectedIcons();}injectBookmarkIcons(){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const e=this.getInlineBookmarkItems(),t=this.adapter.getSessionId(),n=vv.getState();for(let r=0;r{e.stopPropagation(),e.preventDefault(),this.handleBookmarkClick(o,s,d);}),i.insertBefore(d,i.firstChild),this.injectedSignatures.set(i,s);}}startDomObserver(){const e=this.adapter.getObserveTarget()??document.body;e&&(this.observer=new MutationObserver(()=>{this.scheduleInjectBookmarkIcons();}),this.observer.observe(e,{childList:true,subtree:true}));}scheduleInjectBookmarkIcons(){"hidden"!==this.displayMode&&(this.injectDebounceTimer&&clearTimeout(this.injectDebounceTimer),this.injectDebounceTimer=setTimeout(()=>{this.injectDebounceTimer=null,this.injectBookmarkIcons();},120));}getInlineBookmarkItems(){const e=[],t=new Set,n=n=>{n.forEach(n=>{const r=n.element;r&&!t.has(r)&&(t.add(r),e.push(n));});};return n(this.adapter.getInlineBookmarkItems()),n(this.outlineManager.getFlatItems()),e}createStarSvgElement(e){const t=gp("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:e?"#f59e0b":"none",stroke:e?"#f59e0b":"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}),n=gp("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"});return t.appendChild(n),t}handleBookmarkClick(e,t,n){const r=vv.getState(),o=this.adapter.getSessionId(),i=this.adapter.getSiteId(),a=this.adapter.getCurrentCid()||"",s=this.outlineManager.getScrollContainer(),l=e.element.offsetTop+(s?.scrollTop||0);r.toggleBookmark(o,i,a,e,t,l);}updateAllIconStates(){if("hidden"===this.displayMode)return void this.removeInjectedIcons();const e=vv.getState(),t=this.adapter.getSessionId();os.query(`.${wv}`,{all:true,shadow:true}).forEach(n=>{const r=n,o=r.dataset.signature;if(!o)return;const i=null!==e.getBookmarkId(t,o);i!==r.classList.contains(xv)&&(i?(r.classList.add(xv),r.replaceChildren(this.createStarSvgElement(true))):(r.classList.remove(xv),r.replaceChildren(this.createStarSvgElement(false))));});}removeInjectedIcons(){os.query(`.${wv}`,{all:true,shadow:true}).forEach(e=>e.remove());os.query(".gh-has-inline-bookmark",{all:true,shadow:true}).forEach(e=>{e.classList.remove("gh-has-inline-bookmark");}),this.injectedSignatures=new WeakMap;}static cleanupInjectedArtifacts(){document.getElementById(kv)?.remove(),document.getElementById(Sv)?.remove();os.query(`#${Sv}`,{all:true,shadow:true}).forEach(e=>e.remove());os.query(`.${wv}`,{all:true,shadow:true}).forEach(e=>e.remove());os.query(".gh-has-inline-bookmark",{all:true,shadow:true}).forEach(e=>{e.classList.remove("gh-has-inline-bookmark");}),document.body.classList.remove("gh-inline-bookmark-mode-always","gh-inline-bookmark-mode-hover","gh-inline-bookmark-mode-hidden");}cleanup(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.unsubscribeBookmarks&&(this.unsubscribeBookmarks(),this.unsubscribeBookmarks=null),this.observer&&(this.observer.disconnect(),this.observer=null),this.injectDebounceTimer&&(clearTimeout(this.injectDebounceTimer),this.injectDebounceTimer=null),Cv.cleanupInjectedArtifacts(),this.injectedSignatures=new WeakMap,this.injectedRoots=new WeakSet;}}class Av{siteAdapter;settings;tree=[];flatItems=[];flatNodes=[];scrollNodes=[];scrollPositions=[];scrollHeights=[];scrollPositionsStale=true;sources=[];activeSourceId="conversation";minLevel=1;treeKey="";listeners=[];updateIntervalId=null;isAutoUpdating=false;expandLevel=6;levelCounts={};isAllExpanded=false;searchQuery="";preSearchState=null;preSearchExpandLevel=null;searchLevelManual=false;matchCount=0;bookmarkMode=false;preBookmarkModeState=null;ghostBookmarkIds=new Set;wasGenerating=false;postGenerationScheduled=false;pendingPostGenerationRefresh=false;lastTreeChangeTime=0;fallbackRefreshTimer=null;static FALLBACK_DELAY=3e3;isActive=false;isRefreshing=false;unsubscribeBookmarks=null;onExpandLevelChange;onShowUserQueriesChange;constructor(e,t,n,r){this.siteAdapter=e,this.settings=t,this.onExpandLevelChange=n,this.onShowUserQueriesChange=r,this.sources=this.normalizeSources(this.siteAdapter.getOutlineSources()),this.expandLevel=t.expandLevel??6,window.addEventListener("message",this.handleMessage.bind(this)),this.unsubscribeBookmarks=vv.subscribe(()=>{this.isActive&&this.refresh();});}setActive(e){this.isActive=e,this.updateAutoUpdateState(),e&&this.pendingPostGenerationRefresh&&(this.pendingPostGenerationRefresh=false,this.treeKey="",this.refresh());}updateAutoUpdateState(){const e=this.settings.enabled&&this.settings.autoUpdate&&this.isActive;e&&!this.isAutoUpdating?this.startAutoUpdate():!e&&this.isAutoUpdating&&this.stopAutoUpdate();const t=this.settings.enabled&&this.isActive&&this.siteAdapter.supportsDynamicOutlineSources();t&&!this.sourceObserver?this.startSourceObserver():!t&&this.sourceObserver&&this.stopSourceObserver();}updateSettings(e){this.settings=e,void 0!==e.expandLevel&&(this.expandLevel=e.expandLevel),this.refresh(),this.updateAutoUpdateState();}observer=null;updateDebounceTimer=null;sourceObserver=null;sourceRefreshTimer=null;outlineSourcesSignature="";handleMessage(e){if(e.source!==window)return;const{type:t}=e.data||{};"GH_MONITOR_START"===t?this.settings.autoUpdate&&this.startAutoUpdate():"GH_MONITOR_COMPLETE"===t&&(this.stopAutoUpdate(),this.refresh());}startAutoUpdate(){if(this.observer)return;this.isAutoUpdating=true,this.observer=new MutationObserver(()=>{this.triggerAutoUpdate();});const e=this.siteAdapter.getObserveTarget()??document.body;this.observer.observe(e,{childList:true,subtree:true,characterData:true});}stopAutoUpdate(){this.observer&&(this.observer.disconnect(),this.observer=null),this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null),this.isAutoUpdating=false;}startSourceObserver(){this.sourceObserver||(this.outlineSourcesSignature=this.siteAdapter.getOutlineSourcesSignature(),this.sourceObserver=new MutationObserver(()=>{this.sourceRefreshTimer||(this.sourceRefreshTimer=setTimeout(()=>{this.sourceRefreshTimer=null;const e=this.siteAdapter.getOutlineSourcesSignature();e!==this.outlineSourcesSignature&&(this.outlineSourcesSignature=e,this.refresh());},500));}),this.sourceObserver.observe(document.body,{childList:true,subtree:true}));}stopSourceObserver(){this.sourceObserver&&(this.sourceObserver.disconnect(),this.sourceObserver=null),this.sourceRefreshTimer&&(clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null);}triggerAutoUpdate(){const e=1e3*(this.settings.updateInterval||2);this.updateDebounceTimer||(this.updateDebounceTimer=setTimeout(()=>{this.executeAutoUpdate();},e));}executeAutoUpdate(){this.updateDebounceTimer&&(clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null);const e=this.siteAdapter.isGenerating();!this.wasGenerating||e||this.postGenerationScheduled||(this.postGenerationScheduled=true,setTimeout(()=>{this.postGenerationScheduled=false,this.isActive?(this.treeKey="",this.refresh()):this.pendingPostGenerationRefresh=true;},500)),this.wasGenerating=e;const t=this.treeKey;if(this.refresh(),this.treeKey!==t){this.lastTreeChangeTime=Date.now(),this.fallbackRefreshTimer&&clearTimeout(this.fallbackRefreshTimer);const e=this.treeKey;this.fallbackRefreshTimer=setTimeout(()=>{this.fallbackRefreshTimer=null,Date.now()-this.lastTreeChangeTime>=Av.FALLBACK_DELAY-100&&this.treeKey===e&&(this.treeKey="",this.refresh());},Av.FALLBACK_DELAY);}}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}notify(){this.listeners.forEach(e=>e());}normalizeSources(e){const t=e.filter(e=>e.available);return t.length>0?t:[{id:"conversation",kind:"conversation",label:"对话",available:true}]}updateSources(){const e=this.normalizeSources(this.siteAdapter.getOutlineSources()),t=e.map(e=>`${e.id}:${e.kind}:${e.label}:${e.count??""}`).join("|"),n=this.sources.map(e=>`${e.id}:${e.kind}:${e.label}:${e.count??""}`).join("|");return this.sources=e,this.sources.some(e=>e.id===this.activeSourceId)||(this.activeSourceId=this.sources[0]?.id??"conversation",this.treeKey=""),t!==n}getBookmarkSessionId(){const e=this.siteAdapter.getSessionId();return "conversation"===this.activeSourceId?e:`${e}::${this.activeSourceId}`}getTree(){return this.tree}getFlatItems(){return this.flatItems}getSources(){return this.sources}getActiveSourceId(){return this.activeSourceId}setActiveSource(e){if(e===this.activeSourceId)return;this.sources.find(t=>t.id===e&&t.available)&&(this.activeSourceId=e,this.tree=[],this.flatItems=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.treeKey="",this.preSearchState=null,this.preSearchExpandLevel=null,this.searchLevelManual=false,this.matchCount=0,this.refresh(),this.notify());}getSignature(e){return this.generateSignature(e)}getSearchQuery(){return this.searchQuery}getScrollContainer(){return this.siteAdapter.getOutlineScrollContainer(this.activeSourceId)}markScrollPositionsStale(){this.scrollPositionsStale=true;}setBookmarkMode(e){e&&!this.bookmarkMode?(this.preBookmarkModeState=this.saveTreeCollapsedState(this.tree),this.collapseAllExpandedState(this.tree),this.expandBookmarkPaths(this.tree)):!e&&this.bookmarkMode&&this.preBookmarkModeState&&(this.restoreTreeCollapsedState(this.tree,this.preBookmarkModeState),this.preBookmarkModeState=null),this.bookmarkMode=e,this.searchQuery&&this.performSearch(this.searchQuery),this.notify();}toggleBookmarkMode(){this.setBookmarkMode(!this.bookmarkMode);}getBookmarkMode(){return this.bookmarkMode}saveTreeCollapsedState(e){const t={},n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;t[o]=e.collapsed,e.children.forEach((e,t)=>n(e,`${o}/${t}`));};return e.forEach((e,t)=>n(e,`root/${t}`)),t}restoreTreeCollapsedState(e,t){const n=(e,r)=>{const o=`${r}/${e.level}-${e.text}`;o in t&&(e.collapsed=t[o]),e.children.forEach((e,t)=>n(e,`${o}/${t}`));};e.forEach((e,t)=>n(e,`root/${t}`));}collapseAllExpandedState(e){e.forEach(e=>{e.collapsed=true,e.children.length>0&&this.collapseAllExpandedState(e.children);});}expandBookmarkPaths(e){let t=false;return e.forEach(e=>{let n=false;e.children.length>0&&(n=this.expandBookmarkPaths(e.children)),n&&(e.collapsed=false),(e.isBookmarked||n)&&(t=true);}),t}extractUserQueryText(e){return this.siteAdapter.extractUserQueryText(e)}findElementByHeading(e,t){return this.siteAdapter.findElementByHeading(e,t)} /** * 根据 queryIndex 和文本查找用户提问元素 * 用于大纲跳转时元素失效后的重新查找 * @param queryIndex 用户提问的序号(从 1 开始) * @param text 用户提问文本(用于验证和回退搜索) */findUserQueryElement(e,t){return this.siteAdapter.findUserQueryElement(e,t)}async resolveOutlineTarget(e,t){return this.siteAdapter.resolveOutlineTarget(e,t,this.activeSourceId)}scrollToOutlineTarget(e){this.siteAdapter.scrollToOutlineSourceTarget(e,this.activeSourceId);}getState(){const e=this.settings.showUserQueries?0:1;let t;t=this.searchQuery&&!this.searchLevelManual?100:this.expandLevel??6;const n=this.settings.showUserQueries?0:1;return tt.removeBookmark(e)),this.ghostBookmarkIds.clear(),this.refresh(),e.length}generateSignature(e){if(e.id)return "conversation"===this.activeSourceId?e.id:`${this.activeSourceId}:${e.id}`;let t="";if(e.context)t=e.context;else try{e.element?.nextElementSibling&&(t=(e.element.nextElementSibling.textContent||"").trim().substring(0,50));}catch{}const n=`${e.text}::${t}`;return "conversation"===this.activeSourceId?n:`${this.activeSourceId}:${n}`}toggleBookmark(e){const t=this.getBookmarkSessionId(),n=this.siteAdapter.getSiteId(),r=this.siteAdapter.getCurrentCid()||"",o=this.generateSignature(e);let i=0;e.element instanceof HTMLElement?i=e.element.offsetTop:void 0!==e.scrollTop&&(i=e.scrollTop);const a=vv.getState(),s=a.getBookmarkId(t,o);s?(a.removeBookmark(s),e.isBookmarked=false,e.bookmarkId=void 0):(a.addBookmark(t,n,r,e,o,i),e.isBookmarked=true,e.bookmarkId=a.getBookmarkId(t,o)||void 0),this.notify();}refresh(e){if(this.settings.enabled&&!this.isRefreshing){this.isRefreshing=true;try{this._doRefresh(e);}finally{this.isRefreshing=false;}}}handleUrlChange(){this.tree=[],this.flatItems=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.treeKey="",this.levelCounts={},this.notify();for(const e of [80,250,600,1200])setTimeout(()=>this.refresh(),e);}_doRefresh(e){const t=this.updateSources(),n=Ai.getState().settings,r=n?.features?.outline?.showWordCount??false;let o=this.siteAdapter.extractOutlineForSource(this.activeSourceId,this.settings.maxLevel,this.settings.showUserQueries,r);const i=this.getBookmarkSessionId(),a=vv.getState().getBookmarksBySession(i);if(this.ghostBookmarkIds=new Set,a.length>0){const e=new Set(a.map(e=>e.id));o.forEach(t=>{const n=this.generateSignature(t),r=a.find(e=>e.signature===n&&e.title===t.text);r&&(t.isBookmarked=true,t.bookmarkId=r.id,e.delete(r.id));});const t={},n={};e.forEach(e=>{const n=a.find(t=>t.id===e);n&&(t[n.title]||(t[n.title]=[]),t[n.title].push(n.id));}),o.forEach(e=>{e.isBookmarked||(n[e.text]||(n[e.text]=[]),n[e.text].push(e));});const r=vv.getState();Object.keys(t).forEach(o=>{const i=t[o],a=n[o];if(i&&a&&1===i.length&&1===a.length){const t=i[0],n=a[0],o=this.generateSignature(n);r.updateBookmark(t,{signature:o}),n.isBookmarked=true,n.bookmarkId=t,e.delete(t);}}),this.ghostBookmarkIds=new Set(e);const i=[];if(e.forEach(e=>{const t=a.find(t=>t.id===e);if(t){if(0===t.level&&!this.settings.showUserQueries)return;i.push({level:t.level,text:t.title,element:null,isUserQuery:0===t.level,isBookmarked:true,isGhost:true,bookmarkId:t.id,scrollTop:t.scrollTop});}}),i.length>0){const e=e=>e.isGhost?e.scrollTop:e.element instanceof HTMLElement?e.element.offsetTop:0;o=[...o,...i].sort((t,n)=>e(t)-e(n));}}if(0===o.length)return void(this.tree.length>0?(this.tree=[],this.flatNodes=[],this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[],this.scrollPositionsStale=true,this.notify()):t&&this.notify());this.levelCounts={},o.forEach(e=>{this.levelCounts[e.level]=(this.levelCounts[e.level]||0)+1;});const s=o.filter(e=>!e.isUserQuery).map(e=>e.level);this.minLevel=s.length>0?Math.min(...s):1;const l=r?"wc:1":"wc:0",c=this.siteAdapter.getSessionId()||"no-session",d="undefined"!=typeof window?window.location.pathname:"",u=function(e){let t=5381;for(let n=0;n>>0;return t.toString(16).padStart(8,"0")}(`${this.siteAdapter.getSiteId()}:${c}:${d}:${this.activeSourceId}`+"|"+l+"|"+o.map(e=>`${e.text}:${e.isBookmarked}`).join("|")),h={};if(this.tree.length>0&&this.captureTreeState(this.tree,h),this.treeKey===u&&0!==this.tree.length&&void 0===e){let e=false;const n=this.siteAdapter.getSiteId();return n!==co&&n!==mo||(e=this.syncFlatNodeRuntimeData(o)),this.scrollPositionsStale=true,void((e||t)&&this.notify())}this.tree=this.buildTree(o,this.minLevel),this.treeKey=u,this.flatItems=o,this.flatNodes=this.flattenTree(this.tree),this.updateScrollPositions();const g=void 0!==e?e:this.expandLevel??6;this.expandLevel=g;const p=this.settings.showUserQueries?0:1,m=g0&&this.restoreTreeState(this.tree,h),this.searchQuery&&this.performSearch(this.searchQuery),this.bookmarkMode&&this.expandBookmarkPaths(this.tree);const f=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=this.expandLevel>=f,this.notify();}buildTree(e,t){const n=[],r=[];let o=0;return e.forEach((e,i)=>{const a=e.isUserQuery?0:e.level-t+1;let s;e.isUserQuery&&(o++,s=o);const l={...e,relativeLevel:a,index:i,queryIndex:s,children:[],collapsed:false},c=e;for(c.isBookmarked&&(l.isBookmarked=true),c.isGhost&&(l.isGhost=true),c.bookmarkId&&(l.bookmarkId=c.bookmarkId);r.length>0&&r[r.length-1].relativeLevel>=a;)r.pop();0===r.length?n.push(l):r[r.length-1].children.push(l),r.push(l);}),n}syncFlatNodeRuntimeData(e){let t=this.flatItems.length!==e.length;return this.flatItems=e,e.forEach((e,n)=>{const r=this.flatNodes[n];if(!r)return void(t=true);const o=e;(r.element!==e.element||r.id!==e.id||r.navigationId!==e.navigationId||r.context!==e.context||r.wordCount!==e.wordCount||r.isTruncated!==e.isTruncated||r.isUserQuery!==e.isUserQuery||r.isBookmarked!==o.isBookmarked||r.isGhost!==o.isGhost||r.bookmarkId!==o.bookmarkId||void 0!==o.scrollTop&&r.scrollTop!==o.scrollTop)&&(t=true),r.element=e.element,r.id=e.id,r.navigationId=e.navigationId,r.context=e.context,r.wordCount=e.wordCount,r.isTruncated=e.isTruncated,r.isUserQuery=e.isUserQuery,r.isBookmarked=o.isBookmarked,r.isGhost=o.isGhost,r.bookmarkId=o.bookmarkId,void 0!==o.scrollTop&&(r.scrollTop=o.scrollTop);}),t}flattenTree(e){const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children.length>0&&n(e.children);});};return n(e),t}updateScrollPositions(){this.scrollNodes=[],this.scrollPositions=[],this.scrollHeights=[];const e=this.getScrollContainer();if(!e||0===this.flatNodes.length)return;const t=e.getBoundingClientRect().top,n=e.scrollTop,r=[];let o=0;const i=this.shouldKeepPreviousVisibleItem(),a=e=>{const t=e.scrollTop;if(!i||"number"!=typeof t||Number.isNaN(t))return false;const n="number"!=typeof e.scrollHeight||Number.isNaN(e.scrollHeight)?0:e.scrollHeight;return r.push({node:e,top:t,height:n,order:o}),o+=1,true};if(this.flatNodes.forEach(e=>{if(e.isGhost)return;let i=e.element;if(i&&i.isConnected||("conversation"===this.activeSourceId&&(i=e.isUserQuery&&0===e.level&&void 0!==e.queryIndex?this.findUserQueryElement(e.queryIndex,e.text):this.findElementByHeading(e.level,e.text)),i&&(e.element=i)),!i||!i.isConnected)return void a(e);const s=i.getClientRects();if(0===s.length)return void a(e);const l=i.getBoundingClientRect(),c=l.top-t+n,d=l.height||s[0]?.height||0;e.scrollTop=c,e.scrollHeight=d,r.push({node:e,top:c,height:d,order:o}),o+=1;}),0===r.length)return void(this.scrollPositionsStale=false);let s=true;for(let l=1;le.top===t.top?e.order-t.order:e.top-t.top),r.forEach(e=>{this.scrollNodes.push(e.node),this.scrollPositions.push(e.top),this.scrollHeights.push(e.height);}),this.scrollPositionsStale=false;}captureTreeState(e,t){e.forEach(e=>{const n=e.id?`id:${e.id}`:`${e.level}_${e.text}`,r=e.children&&e.children.length>0;t[n]={collapsed:e.collapsed,forceExpanded:e.forceExpanded,hadChildren:r},r&&this.captureTreeState(e.children,t);});}restoreTreeState(e,t){e.forEach(e=>{const n=e.id?`id:${e.id}`:`${e.level}_${e.text}`,r=t[n];if(r){const t=e.children&&e.children.length>0;!r.hadChildren&&t||(e.collapsed=r.collapsed),void 0!==r.forceExpanded&&(e.forceExpanded=r.forceExpanded);}e.children.length>0&&this.restoreTreeState(e.children,t);});}initializeCollapsedState(e,t){e.forEach(e=>{if(e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.initializeCollapsedState(e.children,t);}else e.collapsed=false;});}clearForceExpandedState(e,t){e.forEach(e=>{if(e.forceExpanded=false,e.children&&e.children.length>0){const n=e.children.every(e=>e.level>t);e.collapsed=n,this.clearForceExpandedState(e.children,t);}else e.collapsed=false;});}toggleNode(e){e.collapsed=!e.collapsed,e.collapsed||(e.forceExpanded=true),this.notify();}collapseAll(){const e=this.settings.showUserQueries?0:this.minLevel||1;this.setLevel(e);}expandAll(){const e=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.setLevel(e);}setLevel(e){if(this.bookmarkMode)return void Li(se("bookmarkModeDisableLevel"));this.expandLevel=e,this.tree.length>0&&this.clearForceExpandedState(this.tree,e);const t=Math.max(...Object.keys(this.levelCounts).map(Number),1);this.isAllExpanded=e>=t,this.searchQuery&&(this.searchLevelManual=true),this.onExpandLevelChange&&this.onExpandLevelChange(e),this.notify();}setShowUserQueries(e){this.settings.showUserQueries=e,this.refresh(),this.notify(),this.onShowUserQueriesChange&&this.onShowUserQueriesChange(e);}toggleGroupMode(){this.setShowUserQueries(!this.settings.showUserQueries);}revealNode(e){const t=e=>{e.forEach(e=>{e.forceVisible=false,e.children&&e.children.length>0&&t(e.children);});};t(this.tree);const n=(e,t,r=[])=>{for(const o of e){if(o.index===t)return r.forEach(e=>{e.collapsed=false,e.forceExpanded=true,e.forceVisible=true;}),o.forceVisible=true,true;if(o.children&&o.children.length>0&&n(o.children,t,[...r,o]))return true}return false};n(this.tree,e)&&this.notify();}clearForceVisible(){const e=t=>{t.forEach(t=>{if(t.forceVisible&&(t.forceVisible=false,t.forceExpanded=false,t.children&&t.children.length>0)){const e=t.children.every(e=>e.relativeLevel>this.expandLevel);t.collapsed=e;}t.children&&t.children.length>0&&e(t.children);});};e(this.tree),this.notify();}setSearchQuery(e){if(e)!this.searchQuery&&this.tree.length>0&&(this.preSearchState={},this.captureTreeState(this.tree,this.preSearchState),this.preSearchExpandLevel=this.expandLevel),this.tree.length>0&&this.clearForceExpandedState(this.tree,0),this.searchQuery=e,this.searchLevelManual=false,this.performSearch(e);else if(this.searchQuery="",this.searchLevelManual=false,this.tree.length>0){null!==this.preSearchExpandLevel&&(this.expandLevel=this.preSearchExpandLevel,this.preSearchExpandLevel=null);const e=this.expandLevel??6;this.clearForceExpandedState(this.tree,e),this.preSearchState&&(this.restoreTreeState(this.tree,this.preSearchState),this.preSearchState=null);}this.notify();}performSearch(e){const t=e=>e.toLowerCase(),n=t(e);let r=0;const o=e=>{let i=false;return e.forEach(e=>{const a=t(e.text).includes(n);if(e.isMatch=a,a)if(this.bookmarkMode){const t=e=>!!e.isBookmarked||(e.children?.some(t)||false);(e.isBookmarked||t(e))&&r++;}else r++;if(e.children.length>0){let t=true;if(this.bookmarkMode){const n=e=>!!e.isBookmarked||(e.children?.some(n)||false);e.isBookmarked&&!e.children.some(n)&&(t=false);}e.hasMatchedDescendant=!!t&&o(e.children);}else e.hasMatchedDescendant=false;e.hasMatchedDescendant&&(e.collapsed=false),(a||e.hasMatchedDescendant)&&(i=true);}),i};o(this.tree),this.matchCount=r;}findVisibleItemIndex(e,t){if("current"!==this.settings.followMode)return null;this.scrollPositionsStale&&this.updateScrollPositions();const n=this.scrollNodes.length;if(0===n)return null;const r=e,o=e+t;let i=0,a=n-1,s=-1;for(;i<=a;){const e=i+a>>1;this.scrollPositions[e]<=r?(s=e,i=e+1):a=e-1;}if(s>=0){const e=this.scrollPositions[s],t=this.scrollHeights[s]||0;return er)?this.scrollNodes[s].index:s+1(Ev=()=>e({_hasHydrated:true}),{prompts:no(),_hasHydrated:false,addPrompt:t=>{const n={id:"custom_"+Date.now(),...t};return e(e=>({prompts:[...e.prompts,n]})),n},updatePrompt:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,...n}:e)})),deletePrompt:t=>e(e=>({prompts:e.prompts.filter(e=>e.id!==t)})),renameCategory:(t,n)=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),deleteCategory:(t,n="未分类")=>e(e=>({prompts:e.prompts.map(e=>e.category===t?{...e,category:n}:e)})),updateOrder:t=>e(e=>{const n=[];return t.forEach(t=>{const r=e.prompts.find(e=>e.id===t);r&&n.push(r);}),e.prompts.forEach(e=>{n.find(t=>t.id===e.id)||n.push(e);}),{prompts:n}}),setHasHydrated:t=>e({_hasHydrated:t}),togglePin:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,pinned:!e.pinned}:e)})),updateLastUsed:t=>e(e=>({prompts:e.prompts.map(e=>e.id===t?{...e,lastUsedAt:Date.now()}:e)})),setPrompts:t=>e({prompts:t})}),{name:"prompts",storage:Oo(()=>di),partialize:e=>({prompts:e.prompts}),onRehydrateStorage:()=>()=>{Ev?.();}})),Mv=()=>Tv.getState().prompts,_v=()=>Tv.getState(),Iv=()=>{const e=Mv(),t=new Set;return e.forEach(e=>{e.category&&t.add(e.category);}),Array.from(t)},Lv=(e="",t=Co)=>{let n=Mv();if(t!==Co&&t!==Ao&&(n=n.filter(e=>e.category===t)),e){const t=e.toLowerCase();n=n.filter(e=>e.title.toLowerCase().includes(t)||e.content.toLowerCase().includes(t));}return n},Nv=Object.freeze(Object.defineProperty({__proto__:null,filterPrompts:Lv,getCategories:Iv,getPromptsState:Mv,getPromptsStore:_v,usePromptsStore:Tv},Symbol.toStringTag,{value:"Module"})),Dv="ophel:aistudio-submit-shortcut-synced";class qv{adapter;constructor(e){this.adapter=e;}async init(){Tv.getState()._hasHydrated||await new Promise(e=>{const t=Tv.subscribe(n=>{n._hasHydrated&&(t(),e());});});}getPrompts(){return _v().prompts}addPrompt(e){return _v().addPrompt(e)}updatePrompt(e,t){_v().updatePrompt(e,t);}deletePrompt(e){_v().deletePrompt(e);}getCategories(){return Iv()}renameCategory(e,t){_v().renameCategory(e,t);}deleteCategory(e,t="未分类"){_v().deleteCategory(e,t);}updateOrder(e){_v().updateOrder(e);}filterPrompts(e="",t=Co){return Lv(e,t)}togglePin(e){_v().togglePin(e);}updateLastUsed(e){_v().updateLastUsed(e);}setPrompts(e){_v().setPrompts(e);}async insertPrompt(e){const t=[0,80,120,180,240];for(let n=0;n0&&await new Promise(e=>setTimeout(e,t[n])),this.adapter.findTextarea();if(this.adapter.insertPrompt(e))return true}return false}getEditorContent(e){return e?e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement?e.value||"":e.textContent||"":""}isElementDisabled(e){if(!e)return true;if(e instanceof HTMLButtonElement&&e.disabled)return true;if(e.hasAttribute("disabled"))return true;return "true"===e.getAttribute("aria-disabled")||"true"===e.getAttribute("data-disabled")}isElementVisible(e){if(!e||!e.isConnected)return false;if(e.closest(".gh-main-panel"))return false;const t=window.getComputedStyle(e);if("none"===t.display||"hidden"===t.visibility||0===parseFloat(t.opacity||"1"))return false;const n=e.getBoundingClientRect();return n.width>0&&n.height>0}collectSubmitButtons(e){const t=[],n=new Set;for(const r of e){const e=os.query(r,{all:true,shadow:true});if(e&&Array.isArray(e))for(const r of e)r instanceof HTMLElement&&!n.has(r)&&(n.add(r),t.push(r));}return t}getRectDistance(e,t){const n=Math.max(e.left-t.right,t.left-e.right,0),r=Math.max(e.top-t.bottom,t.top-e.bottom,0);return Math.sqrt(n*n+r*r)}findBestSubmitButton(e,t){const n=this.adapter.findSubmitButton(t);if(n&&this.isElementVisible(n))return n;const r=this.collectSubmitButtons(e).filter(e=>this.isElementVisible(e));if(0===r.length)return null;if(!t||!t.isConnected)return r[0];const o=t.closest("form");if(o){const e=r.filter(e=>e.closest("form")===o);if(e.length>0){return e.find(e=>!this.isElementDisabled(e))||e[0]}}const i=t.getBoundingClientRect();let a=r[0],s=Number.POSITIVE_INFINITY;for(const l of r){const e=this.getRectDistance(i,l.getBoundingClientRect());esetTimeout(e,50));}return null}syncAiStudioSubmitShortcut(e="enter"){if(this.adapter.getSiteId()!==po)return false;const t="ctrlEnter"===e?2:1;let n={};const r=localStorage.getItem("aiStudioUserPreference");if(r)try{const e=JSON.parse(r);e&&"object"==typeof e&&(n=e);}catch{}if(n.enterKeyBehavior===t)return false;try{localStorage.setItem("aiStudioUserPreference",JSON.stringify({...n,enterKeyBehavior:t}));}catch{return false}return window.dispatchEvent(new CustomEvent(Dv,{detail:{submitShortcut:2===t?"ctrlEnter":"enter"}})),true}async waitForSubmitConfirmation(e,t,n){const r=Date.now()+1500,o=e.trim().length>0;for(;Date.now()0){const e=this.findBestSubmitButton(t,r);if(!e&&n.button&&!n.button.isConnected)return true;if(e&&!n.wasDisabled&&this.isElementDisabled(e))return true}await new Promise(e=>setTimeout(e,60));}return false}resolveSubmitKeyConfig(e){return "ctrlEnter"===e?{key:"Ctrl+Enter"}:"enter"===e?{key:"Enter"}:this.adapter.getSubmitKeyConfig()}dispatchSubmitByKeyboard(e,t){e.focus();const n="Ctrl+Enter"===this.resolveSubmitKeyConfig(t).key,r=/Mac|iPhone|iPad|iPod/.test(navigator.platform),o={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,ctrlKey:n&&!r,metaKey:n&&r,shiftKey:false};return e.dispatchEvent(new KeyboardEvent("keydown",o)),e.dispatchEvent(new KeyboardEvent("keypress",o)),e.dispatchEvent(new KeyboardEvent("keyup",o)),true}shouldRetryWithKeyboard(e){if(this.adapter.isGenerating?.())return false;const t=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;const n=this.getEditorContent(t).replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim(),r=e.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();return !!n&&(!!r&&(n===r||n.includes(r)||r.includes(n)))}async submitPrompt(e){this.syncAiStudioSubmitShortcut(e??"enter");const t=this.adapter.getSubmitButtonSelectors(),n=this.adapter.getTextareaElement()||this.adapter.findTextarea(),r=this.getEditorContent(n),o=r.replace(/[\u200B\u200C\u200D\uFEFF]/g,"").trim();let i=false,a=null,s=null,l=true;if(t.length>0){s=this.findBestSubmitButton(t,n),l=this.isElementDisabled(s);let e=s;if(l){const r=null===s?2e3:500,o=await this.waitForEnabledSubmitButton(t,n,r);o&&(e=o,s=o,l=false);}e&&!this.isElementDisabled(e)&&(e.click(),a=e,i=true);}if(!i){if(!o)return false;const t=n||this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!t)return false;i=this.dispatchSubmitByKeyboard(t,e);}if(!i)return false;let c=await this.waitForSubmitConfirmation(r,t,{button:a||s,clicked:!!a,wasDisabled:l});if(c)return true;if(!a||!this.shouldRetryWithKeyboard(r))return false;const d=this.adapter.getTextareaElement()||this.adapter.findTextarea();if(!d)return false;return !!this.dispatchSubmitByKeyboard(d,e)&&(c=await this.waitForSubmitConfirmation(r,t,{button:this.findBestSubmitButton(t,d),clicked:false,wasDisabled:false}),c)}}const Rv=e=>({id:`q_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,content:e,createdAt:Date.now(),status:"pending",type:"prompt"}),Pv=Bo()((e,t)=>({items:[],isProcessing:false,isPaused:false,enqueue:t=>{const n=Rv(t);return e(e=>({items:[...e.items,n]})),n},enqueueMany:t=>{const n=t.map(e=>e.trim()).filter(Boolean).map(e=>Rv(e));return 0===n.length?[]:(e(e=>({items:[...e.items,...n]})),n)},dequeue:()=>{const{items:n}=t(),r=n.find(e=>"pending"===e.status);return r?(e(e=>({items:e.items.map(e=>e.id===r.id?{...e,status:"sending"}:e),isProcessing:true})),r):null},remove:t=>e(e=>({items:e.items.filter(e=>e.id!==t)})),updateContent:(t,n)=>e(e=>({items:e.items.map(e=>e.id===t?{...e,content:n}:e)})),updateStatus:(t,n)=>e(e=>{const r=e.items.map(e=>e.id===t?{...e,status:n}:e),o=r.some(e=>"pending"===e.status||"sending"===e.status);return {items:r,isProcessing:o}}),clear:()=>e({items:[],isProcessing:false}),pause:()=>e({isPaused:true}),resume:()=>e({isPaused:false})}));class zv{adapter;promptManager;intervalId=null;idleCount=0;IDLE_THRESHOLD=2;POLL_INTERVAL=1e3;constructor(e,t){this.adapter=e,this.promptManager=t;}start(){this.intervalId||(this.idleCount=0,this.intervalId=setInterval(()=>this.tick(),this.POLL_INTERVAL));}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.idleCount=0;}isRunning(){return null!==this.intervalId}async tick(){const e=Pv.getState();if(0===e.items.filter(e=>"pending"===e.status).length||e.isPaused)return void(this.idleCount=0);if(e.items.filter(e=>"sending"===e.status).length>0)return void(this.idleCount=0);this.adapter.isGenerating()?this.idleCount=0:(this.idleCount++,this.idleCount>=this.IDLE_THRESHOLD&&(this.idleCount=0,await this.dispatchNext()));}async dispatchNext(){const e=Pv.getState(),t=e.dequeue();if(t)try{if(!(await this.promptManager.insertPrompt(t.content)))return void e.updateStatus(t.id,"failed");const n=Ai.getState().settings.features?.prompts?.submitShortcut??"enter";if(!(await this.promptManager.submitPrompt(n)))return void e.updateStatus(t.id,"failed");e.updateStatus(t.id,"sent");}catch(n){console.error("[QueueDispatcher] 发送失败:",n),e.updateStatus(t.id,"failed");}}async sendImmediately(e,t){try{if(!(await this.promptManager.insertPrompt(e)))return !1;return await this.promptManager.submitPrompt(t)}catch(n){return console.error("[QueueDispatcher] 立即发送失败:",n),false}}async processNextNow(){const e=Pv.getState();if(e.isPaused)return false;if(this.adapter.isGenerating())return false;if(e.items.some(e=>"sending"===e.status))return false;return !!e.items.some(e=>"pending"===e.status)&&(this.idleCount=0,await this.dispatchNext(),true)}}const Bv=[{id:"google-gradient",name:"Google 渐变",description:"默认主题,蓝绿渐变 Header",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f9fafb","--gh-bg-tertiary":"#f3f4f6","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e5e7eb","--gh-border-active":"#4285f4","--gh-hover":"#f3f4f6","--gh-active-bg":"#e5e7eb","--gh-input-bg":"#ffffff","--gh-input-border":"#d1d5db","--gh-input-focus-border":"#4285f4","--gh-input-focus-shadow":"0 0 0 2px rgba(66, 133, 244, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(66, 133, 244, 0.3)","--gh-primary":"#4285f4","--gh-secondary":"#34a853","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-tag-active-bg":"#4285f4","--gh-checkbox-bg":"#4f46e5","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e5e7eb","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(66, 133, 244, 0.1) 0%, rgba(52, 211, 153, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#c7d2fe","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(16, 185, 129, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(52, 211, 153, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(66, 133, 244, 0.08)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #4285f4 0%, #34a853 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e5e7eb","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(59, 130, 246, 0.3)","--gh-slider-dot-bg":"#d1d5db","--gh-code-bg":"rgba(0, 0, 0, 0.05)"}},{id:"purple",name:"紫罗兰",description:"优雅紫色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#faf5ff","--gh-bg-tertiary":"#f3e8ff","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#8b5cf6","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#d8b4fe","--gh-input-focus-border":"#8b5cf6","--gh-input-focus-shadow":"0 0 0 2px rgba(139, 92, 246, 0.1)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(139, 92, 246, 0.3)","--gh-primary":"#8b5cf6","--gh-secondary":"#a855f7","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-tag-active-bg":"#8b5cf6","--gh-checkbox-bg":"#8b5cf6","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.1) 0%, rgba(168, 85, 247, 0.1) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(139, 92, 246, 0.25)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(139, 92, 246, 0.08)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(139, 92, 246, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(139, 92, 246, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#f3e8ff","--gh-highlight-pulse":"rgba(139, 92, 246, 0.3)","--gh-slider-dot-bg":"#d8b4fe","--gh-code-bg":"rgba(139, 92, 246, 0.08)"}},{id:"ocean",name:"海洋蓝",description:"清新海洋主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f0f9ff","--gh-bg-tertiary":"#e0f2fe","--gh-text":"#1f2937","--gh-text-secondary":"#6b7280","--gh-text-tertiary":"#9ca3af","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#bae6fd","--gh-border-active":"#0ea5e9","--gh-hover":"#e0f2fe","--gh-active-bg":"#bae6fd","--gh-input-bg":"#ffffff","--gh-input-border":"#7dd3fc","--gh-input-focus-border":"#0ea5e9","--gh-input-focus-shadow":"0 0 0 2px rgba(14, 165, 233, 0.1)","--gh-shadow":"0 10px 40px rgba(14, 165, 233, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.3)","--gh-shadow-brand":"0 4px 12px rgba(14, 165, 233, 0.3)","--gh-primary":"#0ea5e9","--gh-secondary":"#06b6d4","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-tag-active-bg":"#0ea5e9","--gh-checkbox-bg":"#0ea5e9","--gh-badge-text":"#4b5563","--gh-badge-bg":"#ffffff","--gh-badge-border":"#bae6fd","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(14, 165, 233, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%)","--gh-folder-bg-default":"#e0f2fe","--gh-folder-bg-expanded":"#bae6fd","--gh-folder-bg-0":"#fef9e7","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fefce8","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(14, 165, 233, 0.25)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.5)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.1)","--gh-outline-sync-border":"#fb923c","--gh-user-query-bg":"rgba(14, 165, 233, 0.08)","--gh-user-query-hover-bg":"rgba(14, 165, 233, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.2)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.3)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#bae6fd","--gh-overlay-bg":"rgba(0, 0, 0, 0.5)","--gh-btn-shadow":"0 2px 6px rgba(14, 165, 233, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(14, 165, 233, 0.2)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"#e0f2fe","--gh-highlight-pulse":"rgba(14, 165, 233, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(14, 165, 233, 0.08)"}},{id:"sakura",name:"樱花物语",description:"柔美粉色主题",variables:{"--gh-bg":"#fff5f7","--gh-bg-secondary":"#fff0f3","--gh-bg-tertiary":"#ffe4e9","--gh-text":"#4a0418","--gh-text-secondary":"#9d4f64","--gh-text-tertiary":"#d48aa0","--gh-text-on-primary":"#881337","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fecdd3","--gh-border-active":"#fb7185","--gh-hover":"#ffe4e9","--gh-active-bg":"#fecdd3","--gh-input-bg":"#ffffff","--gh-input-border":"#fda4af","--gh-input-focus-border":"#fb7185","--gh-input-focus-shadow":"0 0 0 2px rgba(251, 113, 133, 0.2)","--gh-shadow":"0 10px 40px rgba(251, 113, 133, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(255, 179, 193, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(251, 113, 133, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-primary":"#fb7185","--gh-secondary":"#f43f5e","--gh-danger":"#e11d48","--gh-header-bg":"linear-gradient(135deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%)","--gh-tag-active-bg":"#fb7185","--gh-checkbox-bg":"#fb7185","--gh-badge-text":"#881337","--gh-badge-bg":"#fff1f2","--gh-badge-border":"#fecdd3","--gh-badge-shadow":"#fff0f3","--gh-selected-gradient":"linear-gradient(135deg, rgba(251, 113, 133, 0.15) 0%, rgba(244, 63, 94, 0.1) 100%)","--gh-folder-bg-default":"#fff1f2","--gh-folder-bg-expanded":"#ffe4e6","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#f5f3ff","--gh-outline-locate-bg":"rgba(251, 113, 133, 0.2)","--gh-outline-locate-border":"#10b981","--gh-outline-locate-shadow":"rgba(16, 185, 129, 0.5)","--gh-outline-sync-bg":"rgba(16, 185, 129, 0.1)","--gh-outline-sync-border":"#34d399","--gh-user-query-bg":"rgba(251, 113, 133, 0.08)","--gh-user-query-hover-bg":"rgba(251, 113, 133, 0.15)","--gh-bg-danger":"#fff1f2","--gh-text-danger":"#e11d48","--gh-bg-danger-hover":"#ffe4e6","--gh-brand-gradient":"linear-gradient(135deg, #fb7185 0%, #f43f5e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#881337","--gh-card-bg":"#ffffff","--gh-card-border":"#ffe4e6","--gh-overlay-bg":"rgba(255, 241, 242, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(251, 113, 133, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(251, 113, 133, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ffe4e6","--gh-highlight-pulse":"rgba(251, 113, 133, 0.3)","--gh-slider-dot-bg":"#fda4af","--gh-code-bg":"rgba(251, 113, 133, 0.08)"}},{id:"mint",name:"清新薄荷",description:"活力青绿主题",variables:{"--gh-bg":"#f0fdf9","--gh-bg-secondary":"#e6fffa","--gh-bg-tertiary":"#ccfbf1","--gh-text":"#134e4a","--gh-text-secondary":"#2d7a74","--gh-text-tertiary":"#5eead4","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#99f6e4","--gh-border-active":"#2dd4bf","--gh-hover":"#ccfbf1","--gh-active-bg":"#99f6e4","--gh-input-bg":"#ffffff","--gh-input-border":"#5eead4","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.2)","--gh-shadow":"0 10px 40px rgba(45, 212, 191, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(45, 212, 191, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(45, 212, 191, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#14b8a6","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #14b8a6 0%, #34d399 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#115e59","--gh-badge-bg":"#ccfbf1","--gh-badge-border":"#99f6e4","--gh-badge-shadow":"#e6fffa","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.15) 0%, rgba(20, 184, 166, 0.1) 100%)","--gh-folder-bg-default":"#ccfbf1","--gh-folder-bg-expanded":"#99f6e4","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#f43f5e","--gh-outline-locate-shadow":"rgba(244, 63, 94, 0.5)","--gh-outline-sync-bg":"rgba(244, 63, 94, 0.1)","--gh-outline-sync-border":"#fb7185","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #14b8a6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#115e59","--gh-card-bg":"#ffffff","--gh-card-border":"#99f6e4","--gh-overlay-bg":"rgba(240, 253, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(45, 212, 191, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#ccfbf1","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#5eead4","--gh-code-bg":"rgba(45, 212, 191, 0.1)"}},{id:"nordic",name:"北欧霜雪",description:"极简冷淡主题",variables:{"--gh-bg":"#f8fafc","--gh-bg-secondary":"#f1f5f9","--gh-bg-tertiary":"#e2e8f0","--gh-text":"#0f172a","--gh-text-secondary":"#475569","--gh-text-tertiary":"#94a3b8","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#cbd5e1","--gh-border-active":"#64748b","--gh-hover":"#e2e8f0","--gh-active-bg":"#cbd5e1","--gh-input-bg":"#ffffff","--gh-input-border":"#cbd5e1","--gh-input-focus-border":"#64748b","--gh-input-focus-shadow":"0 0 0 2px rgba(100, 116, 139, 0.15)","--gh-shadow":"0 10px 40px rgba(15, 23, 42, 0.08)","--gh-shadow-sm":"0 1px 3px rgba(15, 23, 42, 0.05)","--gh-shadow-lg":"0 20px 60px rgba(15, 23, 42, 0.12)","--gh-shadow-brand":"0 4px 12px rgba(100, 116, 139, 0.2)","--gh-primary":"#64748b","--gh-secondary":"#475569","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-tag-active-bg":"#64748b","--gh-checkbox-bg":"#64748b","--gh-badge-text":"#334155","--gh-badge-bg":"#f1f5f9","--gh-badge-border":"#cbd5e1","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(100, 116, 139, 0.1) 0%, rgba(71, 85, 105, 0.08) 100%)","--gh-folder-bg-default":"#f1f5f9","--gh-folder-bg-expanded":"#e2e8f0","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(100, 116, 139, 0.15)","--gh-outline-locate-border":"#ef4444","--gh-outline-locate-shadow":"rgba(239, 68, 68, 0.5)","--gh-outline-sync-bg":"rgba(239, 68, 68, 0.1)","--gh-outline-sync-border":"#f87171","--gh-user-query-bg":"rgba(100, 116, 139, 0.06)","--gh-user-query-hover-bg":"rgba(100, 116, 139, 0.12)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #64748b 0%, #475569 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#cbd5e1","--gh-overlay-bg":"rgba(241, 245, 249, 0.6)","--gh-btn-shadow":"0 2px 6px rgba(100, 116, 139, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(100, 116, 139, 0.25)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e2e8f0","--gh-highlight-pulse":"rgba(100, 116, 139, 0.25)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(100, 116, 139, 0.06)"}},{id:"lemon-soda",name:"柠檬苏打",description:"明亮活力主题",variables:{"--gh-bg":"#fefce8","--gh-bg-secondary":"#fef9c3","--gh-bg-tertiary":"#fde047","--gh-text":"#854d0e","--gh-text-secondary":"#a16207","--gh-text-tertiary":"#ca8a04","--gh-text-on-primary":"#854d0e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde047","--gh-border-active":"#eab308","--gh-hover":"#fef9c3","--gh-active-bg":"#fde047","--gh-input-bg":"#ffffff","--gh-input-border":"#fde047","--gh-input-focus-border":"#eab308","--gh-input-focus-shadow":"0 0 0 2px rgba(234, 179, 8, 0.2)","--gh-shadow":"0 10px 40px rgba(234, 179, 8, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(234, 179, 8, 0.2)","--gh-shadow-lg":"0 20px 60px rgba(234, 179, 8, 0.25)","--gh-shadow-brand":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-primary":"#eab308","--gh-secondary":"#ca8a04","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-tag-active-bg":"#eab308","--gh-checkbox-bg":"#eab308","--gh-badge-text":"#854d0e","--gh-badge-bg":"#fef9c3","--gh-badge-border":"#fde047","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(234, 179, 8, 0.15) 0%, rgba(132, 204, 22, 0.1) 100%)","--gh-folder-bg-default":"#fef9c3","--gh-folder-bg-expanded":"#fde047","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(234, 179, 8, 0.2)","--gh-outline-locate-border":"#3b82f6","--gh-outline-locate-shadow":"rgba(59, 130, 246, 0.5)","--gh-outline-sync-bg":"rgba(59, 130, 246, 0.1)","--gh-outline-sync-border":"#60a5fa","--gh-user-query-bg":"rgba(234, 179, 8, 0.08)","--gh-user-query-hover-bg":"rgba(234, 179, 8, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #eab308 0%, #84cc16 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#854d0e","--gh-card-bg":"#ffffff","--gh-card-border":"#fde047","--gh-overlay-bg":"rgba(254, 252, 232, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(234, 179, 8, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(234, 179, 8, 0.3)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.8)","--gh-emoji-selected-bg":"#fde047","--gh-highlight-pulse":"rgba(234, 179, 8, 0.3)","--gh-slider-dot-bg":"#d4d4d8","--gh-code-bg":"rgba(234, 179, 8, 0.1)"}},{id:"ancient-scroll",name:"羊皮卷",description:"复古纸张主题",variables:{"--gh-bg":"#fffbeb","--gh-bg-secondary":"#fef3c7","--gh-bg-tertiary":"#fde68a","--gh-text":"#451a03","--gh-text-secondary":"#92400e","--gh-text-tertiary":"#b45309","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#fde68a","--gh-border-active":"#d97706","--gh-hover":"#fef3c7","--gh-active-bg":"#fde68a","--gh-input-bg":"#ffffff","--gh-input-border":"#fcd34d","--gh-input-focus-border":"#d97706","--gh-input-focus-shadow":"0 0 0 2px rgba(217, 119, 6, 0.2)","--gh-shadow":"0 10px 40px rgba(146, 64, 14, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(146, 64, 14, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(146, 64, 14, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(217, 119, 6, 0.25)","--gh-primary":"#d97706","--gh-secondary":"#b45309","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-tag-active-bg":"#d97706","--gh-checkbox-bg":"#d97706","--gh-badge-text":"#78350f","--gh-badge-bg":"#fef3c7","--gh-badge-border":"#fcd34d","--gh-badge-shadow":"#fffbeb","--gh-selected-gradient":"linear-gradient(135deg, rgba(217, 119, 6, 0.15) 0%, rgba(146, 64, 14, 0.1) 100%)","--gh-folder-bg-default":"#fef3c7","--gh-folder-bg-expanded":"#fde68a","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(217, 119, 6, 0.2)","--gh-outline-locate-border":"#0d9488","--gh-outline-locate-shadow":"rgba(13, 148, 136, 0.5)","--gh-outline-sync-bg":"rgba(13, 148, 136, 0.1)","--gh-outline-sync-border":"#14b8a6","--gh-user-query-bg":"rgba(217, 119, 6, 0.08)","--gh-user-query-hover-bg":"rgba(217, 119, 6, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #d97706 0%, #92400e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#78350f","--gh-card-bg":"#fffbeb","--gh-card-border":"#fde68a","--gh-overlay-bg":"rgba(255, 251, 235, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(217, 119, 6, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(217, 119, 6, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#fde68a","--gh-highlight-pulse":"rgba(217, 119, 6, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(217, 119, 6, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 400 400' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.12'/%3E%3C/svg%3E\")"}},{id:"mono-pro",name:"极致黑白",description:"纯粹单色主题",variables:{"--gh-bg":"#ffffff","--gh-bg-secondary":"#f4f4f5","--gh-bg-tertiary":"#e4e4e7","--gh-text":"#09090b","--gh-text-secondary":"#52525b","--gh-text-tertiary":"#a1a1aa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e4e4e7","--gh-border-active":"#18181b","--gh-hover":"#f4f4f5","--gh-active-bg":"#e4e4e7","--gh-input-bg":"#ffffff","--gh-input-border":"#d4d4d8","--gh-input-focus-border":"#18181b","--gh-input-focus-shadow":"0 0 0 2px rgba(24, 24, 27, 0.1)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.12)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(0, 0, 0, 0.2)","--gh-primary":"#18181b","--gh-secondary":"#3f3f46","--gh-danger":"#71717a","--gh-header-bg":"#000000","--gh-tag-active-bg":"#18181b","--gh-checkbox-bg":"#18181b","--gh-badge-text":"#18181b","--gh-badge-bg":"#f4f4f5","--gh-badge-border":"#e4e4e7","--gh-badge-shadow":"#ffffff","--gh-selected-gradient":"linear-gradient(135deg, rgba(24, 24, 27, 0.08) 0%, rgba(63, 63, 70, 0.05) 100%)","--gh-folder-bg-default":"#f4f4f5","--gh-folder-bg-expanded":"#e4e4e7","--gh-folder-bg-0":"#f4f4f5","--gh-folder-bg-1":"#f4f4f5","--gh-folder-bg-2":"#f4f4f5","--gh-folder-bg-3":"#f4f4f5","--gh-folder-bg-4":"#f4f4f5","--gh-folder-bg-5":"#f4f4f5","--gh-folder-bg-6":"#f4f4f5","--gh-folder-bg-7":"#f4f4f5","--gh-outline-locate-bg":"rgba(24, 24, 27, 0.08)","--gh-outline-locate-border":"#dc2626","--gh-outline-locate-shadow":"rgba(220, 38, 38, 0.5)","--gh-outline-sync-bg":"rgba(220, 38, 38, 0.1)","--gh-outline-sync-border":"#ef4444","--gh-user-query-bg":"rgba(24, 24, 27, 0.04)","--gh-user-query-hover-bg":"rgba(24, 24, 27, 0.08)","--gh-bg-danger":"#f4f4f5","--gh-text-danger":"#18181b","--gh-bg-danger-hover":"#e4e4e7","--gh-brand-gradient":"linear-gradient(135deg, #000000 0%, #333333 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"#e4e4e7","--gh-overlay-bg":"rgba(255, 255, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.25)","--gh-search-highlight-bg":"rgba(0, 0, 0, 0.1)","--gh-emoji-selected-bg":"#e4e4e7","--gh-highlight-pulse":"rgba(24, 24, 27, 0.2)","--gh-slider-dot-bg":"#a1a1aa","--gh-code-bg":"rgba(24, 24, 27, 0.05)"}},{id:"porcelain",name:"青花瓷",description:"东方古典主题",variables:{"--gh-bg":"#f9fbff","--gh-bg-secondary":"#eff6ff","--gh-bg-tertiary":"#e0e7ff","--gh-text":"#1e4e79","--gh-text-secondary":"#4e7ca1","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"rgba(78, 124, 161, 0.2)","--gh-border-active":"#1e4e79","--gh-hover":"#eff6ff","--gh-active-bg":"#dbeafe","--gh-input-bg":"#ffffff","--gh-input-border":"#bfdbfe","--gh-input-focus-border":"#1e4e79","--gh-input-focus-shadow":"0 0 0 2px rgba(30, 78, 121, 0.1)","--gh-shadow":"0 10px 40px -10px rgba(30, 78, 121, 0.15), 0 4px 12px -4px rgba(30, 78, 121, 0.1)","--gh-shadow-sm":"0 2px 6px rgba(30, 78, 121, 0.08)","--gh-shadow-lg":"0 20px 60px rgba(30, 78, 121, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-primary":"#1e4e79","--gh-secondary":"#4e7ca1","--gh-danger":"#dc2626","--gh-header-bg":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-tag-active-bg":"#1e4e79","--gh-checkbox-bg":"#1e4e79","--gh-badge-text":"#1e4e79","--gh-badge-bg":"#eff6ff","--gh-badge-border":"rgba(78, 124, 161, 0.3)","--gh-badge-shadow":"#f9fbff","--gh-selected-gradient":"linear-gradient(135deg, rgba(30, 78, 121, 0.1) 0%, rgba(78, 124, 161, 0.05) 100%)","--gh-folder-bg-default":"#eff6ff","--gh-folder-bg-expanded":"#dbeafe","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(30, 78, 121, 0.15)","--gh-outline-locate-border":"#b91c1c","--gh-outline-locate-shadow":"rgba(185, 28, 28, 0.5)","--gh-outline-sync-bg":"rgba(185, 28, 28, 0.1)","--gh-outline-sync-border":"#dc2626","--gh-user-query-bg":"rgba(30, 78, 121, 0.05)","--gh-user-query-hover-bg":"rgba(30, 78, 121, 0.1)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#dc2626","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #1e4e79 0%, #2c3e50 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.15)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.25)","--gh-glass-text":"#ffffff","--gh-card-bg":"#ffffff","--gh-card-border":"rgba(78, 124, 161, 0.15)","--gh-overlay-bg":"rgba(249, 251, 255, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(30, 78, 121, 0.15)","--gh-btn-shadow-hover":"0 4px 12px rgba(30, 78, 121, 0.25)","--gh-search-highlight-bg":"rgba(78, 124, 161, 0.2)","--gh-emoji-selected-bg":"#dbeafe","--gh-highlight-pulse":"rgba(30, 78, 121, 0.2)","--gh-slider-dot-bg":"#94a3b8","--gh-code-bg":"rgba(30, 78, 121, 0.06)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.5' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.1'/%3E%3C/svg%3E\")"}},{id:"shortbread",name:"奶油脆饼",description:"莫兰迪治愈主题",variables:{"--gh-bg":"#f5f5f4","--gh-bg-secondary":"#e7e5e4","--gh-bg-tertiary":"#d6d3d1","--gh-text":"#44403c","--gh-text-secondary":"#78716c","--gh-text-tertiary":"#a8a29e","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d6d3d1","--gh-border-active":"#a8a29e","--gh-hover":"#e7e5e4","--gh-active-bg":"#d6d3d1","--gh-input-bg":"#ffffff","--gh-input-border":"#d6d3d1","--gh-input-focus-border":"#78716c","--gh-input-focus-shadow":"0 0 0 2px rgba(120, 113, 108, 0.2)","--gh-shadow":"0 10px 40px rgba(120, 113, 108, 0.1)","--gh-shadow-sm":"0 1px 3px rgba(120, 113, 108, 0.1)","--gh-shadow-lg":"0 20px 60px rgba(120, 113, 108, 0.15)","--gh-shadow-brand":"0 4px 12px rgba(120, 113, 108, 0.2)","--gh-primary":"#78716c","--gh-secondary":"#57534e","--gh-danger":"#ef4444","--gh-header-bg":"#78716c","--gh-tag-active-bg":"#78716c","--gh-checkbox-bg":"#78716c","--gh-badge-text":"#44403c","--gh-badge-bg":"#e7e5e4","--gh-badge-border":"#d6d3d1","--gh-badge-shadow":"#f5f5f4","--gh-selected-gradient":"linear-gradient(135deg, rgba(120, 113, 108, 0.15) 0%, rgba(87, 83, 78, 0.1) 100%)","--gh-folder-bg-default":"#e7e5e4","--gh-folder-bg-expanded":"#d6d3d1","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(120, 113, 108, 0.2)","--gh-outline-locate-border":"#2563eb","--gh-outline-locate-shadow":"rgba(37, 99, 235, 0.5)","--gh-outline-sync-bg":"rgba(37, 99, 235, 0.1)","--gh-outline-sync-border":"#3b82f6","--gh-user-query-bg":"rgba(120, 113, 108, 0.08)","--gh-user-query-hover-bg":"rgba(120, 113, 108, 0.15)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #78716c 0%, #57534e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.5)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.7)","--gh-glass-text":"#44403c","--gh-card-bg":"#ffffff","--gh-card-border":"#d6d3d1","--gh-overlay-bg":"rgba(245, 245, 244, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(120, 113, 108, 0.2)","--gh-btn-shadow-hover":"0 4px 12px rgba(120, 113, 108, 0.3)","--gh-search-highlight-bg":"rgba(120, 113, 108, 0.3)","--gh-emoji-selected-bg":"#d6d3d1","--gh-highlight-pulse":"rgba(120, 113, 108, 0.3)","--gh-slider-dot-bg":"#d6d3d1","--gh-code-bg":"rgba(120, 113, 108, 0.08)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"unicorn-dream",name:"独角兽",description:"梦幻童话主题",variables:{"--gh-bg":"#faf5ff","--gh-bg-secondary":"#f3e8ff","--gh-bg-tertiary":"#e9d5ff","--gh-text":"#5b21b6","--gh-text-secondary":"#7c3aed","--gh-text-tertiary":"#8b5cf6","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#e9d5ff","--gh-border-active":"#d8b4fe","--gh-hover":"#f3e8ff","--gh-active-bg":"#e9d5ff","--gh-input-bg":"#ffffff","--gh-input-border":"#e9d5ff","--gh-input-focus-border":"#22d3ee","--gh-input-focus-shadow":"0 0 0 2px rgba(34, 211, 238, 0.3)","--gh-shadow":"0 10px 40px rgba(139, 92, 246, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(139, 92, 246, 0.15)","--gh-shadow-lg":"0 20px 60px rgba(139, 92, 246, 0.2)","--gh-shadow-brand":"0 4px 12px rgba(244, 114, 182, 0.3)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #f472b6 0%, #22d3ee 50%, #a78bfa 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#7c3aed","--gh-badge-bg":"#f3e8ff","--gh-badge-border":"#e9d5ff","--gh-badge-shadow":"#faf5ff","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"#f3e8ff","--gh-folder-bg-expanded":"#e9d5ff","--gh-folder-bg-0":"#fefce8","--gh-folder-bg-1":"#fdf2f8","--gh-folder-bg-2":"#eff6ff","--gh-folder-bg-3":"#ecfdf5","--gh-folder-bg-4":"#faf5ff","--gh-folder-bg-5":"#fff7ed","--gh-folder-bg-6":"#ecfeff","--gh-folder-bg-7":"#fdf4ff","--gh-outline-locate-bg":"rgba(167, 139, 250, 0.2)","--gh-outline-locate-border":"#a78bfa","--gh-outline-locate-shadow":"rgba(167, 139, 250, 0.5)","--gh-outline-sync-bg":"rgba(167, 139, 250, 0.15)","--gh-outline-sync-border":"#a78bfa","--gh-user-query-bg":"rgba(167, 139, 250, 0.1)","--gh-user-query-hover-bg":"rgba(167, 139, 250, 0.2)","--gh-bg-danger":"#fef2f2","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"#fee2e2","--gh-brand-gradient":"linear-gradient(135deg, #f472b6 0%, #22d3ee 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.4)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.6)","--gh-glass-text":"#5b21b6","--gh-card-bg":"#ffffff","--gh-card-border":"#e9d5ff","--gh-overlay-bg":"rgba(250, 245, 255, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(167, 139, 250, 0.25)","--gh-btn-shadow-hover":"0 4px 12px rgba(167, 139, 250, 0.35)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.6)","--gh-emoji-selected-bg":"#e9d5ff","--gh-highlight-pulse":"rgba(244, 114, 182, 0.3)","--gh-slider-dot-bg":"#e2e8f0","--gh-code-bg":"rgba(167, 139, 250, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.01' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.4'/%3E%3C/svg%3E\")","--gh-bg-animation":"gh-mist-drift 20s linear infinite alternate"}}],Ov=[{id:"classic-dark",name:"经典深黑",description:"默认深色主题",variables:{"--gh-bg":"#1e1e1e","--gh-bg-secondary":"#0b0b0b","--gh-bg-tertiary":"#262626","--gh-text":"#e3e3e3","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#6b7280","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#333333","--gh-border-active":"#818cf8","--gh-hover":"#262626","--gh-active-bg":"#333333","--gh-input-bg":"#262626","--gh-input-border":"#404040","--gh-input-focus-border":"#818cf8","--gh-input-focus-shadow":"0 0 0 2px rgba(129, 140, 248, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(129, 140, 248, 0.3)","--gh-primary":"#818cf8","--gh-secondary":"#6366f1","--gh-danger":"#fca5a5","--gh-header-bg":"#1e1e1e","--gh-tag-active-bg":"rgba(129, 140, 248, 0.6)","--gh-checkbox-bg":"#818cf8","--gh-badge-text":"#e5e7eb","--gh-badge-bg":"#374151","--gh-badge-border":"#4b5563","--gh-badge-shadow":"#1f2937","--gh-selected-gradient":"linear-gradient(135deg, rgba(129, 140, 248, 0.25) 0%, rgba(99, 102, 241, 0.15) 100%)","--gh-folder-bg-default":"rgba(66, 133, 244, 0.15)","--gh-folder-bg-expanded":"rgba(66, 133, 244, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(66, 133, 244, 0.15)","--gh-user-query-hover-bg":"rgba(66, 133, 244, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1a73e8 0%, #1e8e3e 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e3e3e3","--gh-card-bg":"#0b0b0b","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(129, 140, 248, 0.3)","--gh-highlight-pulse":"rgba(129, 140, 248, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(255, 255, 255, 0.08)"}},{id:"midnight-blue",name:"午夜蓝",description:"深邃蓝色主题",variables:{"--gh-bg":"#0f172a","--gh-bg-secondary":"#020617","--gh-bg-tertiary":"#1e293b","--gh-text":"#e2e8f0","--gh-text-secondary":"#94a3b8","--gh-text-tertiary":"#64748b","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#334155","--gh-border-active":"#60a5fa","--gh-hover":"#1e293b","--gh-active-bg":"#334155","--gh-input-bg":"#1e293b","--gh-input-border":"#475569","--gh-input-focus-border":"#60a5fa","--gh-input-focus-shadow":"0 0 0 2px rgba(96, 165, 250, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(96, 165, 250, 0.3)","--gh-primary":"#60a5fa","--gh-secondary":"#3b82f6","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-tag-active-bg":"rgba(96, 165, 250, 0.6)","--gh-checkbox-bg":"#60a5fa","--gh-badge-text":"#e2e8f0","--gh-badge-bg":"#334155","--gh-badge-border":"#475569","--gh-badge-shadow":"#1e293b","--gh-selected-gradient":"linear-gradient(135deg, rgba(96, 165, 250, 0.25) 0%, rgba(59, 130, 246, 0.15) 100%)","--gh-folder-bg-default":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-expanded":"rgba(59, 130, 246, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(96, 165, 250, 0.3)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(96, 165, 250, 0.15)","--gh-user-query-hover-bg":"rgba(96, 165, 250, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #1e40af 0%, #3b82f6 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#e2e8f0","--gh-card-bg":"#020617","--gh-card-border":"#334155","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(96, 165, 250, 0.3)","--gh-highlight-pulse":"rgba(96, 165, 250, 0.4)","--gh-slider-dot-bg":"#475569","--gh-code-bg":"rgba(96, 165, 250, 0.12)"}},{id:"forest",name:"暗夜森林",description:"深绿色主题",variables:{"--gh-bg":"#0f1a14","--gh-bg-secondary":"#050a07","--gh-bg-tertiary":"#14261c","--gh-text":"#d1fae5","--gh-text-secondary":"#86efac","--gh-text-tertiary":"#6ee7b7","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1f3d2b","--gh-border-active":"#34d399","--gh-hover":"#14261c","--gh-active-bg":"#1f3d2b","--gh-input-bg":"#14261c","--gh-input-border":"#2a5a3d","--gh-input-focus-border":"#34d399","--gh-input-focus-shadow":"0 0 0 2px rgba(52, 211, 153, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(52, 211, 153, 0.3)","--gh-primary":"#34d399","--gh-secondary":"#10b981","--gh-danger":"#fca5a5","--gh-header-bg":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-tag-active-bg":"rgba(52, 211, 153, 0.6)","--gh-checkbox-bg":"#34d399","--gh-badge-text":"#d1fae5","--gh-badge-bg":"#1f3d2b","--gh-badge-border":"#2a5a3d","--gh-badge-shadow":"#14261c","--gh-selected-gradient":"linear-gradient(135deg, rgba(52, 211, 153, 0.25) 0%, rgba(16, 185, 129, 0.15) 100%)","--gh-folder-bg-default":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-expanded":"rgba(16, 185, 129, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(52, 211, 153, 0.3)","--gh-outline-locate-border":"#e879f9","--gh-outline-locate-shadow":"rgba(232, 121, 249, 0.6)","--gh-outline-sync-bg":"rgba(232, 121, 249, 0.15)","--gh-outline-sync-border":"#d946ef","--gh-user-query-bg":"rgba(52, 211, 153, 0.15)","--gh-user-query-hover-bg":"rgba(52, 211, 153, 0.25)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #065f46 0%, #10b981 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.08)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.12)","--gh-glass-text":"#d1fae5","--gh-card-bg":"#050a07","--gh-card-border":"#1f3d2b","--gh-overlay-bg":"rgba(0, 0, 0, 0.7)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(52, 211, 153, 0.3)","--gh-highlight-pulse":"rgba(52, 211, 153, 0.4)","--gh-slider-dot-bg":"#2a5a3d","--gh-code-bg":"rgba(52, 211, 153, 0.12)"}},{id:"cyberpunk",name:"赛博霓虹",description:"高对比科技主题",variables:{"--gh-bg":"#050505","--gh-bg-secondary":"#121212","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#e0e0e0","--gh-text-secondary":"#a0a0a0","--gh-text-tertiary":"#707070","--gh-text-on-primary":"#ffffff","--gh-footer-text":"#f472b6","--gh-border":"#333333","--gh-border-active":"#f472b6","--gh-hover":"#1a1a1a","--gh-active-bg":"#262626","--gh-input-bg":"#121212","--gh-input-border":"#404040","--gh-input-focus-border":"#f472b6","--gh-input-focus-shadow":"0 0 0 2px rgba(244, 114, 182, 0.3)","--gh-shadow":"0 0 20px rgba(244, 114, 182, 0.15)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.8)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 0 15px rgba(244, 114, 182, 0.4)","--gh-primary":"#f472b6","--gh-secondary":"#22d3ee","--gh-danger":"#ff0055","--gh-header-bg":"linear-gradient(45deg, #000000 0%, #1a1a1a 100%)","--gh-tag-active-bg":"#f472b6","--gh-checkbox-bg":"#f472b6","--gh-badge-text":"#f472b6","--gh-badge-bg":"#1a1a1a","--gh-badge-border":"#333333","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(135deg, rgba(244, 114, 182, 0.2) 0%, rgba(34, 211, 238, 0.2) 100%)","--gh-folder-bg-default":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-expanded":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.2)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.2)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.2)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.2)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.2)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.2)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.2)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.2)","--gh-outline-locate-border":"#facc15","--gh-outline-locate-shadow":"0 0 10px rgba(250, 204, 21, 0.6)","--gh-outline-sync-bg":"rgba(250, 204, 21, 0.15)","--gh-outline-sync-border":"#eab308","--gh-user-query-bg":"rgba(34, 211, 238, 0.1)","--gh-user-query-hover-bg":"rgba(34, 211, 238, 0.2)","--gh-bg-danger":"rgba(255, 0, 85, 0.15)","--gh-text-danger":"#ff0055","--gh-bg-danger-hover":"rgba(255, 0, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #be185d 0%, #0891b2 100%)","--gh-brand-border":"#333333","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.1)","--gh-glass-text":"#f472b6","--gh-card-bg":"#0a0a0a","--gh-card-border":"#333333","--gh-overlay-bg":"rgba(0, 0, 0, 0.85)","--gh-btn-shadow":"0 0 10px rgba(244, 114, 182, 0.3)","--gh-btn-shadow-hover":"0 0 15px rgba(244, 114, 182, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.5)","--gh-emoji-selected-bg":"rgba(244, 114, 182, 0.3)","--gh-highlight-pulse":"rgba(34, 211, 238, 0.4)","--gh-slider-dot-bg":"#555555","--gh-code-bg":"rgba(244, 114, 182, 0.1)"}},{id:"coffee",name:"醇香咖啡",description:"暖调护眼主题",variables:{"--gh-bg":"#1c1917","--gh-bg-secondary":"#292524","--gh-bg-tertiary":"#44403c","--gh-text":"#e7e5e4","--gh-text-secondary":"#a8a29e","--gh-text-tertiary":"#78716c","--gh-text-on-primary":"#e7e5e4","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44403c","--gh-border-active":"#d4a373","--gh-hover":"#292524","--gh-active-bg":"#44403c","--gh-input-bg":"#292524","--gh-input-border":"#57534e","--gh-input-focus-border":"#d4a373","--gh-input-focus-shadow":"0 0 0 2px rgba(212, 163, 115, 0.2)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(212, 163, 115, 0.2)","--gh-primary":"#d4a373","--gh-secondary":"#a96e45","--gh-danger":"#ef4444","--gh-header-bg":"#292524","--gh-tag-active-bg":"#d4a373","--gh-checkbox-bg":"#d4a373","--gh-badge-text":"#e7e5e4","--gh-badge-bg":"#44403c","--gh-badge-border":"#57534e","--gh-badge-shadow":"#1c1917","--gh-selected-gradient":"linear-gradient(135deg, rgba(212, 163, 115, 0.2) 0%, rgba(169, 110, 69, 0.15) 100%)","--gh-folder-bg-default":"rgba(212, 163, 115, 0.15)","--gh-folder-bg-expanded":"rgba(169, 110, 69, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(212, 163, 115, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(212, 163, 115, 0.1)","--gh-user-query-hover-bg":"rgba(212, 163, 115, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #d4a373 0%, #a96e45 100%)","--gh-brand-border":"#44403c","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e7e5e4","--gh-card-bg":"#292524","--gh-card-border":"#44403c","--gh-overlay-bg":"rgba(28, 25, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(212, 163, 115, 0.25)","--gh-highlight-pulse":"rgba(212, 163, 115, 0.3)","--gh-slider-dot-bg":"#78716c","--gh-code-bg":"rgba(212, 163, 115, 0.12)"}},{id:"sunset",name:"幻梦落日",description:"紫橙渐变艺术主题",variables:{"--gh-bg":"#120a21","--gh-bg-secondary":"#1d1136","--gh-bg-tertiary":"#2a1b4b","--gh-text":"#f3e8ff","--gh-text-secondary":"#d8b4fe","--gh-text-tertiary":"#a78bfa","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#4c1d95","--gh-border-active":"#f97316","--gh-hover":"#2a1b4b","--gh-active-bg":"#392463","--gh-input-bg":"#1d1136","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#f97316","--gh-input-focus-shadow":"0 0 0 2px rgba(249, 115, 22, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(249, 115, 22, 0.3)","--gh-primary":"#f97316","--gh-secondary":"#8b5cf6","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #be185d 100%)","--gh-tag-active-bg":"#f97316","--gh-checkbox-bg":"#f97316","--gh-badge-text":"#f3e8ff","--gh-badge-bg":"#2a1b4b","--gh-badge-border":"#4c1d95","--gh-badge-shadow":"#120a21","--gh-selected-gradient":"linear-gradient(135deg, rgba(139, 92, 246, 0.25) 0%, rgba(249, 115, 22, 0.2) 100%)","--gh-folder-bg-default":"rgba(139, 92, 246, 0.2)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.3)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(249, 115, 22, 0.25)","--gh-outline-locate-border":"#22d3ee","--gh-outline-locate-shadow":"rgba(34, 211, 238, 0.6)","--gh-outline-sync-bg":"rgba(34, 211, 238, 0.15)","--gh-outline-sync-border":"#06b6d4","--gh-user-query-bg":"rgba(139, 92, 246, 0.1)","--gh-user-query-hover-bg":"rgba(139, 92, 246, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #8b5cf6 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#f3e8ff","--gh-card-bg":"#1d1136","--gh-card-border":"#4c1d95","--gh-overlay-bg":"rgba(18, 10, 33, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(139, 92, 246, 0.3)","--gh-highlight-pulse":"rgba(249, 115, 22, 0.4)","--gh-slider-dot-bg":"#a78bfa","--gh-code-bg":"rgba(139, 92, 246, 0.12)"}},{id:"dracula",name:"德古拉",description:"经典极客主题",variables:{"--gh-bg":"#282a36","--gh-bg-secondary":"#21222c","--gh-bg-tertiary":"#44475a","--gh-text":"#f8f8f2","--gh-text-secondary":"#bd93f9","--gh-text-tertiary":"#6272a4","--gh-text-on-primary":"#f8f8f2","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#44475a","--gh-border-active":"#ff79c6","--gh-hover":"#44475a","--gh-active-bg":"#21222c","--gh-input-bg":"#21222c","--gh-input-border":"#6272a4","--gh-input-focus-border":"#ff79c6","--gh-input-focus-shadow":"0 0 0 2px rgba(255, 121, 198, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.5)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.3)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.6)","--gh-shadow-brand":"0 4px 12px rgba(255, 121, 198, 0.3)","--gh-primary":"#ff79c6","--gh-secondary":"#bd93f9","--gh-danger":"#ff5555","--gh-header-bg":"#21222c","--gh-tag-active-bg":"#ff79c6","--gh-checkbox-bg":"#ff79c6","--gh-badge-text":"#f8f8f2","--gh-badge-bg":"#44475a","--gh-badge-border":"#6272a4","--gh-badge-shadow":"#282a36","--gh-selected-gradient":"linear-gradient(135deg, rgba(189, 147, 249, 0.25) 0%, rgba(255, 121, 198, 0.15) 100%)","--gh-folder-bg-default":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-expanded":"rgba(255, 121, 198, 0.25)","--gh-folder-bg-0":"rgba(241, 250, 140, 0.15)","--gh-folder-bg-1":"rgba(255, 121, 198, 0.15)","--gh-folder-bg-2":"rgba(189, 147, 249, 0.15)","--gh-folder-bg-3":"rgba(80, 250, 123, 0.15)","--gh-folder-bg-4":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-5":"rgba(255, 184, 108, 0.15)","--gh-folder-bg-6":"rgba(139, 233, 253, 0.15)","--gh-folder-bg-7":"rgba(255, 121, 198, 0.15)","--gh-outline-locate-bg":"rgba(255, 121, 198, 0.25)","--gh-outline-locate-border":"#4ade80","--gh-outline-locate-shadow":"rgba(74, 222, 128, 0.6)","--gh-outline-sync-bg":"rgba(74, 222, 128, 0.15)","--gh-outline-sync-border":"#22c55e","--gh-user-query-bg":"rgba(189, 147, 249, 0.1)","--gh-user-query-hover-bg":"rgba(189, 147, 249, 0.2)","--gh-bg-danger":"rgba(255, 85, 85, 0.15)","--gh-text-danger":"#ff5555","--gh-bg-danger-hover":"rgba(255, 85, 85, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #bd93f9 0%, #ff79c6 100%)","--gh-brand-border":"#44475a","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#f8f8f2","--gh-card-bg":"#21222c","--gh-card-border":"#44475a","--gh-overlay-bg":"rgba(40, 42, 54, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(241, 250, 140, 0.5)","--gh-emoji-selected-bg":"rgba(189, 147, 249, 0.3)","--gh-highlight-pulse":"rgba(255, 121, 198, 0.4)","--gh-slider-dot-bg":"#6272a4","--gh-code-bg":"rgba(189, 147, 249, 0.12)"}},{id:"deep-abyss",name:"深海幽蓝",description:"静谧蓝绿主题",variables:{"--gh-bg":"#042f2e","--gh-bg-secondary":"#134e4a","--gh-bg-tertiary":"#115e59","--gh-text":"#ccfbf1","--gh-text-secondary":"#5eead4","--gh-text-tertiary":"#2dd4bf","--gh-text-on-primary":"#042f2e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#115e59","--gh-border-active":"#2dd4bf","--gh-hover":"#134e4a","--gh-active-bg":"#115e59","--gh-input-bg":"#134e4a","--gh-input-border":"#115e59","--gh-input-focus-border":"#2dd4bf","--gh-input-focus-shadow":"0 0 0 2px rgba(45, 212, 191, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(45, 212, 191, 0.3)","--gh-primary":"#2dd4bf","--gh-secondary":"#0ea5e9","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f766e 0%, #0369a1 100%)","--gh-tag-active-bg":"#2dd4bf","--gh-checkbox-bg":"#2dd4bf","--gh-badge-text":"#ccfbf1","--gh-badge-bg":"#115e59","--gh-badge-border":"#2d7a74","--gh-badge-shadow":"#042f2e","--gh-selected-gradient":"linear-gradient(135deg, rgba(45, 212, 191, 0.25) 0%, rgba(14, 165, 233, 0.15) 100%)","--gh-folder-bg-default":"rgba(45, 212, 191, 0.15)","--gh-folder-bg-expanded":"rgba(14, 165, 233, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(45, 212, 191, 0.25)","--gh-outline-locate-border":"#fb923c","--gh-outline-locate-shadow":"rgba(251, 146, 60, 0.6)","--gh-outline-sync-bg":"rgba(251, 146, 60, 0.15)","--gh-outline-sync-border":"#f97316","--gh-user-query-bg":"rgba(45, 212, 191, 0.1)","--gh-user-query-hover-bg":"rgba(45, 212, 191, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #2dd4bf 0%, #0ea5e9 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#ccfbf1","--gh-card-bg":"#134e4a","--gh-card-border":"#115e59","--gh-overlay-bg":"rgba(4, 47, 46, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(45, 212, 191, 0.25)","--gh-highlight-pulse":"rgba(45, 212, 191, 0.3)","--gh-slider-dot-bg":"#334155","--gh-code-bg":"rgba(45, 212, 191, 0.1)","--gh-bg-image":"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='turbulence' baseFrequency='0.02' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.15'/%3E%3C/svg%3E\")"}},{id:"crimson-moon",name:"猩红赤月",description:"暗红狂野主题",variables:{"--gh-bg":"#0f0f0f","--gh-bg-secondary":"#1c1c1c","--gh-bg-tertiary":"#2a2a2a","--gh-text":"#fecaca","--gh-text-secondary":"#f87171","--gh-text-tertiary":"#ef4444","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#450a0a","--gh-border-active":"#ef4444","--gh-hover":"#2a2a2a","--gh-active-bg":"#450a0a","--gh-input-bg":"#1c1c1c","--gh-input-border":"#450a0a","--gh-input-focus-border":"#ef4444","--gh-input-focus-shadow":"0 0 0 2px rgba(239, 68, 68, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.8)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.6)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.9)","--gh-shadow-brand":"0 4px 12px rgba(239, 68, 68, 0.3)","--gh-primary":"#ef4444","--gh-secondary":"#991b1b","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #7f1d1d 0%, #991b1b 100%)","--gh-tag-active-bg":"#ef4444","--gh-checkbox-bg":"#ef4444","--gh-badge-text":"#fee2e2","--gh-badge-bg":"#450a0a","--gh-badge-border":"#7f1d1d","--gh-badge-shadow":"#0f0f0f","--gh-selected-gradient":"linear-gradient(135deg, rgba(239, 68, 68, 0.25) 0%, rgba(153, 27, 27, 0.15) 100%)","--gh-folder-bg-default":"rgba(239, 68, 68, 0.15)","--gh-folder-bg-expanded":"rgba(153, 27, 27, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(251, 113, 133, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(239, 68, 68, 0.25)","--gh-outline-locate-border":"#fbbf24","--gh-outline-locate-shadow":"rgba(251, 191, 36, 0.6)","--gh-outline-sync-bg":"rgba(251, 191, 36, 0.15)","--gh-outline-sync-border":"#f59e0b","--gh-user-query-bg":"rgba(239, 68, 68, 0.1)","--gh-user-query-hover-bg":"rgba(239, 68, 68, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#fecaca","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #ef4444 0%, #991b1b 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#fecaca","--gh-card-bg":"#1c1c1c","--gh-card-border":"#450a0a","--gh-overlay-bg":"rgba(15, 15, 15, 0.9)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(239, 68, 68, 0.25)","--gh-highlight-pulse":"rgba(239, 68, 68, 0.3)","--gh-slider-dot-bg":"#f87171","--gh-code-bg":"rgba(239, 68, 68, 0.12)"}},{id:"retro-terminal",name:"黑客终端",description:"复古 CRT 主题",variables:{"--gh-bg":"#0c0c0c","--gh-bg-secondary":"#000000","--gh-bg-tertiary":"#1a1a1a","--gh-text":"#22c55e","--gh-text-secondary":"#15803d","--gh-text-tertiary":"#14532d","--gh-text-on-primary":"#22c55e","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#14532d","--gh-border-active":"#22c55e","--gh-hover":"#1a1a1a","--gh-active-bg":"#14532d","--gh-input-bg":"#000000","--gh-input-border":"#15803d","--gh-input-focus-border":"#4ade80","--gh-input-focus-shadow":"0 0 0 2px rgba(74, 222, 128, 0.3)","--gh-shadow":"0 0 20px rgba(34, 197, 94, 0.1)","--gh-shadow-sm":"0 0 10px rgba(34, 197, 94, 0.1)","--gh-shadow-lg":"0 0 40px rgba(34, 197, 94, 0.2)","--gh-shadow-brand":"0 0 15px rgba(34, 197, 94, 0.3)","--gh-primary":"#15803d","--gh-secondary":"#4ade80","--gh-danger":"#ef4444","--gh-header-bg":"#000000","--gh-tag-active-bg":"#22c55e","--gh-checkbox-bg":"#22c55e","--gh-badge-text":"#22c55e","--gh-badge-bg":"#000000","--gh-badge-border":"#15803d","--gh-badge-shadow":"#000000","--gh-selected-gradient":"linear-gradient(90deg, rgba(34, 197, 94, 0.25) 0%, rgba(34, 197, 94, 0.05) 100%)","--gh-folder-bg-default":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-expanded":"rgba(34, 197, 94, 0.2)","--gh-folder-bg-0":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-1":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-2":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-3":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-4":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-5":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-6":"rgba(34, 197, 94, 0.1)","--gh-folder-bg-7":"rgba(34, 197, 94, 0.1)","--gh-outline-locate-bg":"rgba(34, 197, 94, 0.5)","--gh-outline-locate-border":"#f59e0b","--gh-outline-locate-shadow":"0 0 15px rgba(245, 158, 11, 0.6)","--gh-outline-sync-bg":"rgba(245, 158, 11, 0.1)","--gh-outline-sync-border":"#d97706","--gh-user-query-bg":"rgba(34, 197, 94, 0.05)","--gh-user-query-hover-bg":"rgba(34, 197, 94, 0.1)","--gh-bg-danger":"rgba(239, 68, 68, 0.2)","--gh-text-danger":"#ef4444","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.3)","--gh-brand-gradient":"linear-gradient(135deg, #022c22 0%, #15803d 100%)","--gh-brand-border":"#15803d","--gh-glass-bg":"rgba(0, 0, 0, 0.8)","--gh-glass-bg-hover":"rgba(0, 0, 0, 0.9)","--gh-glass-text":"#22c55e","--gh-card-bg":"#000000","--gh-card-border":"#15803d","--gh-overlay-bg":"rgba(0, 0, 0, 0.9)","--gh-btn-shadow":"0 0 8px rgba(34, 197, 94, 0.4)","--gh-btn-shadow-hover":"0 0 12px rgba(34, 197, 94, 0.6)","--gh-search-highlight-bg":"rgba(34, 197, 94, 0.4)","--gh-emoji-selected-bg":"rgba(34, 197, 94, 0.2)","--gh-highlight-pulse":"rgba(34, 197, 94, 0.5)","--gh-slider-dot-bg":"#14532d","--gh-code-bg":"rgba(34, 197, 94, 0.15)","--gh-bg-image":"repeating-linear-gradient(to bottom, transparent 0px, transparent 2px, rgba(34, 197, 94, 0.05) 2px, rgba(34, 197, 94, 0.05) 4px)","--gh-bg-animation":"gh-scanline 8s linear infinite"}},{id:"eva-unit-01",name:"代号:暴走",description:"机甲撞色主题",variables:{"--gh-bg":"#2e1065","--gh-bg-secondary":"#1e0b4b","--gh-bg-tertiary":"#4c1d95","--gh-text":"#d9f99d","--gh-text-secondary":"#bef264","--gh-text-tertiary":"#a3e635","--gh-text-on-primary":"#1e0b4b","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#d9f99d","--gh-border-active":"#a3e635","--gh-hover":"#4c1d95","--gh-active-bg":"#5b21b6","--gh-input-bg":"#1e0b4b","--gh-input-border":"#5b21b6","--gh-input-focus-border":"#a3e635","--gh-input-focus-shadow":"0 0 0 2px rgba(163, 230, 53, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.6)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.4)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.7)","--gh-shadow-brand":"0 4px 12px rgba(163, 230, 53, 0.3)","--gh-primary":"#a3e635","--gh-secondary":"#f97316","--gh-danger":"#ef4444","--gh-header-bg":"linear-gradient(135deg, #4c1d95 0%, #a3e635 100%)","--gh-tag-active-bg":"#a3e635","--gh-checkbox-bg":"#a3e635","--gh-badge-text":"#1e0b4b","--gh-badge-bg":"#d9f99d","--gh-badge-border":"#a3e635","--gh-badge-shadow":"#2e1065","--gh-selected-gradient":"linear-gradient(135deg, rgba(163, 230, 53, 0.25) 0%, rgba(249, 115, 22, 0.15) 100%)","--gh-folder-bg-default":"rgba(163, 230, 53, 0.15)","--gh-folder-bg-expanded":"rgba(249, 115, 22, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(163, 230, 53, 0.3)","--gh-outline-locate-border":"#f97316","--gh-outline-locate-shadow":"rgba(249, 115, 22, 0.6)","--gh-outline-sync-bg":"rgba(249, 115, 22, 0.15)","--gh-outline-sync-border":"#ea580c","--gh-user-query-bg":"rgba(163, 230, 53, 0.1)","--gh-user-query-hover-bg":"rgba(163, 230, 53, 0.2)","--gh-bg-danger":"rgba(239, 68, 68, 0.15)","--gh-text-danger":"#fca5a5","--gh-bg-danger-hover":"rgba(239, 68, 68, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #a3e635 0%, #f97316 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.1)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.15)","--gh-glass-text":"#d9f99d","--gh-card-bg":"#1e0b4b","--gh-card-border":"#5b21b6","--gh-overlay-bg":"rgba(46, 16, 101, 0.85)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.5)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.6)","--gh-search-highlight-bg":"rgba(249, 115, 22, 0.5)","--gh-emoji-selected-bg":"rgba(163, 230, 53, 0.3)","--gh-highlight-pulse":"rgba(163, 230, 53, 0.4)","--gh-slider-dot-bg":"#4b5563","--gh-code-bg":"rgba(163, 230, 53, 0.12)"}},{id:"aurora",name:"极光行者",description:"自然奇观主题",variables:{"--gh-bg":"#020617","--gh-bg-secondary":"#0f172a","--gh-bg-tertiary":"#1e293b","--gh-text":"#e0f2fe","--gh-text-secondary":"#bae6fd","--gh-text-tertiary":"#7dd3fc","--gh-text-on-primary":"#ffffff","--gh-footer-text":"var(--gh-text-on-primary)","--gh-border":"#1e293b","--gh-border-active":"#38bdf8","--gh-hover":"#0f172a","--gh-active-bg":"#1e293b","--gh-input-bg":"#0f172a","--gh-input-border":"#1e293b","--gh-input-focus-border":"#38bdf8","--gh-input-focus-shadow":"0 0 0 2px rgba(56, 189, 248, 0.3)","--gh-shadow":"0 10px 40px rgba(0, 0, 0, 0.7)","--gh-shadow-sm":"0 1px 3px rgba(0, 0, 0, 0.5)","--gh-shadow-lg":"0 20px 60px rgba(0, 0, 0, 0.8)","--gh-shadow-brand":"0 4px 12px rgba(56, 189, 248, 0.3)","--gh-primary":"#38bdf8","--gh-secondary":"#34d399","--gh-danger":"#f87171","--gh-header-bg":"linear-gradient(135deg, #0f172a 0%, #1e40af 100%)","--gh-tag-active-bg":"#38bdf8","--gh-checkbox-bg":"#38bdf8","--gh-badge-text":"#e0f2fe","--gh-badge-bg":"#1e293b","--gh-badge-border":"#38bdf8","--gh-badge-shadow":"#020617","--gh-selected-gradient":"linear-gradient(135deg, rgba(56, 189, 248, 0.25) 0%, rgba(52, 211, 153, 0.15) 100%)","--gh-folder-bg-default":"rgba(56, 189, 248, 0.15)","--gh-folder-bg-expanded":"rgba(52, 211, 153, 0.25)","--gh-folder-bg-0":"rgba(253, 224, 71, 0.15)","--gh-folder-bg-1":"rgba(244, 114, 182, 0.15)","--gh-folder-bg-2":"rgba(96, 165, 250, 0.15)","--gh-folder-bg-3":"rgba(52, 211, 153, 0.15)","--gh-folder-bg-4":"rgba(167, 139, 250, 0.15)","--gh-folder-bg-5":"rgba(253, 224, 71, 0.1)","--gh-folder-bg-6":"rgba(34, 211, 238, 0.15)","--gh-folder-bg-7":"rgba(232, 121, 249, 0.15)","--gh-outline-locate-bg":"rgba(244, 114, 182, 0.25)","--gh-outline-locate-border":"#f472b6","--gh-outline-locate-shadow":"rgba(244, 114, 182, 0.5)","--gh-outline-sync-bg":"rgba(244, 114, 182, 0.15)","--gh-outline-sync-border":"#f472b6","--gh-user-query-bg":"rgba(56, 189, 248, 0.1)","--gh-user-query-hover-bg":"rgba(56, 189, 248, 0.2)","--gh-bg-danger":"rgba(248, 113, 113, 0.15)","--gh-text-danger":"#f87171","--gh-bg-danger-hover":"rgba(248, 113, 113, 0.25)","--gh-brand-gradient":"linear-gradient(135deg, #0369a1 0%, #0f766e 100%)","--gh-brand-border":"transparent","--gh-glass-bg":"rgba(255, 255, 255, 0.05)","--gh-glass-bg-hover":"rgba(255, 255, 255, 0.08)","--gh-glass-text":"#e0f2fe","--gh-card-bg":"#0f172a","--gh-card-border":"#1e293b","--gh-overlay-bg":"rgba(2, 6, 23, 0.8)","--gh-btn-shadow":"0 2px 6px rgba(0, 0, 0, 0.4)","--gh-btn-shadow-hover":"0 4px 12px rgba(0, 0, 0, 0.5)","--gh-search-highlight-bg":"rgba(255, 235, 59, 0.4)","--gh-emoji-selected-bg":"rgba(56, 189, 248, 0.25)","--gh-highlight-pulse":"rgba(56, 189, 248, 0.3)","--gh-slider-dot-bg":"#7dd3fc","--gh-code-bg":"rgba(56, 189, 248, 0.12)"}}],Fv=(e,t)=>{const n=((e,t)=>("light"===t?Bv:Ov).find(t=>t.id===e))(e,t);return n||("light"===t?Bv[0]:Ov[0])},$v="google-gradient",Uv="classic-dark",jv="ophel-native-adaptive-style";class Hv{mode;preference;lightPresetId;darkPresetId;hostThemeObserver=null;onModeChange;adapter;nativeThemeOverrideEnabled;customStyles=[];skipNextDetection=false;listeners=new Set;systemMediaQuery=null;handleSystemChange=e=>{if("system"!==this.preference)return;const t=e.matches?"dark":"light";this.mode!==t&&(this.mode=t,this.emitChange(),this.syncHostTheme(t,"system"),this.onModeChange&&this.onModeChange(t,this.preference));};constructor(e,t,n,r="google-gradient",o="classic-dark",i=true){const a="system"===e?"system":"dark"===e?"dark":"light";this.preference=a,this.mode=this.resolveMode(a),this.lightPresetId=r,this.darkPresetId=o,this.onModeChange=t,this.adapter=n,this.nativeThemeOverrideEnabled=i,this.injectGlobalStyles(),this.ensureSystemListener();}ensureSystemListener(){!this.systemMediaQuery&&"undefined"!=typeof window&&window.matchMedia&&(this.systemMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),"function"==typeof this.systemMediaQuery.addEventListener?this.systemMediaQuery.addEventListener("change",this.handleSystemChange):"function"==typeof this.systemMediaQuery.addListener&&this.systemMediaQuery.addListener(this.handleSystemChange));}getSystemMode(){return "undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}resolveMode(e){return "system"===e?this.getSystemMode():e}isHostThemeSyncActive(){return this.adapter?.supportsHostThemeSync()??true}isNativeThemeOverrideActive(){return this.nativeThemeOverrideEnabled&&this.isHostThemeSyncActive()}syncHostTheme(e,t=e){if(this.isHostThemeSyncActive()){if("system"===t){!this.applySystemPreferenceToHost(e)&&this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(e).catch(()=>{});}else this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{});this.applyTheme(e);}else this.applyTheme(e);}applySystemPreferenceToHost(e){if(!this.adapter)return false;const t=this.adapter.getSiteId();try{switch(t){case co:return localStorage.setItem("theme","system"),document.documentElement.className=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case ko:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case go:return localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0;case wo:{const t=localStorage.getItem("theme");localStorage.setItem("theme","system"),document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(e),document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e,document.body&&(document.body.setAttribute("data-theme",e),document.body.style.colorScheme=e);const n=document.querySelector('meta[name="color-scheme"]');return n&&n.setAttribute("content",e),"system"!==t&&this.adapter?.toggleTheme?this.adapter.toggleTheme("system").catch(()=>{}):window.dispatchEvent(new StorageEvent("storage",{key:"theme",newValue:"system",storageArea:localStorage})),!0}case po:{const t=localStorage.getItem("aiStudioUserPreference")||"{}";let n={};try{n=JSON.parse(t);}catch{n={};}n.theme="system";const r=JSON.stringify(n);localStorage.setItem("aiStudioUserPreference",r);const o=document.body;"dark"===e?(o.classList.add("dark-theme"),o.classList.remove("light-theme")):(o.classList.remove("dark-theme"),o.classList.add("light-theme")),o.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"aiStudioUserPreference",newValue:r,storageArea:localStorage}));const i=document.querySelector("app-root, ms-app, body");return i&&i.dispatchEvent(new CustomEvent("themechange",{detail:{theme:e}})),!0}case bo:case uo:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case lo:return localStorage.removeItem("Bard-Color-Theme"),"dark"===e?(document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme")):(document.body.classList.remove("dark-theme"),document.body.classList.add("light-theme")),document.body.style.colorScheme=e,window.dispatchEvent(new StorageEvent("storage",{key:"Bard-Color-Theme",newValue:null,storageArea:localStorage})),!0;case so:case ho:return !(!this.adapter||"function"!=typeof this.adapter.toggleTheme)&&(this.adapter.toggleTheme("system").catch(()=>{}),!0);case mo:return !1;case xo:return localStorage.setItem("yb_web_theme_mode","system"),window.dispatchEvent(new StorageEvent("storage",{key:"yb_web_theme_mode",newValue:"system",storageArea:localStorage})),document.documentElement.style.colorScheme="",!0;default:return !1}}catch{return false}}injectGlobalStyles(){if(document.getElementById("gh-global-styles"))return;const e=document.createElement("style");e.id="gh-global-styles",e.textContent="\n ::view-transition-old(root),\n ::view-transition-new(root),\n ::view-transition-old(gh-page),\n ::view-transition-new(gh-page) {\n animation: none;\n mix-blend-mode: normal;\n }\n\n ::view-transition-new(gh-page),\n ::view-transition-new(root) {\n clip-path: circle(0px at var(--theme-x, 50%) var(--theme-y, 50%));\n }\n ",document.head.appendChild(e);}injectNativeThemeOverrideCss(){if(!this.adapter||!this.isNativeThemeOverrideActive())return;const e=this.adapter.getNativeThemeCss();if(!e||document.getElementById(jv))return;const t=document.createElement("style");t.id=jv,t.textContent=e,document.head.appendChild(t);}removeNativeThemeOverrideCss(){document.getElementById(jv)?.remove();}syncNativeThemeOverrideCssState(){this.isNativeThemeOverrideActive()?this.injectNativeThemeOverrideCss():this.removeNativeThemeOverrideCss();}setAdapter(e){this.adapter=e,this.syncNativeThemeOverrideCssState(),this.isHostThemeSyncActive()||(this.stopThemeMonitoring(),this.syncPluginUiTheme(this.mode));}setOnModeChange(e){this.onModeChange=e;}setNativeThemeOverrideEnabled(e){const t=false!==e;this.nativeThemeOverrideEnabled=t,this.syncNativeThemeOverrideCssState();}applyModePreference(e){const t="system"===e?"system":"dark"===e?"dark":"light";this.preference=t,this.mode=this.resolveMode(t),this.emitChange(),"system"!==this.preference?this.applyTheme(this.mode):this.syncHostTheme(this.mode,"system");}applyGenericHostThemeFallback(e){const t=this.adapter?.getSiteId()===lo;if("dark"===e)return document.body.classList.add("dark-theme"),document.body.classList.remove("light-theme"),void(document.body.style.colorScheme="dark");document.body.classList.remove("dark-theme"),document.body.style.colorScheme="light",t?document.body.classList.add("light-theme"):document.body.classList.remove("light-theme");}detectHostThemeMode(){const e=document.documentElement.getAttribute("yb-theme-mode");if("dark"===e)return "dark";if("light"===e)return "light";if("system"===e)return this.getSystemMode();const t=document.documentElement.className;if(/\bdark\b/i.test(t))return "dark";if(/\blight\b/i.test(t))return "light";const n=document.body.className;if(/\bdark-theme\b/i.test(n))return "dark";if(/\blight-theme\b/i.test(n))return "light";const r=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===r?"dark":"light"===r?"light":"dark"===document.body.style.colorScheme?"dark":"light"}detectHostThemePreference(){if(!this.adapter)return null;const e=this.adapter.getSiteId();try{switch(e){case co:case go:case ko:case wo:{const e=localStorage.getItem("theme");return "light"===e||"dark"===e||"system"===e?e:null}case po:{const e=localStorage.getItem("aiStudioUserPreference");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.theme;return "light"===n||"dark"===n||"system"===n?n:null}case bo:{const e=localStorage.getItem("__appKit_@deepseek/chat_themePreference");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.value;return "light"===n||"dark"===n||"system"===n?n:null}case uo:{const e=localStorage.getItem("SKIN_MODE");return "1"===e?"light":"2"===e?"dark":"3"===e?"system":null}case lo:{const e=localStorage.getItem("Bard-Color-Theme");return e?/dark/i.test(e)?"dark":/light/i.test(e)?"light":null:"system"}case so:{const e=localStorage.getItem("LSS-userThemeMode");if(!e)return null;let t={};try{t=JSON.parse(e);}catch{t={};}const n=t.value;return "auto"===n||"system"===n?"system":"dark"===n||"light"===n?n:null}case ho:{const e=os.query("md-primary-tab",{all:!0,shadow:!0});if(!e||0===e.length)return null;const t=[];for(const r of e){let e=r.querySelector("md-icon");e||(e=os.query("md-icon",{parent:r,shadow:!0}));const n=e?.textContent?.trim();if("computer"!==n&&"light_mode"!==n&&"dark_mode"!==n)continue;const o=r,i=Boolean(o.selected||o.active||0===o.tabIndex);t.push({icon:n,selected:i});}const n=t.find(e=>e.selected);return n?"computer"===n.icon?"system":"dark_mode"===n.icon?"dark":"light":null}case mo:return "light";case xo:{const e=localStorage.getItem("yb_web_theme_mode");return "light"===e||"dark"===e||"system"===e?e:null}default:return null}}catch{return null}}applyTheme(e){const t=e||this.mode;!this.isHostThemeSyncActive()||this.adapter&&this.adapter.hasCustomToggleTheme()||this.applyGenericHostThemeFallback(t),this.syncPluginUiTheme(t);}getCurrentPreset(){const e="dark"===this.mode?this.darkPresetId:this.lightPresetId;return Fv(e,this.mode)}setPresets(e,t){this.lightPresetId=e,this.darkPresetId=t,this.syncPluginUiTheme();}setCustomStyles(e){this.customStyles=e||[];const t="dark"===this.mode?this.darkPresetId:this.lightPresetId;this.customStyles.some(e=>e.id===t)&&this.syncPluginUiTheme();}syncPluginUiTheme(e){const t=e||this.mode,n=document.documentElement,r="dark"===t?this.darkPresetId:this.lightPresetId,o=this.customStyles.find(e=>e.id===r);let i=null;if(o);else try{i=Fv(r,t).variables;}catch(c){return void console.error("[ThemeManager] getPreset FAILED:",c)}const a=null!==this.hostThemeObserver;if(a&&this.hostThemeObserver?.disconnect(),"dark"===t?document.body.dataset.ghMode="dark":delete document.body.dataset.ghMode,i)for(const[d,u]of Object.entries(i))n.style.setProperty(d,u);let s="";if(o)s=o.css;else if(i){const e=(l=i,Object.entries(l).map(([e,t])=>`${e}: ${t} !important;`).join("\n "));s=`:host {\n${e}\ncolor-scheme: ${t};\n}\n\n:host([data-theme="dark"]),\n:host .gh-root[data-theme="dark"] {\n${e}\n}\n`;}var l;if(document.querySelectorAll("plasmo-csui, #ophel-userscript-root").forEach(e=>{const n=e.shadowRoot;if(n){let r=n.querySelector("#gh-theme-vars");r||(r=document.createElement("style"),r.id="gh-theme-vars"),s&&(r.textContent=s),e.dataset.theme=t,n.append(r);}}),s)try{const e="undefined"!=typeof chrome&&chrome.runtime?.id?"ophel_ext_theme_cache":"ophel_us_theme_cache";localStorage.setItem(e,s);}catch{}a&&this.hostThemeObserver&&(this.hostThemeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.hostThemeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme","yb-theme-mode"]}));}startThemeMonitoring(){if(!this.isHostThemeSyncActive())return this.stopThemeMonitoring(),void this.syncPluginUiTheme(this.mode);const e=()=>{if(this.skipNextDetection)return void(this.skipNextDetection=false);const e=this.detectHostThemeMode(),t=this.detectHostThemePreference()??e,n="system"===t?this.getSystemMode():t;"system"===t?(this.ensureSystemListener(),e!==n?this.syncHostTheme(n,"system"):this.syncPluginUiTheme(n)):this.syncPluginUiTheme(n),this.mode===n&&this.preference===t||(this.mode=n,this.preference=t,this.emitChange(),this.onModeChange&&this.onModeChange(n,t));};e(),this.hostThemeObserver||(this.hostThemeObserver=new MutationObserver(()=>{e();}),this.hostThemeObserver.observe(document.body,{attributes:true,attributeFilter:["class","data-theme","style"]}),this.hostThemeObserver.observe(document.documentElement,{attributes:true,attributeFilter:["class","data-theme","yb-theme-mode"]}));}stopThemeMonitoring(){this.hostThemeObserver&&(this.hostThemeObserver.disconnect(),this.hostThemeObserver=null);}getTransitionOrigin(e){let t=95,n=5;if(e&&void 0!==e.clientX)return t=e.clientX/window.innerWidth*100,n=e.clientY/window.innerHeight*100,{x:t,y:n};const r=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(r){const e=r.getBoundingClientRect();t=(e.left+e.width/2)/window.innerWidth*100,n=(e.top+e.height/2)/window.innerHeight*100;}return {x:t,y:n}}prepareTransitionSnapshotTarget(){if(this.adapter?.getSiteId()!==co||!document.body)return {pseudoElement:"::view-transition-new(root)",cleanup:()=>{}};const e=document.body.style.getPropertyValue("view-transition-name");return document.body.style.setProperty("view-transition-name","gh-page"),{pseudoElement:"::view-transition-new(gh-page)",cleanup:()=>{e?document.body.style.setProperty("view-transition-name",e):document.body.style.removeProperty("view-transition-name");}}}async applyWithTransition(e,t){const{x:n,y:r}=this.getTransitionOrigin(t);document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopThemeMonitoring();const o=window.matchMedia("(prefers-reduced-motion: reduce)").matches;if(!document.startViewTransition||o){try{e();}finally{this.startThemeMonitoring();}return false}const i=this.prepareTransitionSnapshotTarget();try{const t=document.startViewTransition(()=>{e();});t.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),a=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:a},{duration:500,easing:"ease-in",pseudoElement:i.pseudoElement,fill:"forwards"});}),await t.finished.catch(()=>{});}catch{return e(),i.cleanup(),this.startThemeMonitoring(),false}return i.cleanup(),this.skipNextDetection=true,this.startThemeMonitoring(),true} /** * 切换主题(User Action)- 带圆形扩散动画 * @param event 可选的鼠标事件,用于确定动画中心 */async toggle(e){const t="dark"===("system"!==this.preference&&this.isHostThemeSyncActive()?this.detectHostThemeMode():this.mode)?"light":"dark";this.preference=t;let n=95,r=5;if(e&&void 0!==e.clientX)n=e.clientX/window.innerWidth*100,r=e.clientY/window.innerHeight*100;else {const e=document.getElementById("theme-toggle-btn")||document.getElementById("quick-theme-btn");if(e){const t=e.getBoundingClientRect();n=(t.left+t.width/2)/window.innerWidth*100,r=(t.top+t.height/2)/window.innerHeight*100;}}document.documentElement.style.setProperty("--theme-x",`${n}%`),document.documentElement.style.setProperty("--theme-y",`${r}%`),this.stopThemeMonitoring();const o=()=>{this.isHostThemeSyncActive()&&this.adapter&&"function"==typeof this.adapter.toggleTheme&&this.adapter.toggleTheme(t).catch(()=>{}),this.applyTheme(t);};if(!document.startViewTransition||window.matchMedia("(prefers-reduced-motion: reduce)").matches)return o(),this.mode=t,this.emitChange(),this.startThemeMonitoring(),t;const i=this.prepareTransitionSnapshotTarget();let a;try{a=document.startViewTransition(()=>{o();});}catch{return i.cleanup(),o(),this.mode=t,this.emitChange(),this.startThemeMonitoring(),t}return a.ready.then(()=>{const e=window.innerWidth-n/100*window.innerWidth,t=window.innerHeight-r/100*window.innerHeight,o=Math.hypot(Math.max(n/100*window.innerWidth,e),Math.max(r/100*window.innerHeight,t)),a=[`circle(0px at ${n}% ${r}%)`,`circle(${o}px at ${n}% ${r}%)`];document.documentElement.animate({clipPath:a},{duration:500,easing:"ease-in",pseudoElement:i.pseudoElement,fill:"forwards"});}),await a.finished.catch(()=>{}),i.cleanup(),this.skipNextDetection=true,this.isHostThemeSyncActive()?(this.onModeChange&&this.onModeChange(t,this.preference),this.startThemeMonitoring(),this.mode=t,this.emitChange(),t):(this.mode=t,this.emitChange(),this.onModeChange&&this.onModeChange(t,this.preference),this.startThemeMonitoring(),t)} /** * 设置主题模式(绝对操作) * 与 toggle() 不同,此方法明确指定目标模式,无论调用多少次结果都是确定的 * 如果当前已是目标模式,则不做任何操作 * @param targetMode 目标模式 * @param event 可选的鼠标事件,用于确定动画中心 * @returns 包含最终模式和是否触发了动画 */async setMode(e,t){const n="system"===e?"system":"dark"===e?"dark":"light";if("system"===n){this.preference="system",this.ensureSystemListener();const e=this.getSystemMode(),n=this.mode!==e;let r=false;return Boolean(t)&&n?r=await this.applyWithTransition(()=>{this.syncHostTheme(e,"system");},t):this.syncHostTheme(e,"system"),n&&(this.mode=e,this.emitChange(),this.isHostThemeSyncActive()||this.syncPluginUiTheme(e)),this.onModeChange&&this.onModeChange(e,this.preference),{mode:e,animated:r}}if((this.isHostThemeSyncActive()?this.detectHostThemeMode():this.mode)===n)return this.preference=n,this.syncHostTheme(n,n),this.onModeChange&&this.onModeChange(n,this.preference),{mode:n,animated:false};return {mode:await this.toggle(t),animated:true}}getMode(){return this.mode}getPreference(){return this.preference}getSnapshot=()=>this.mode; /** * 订阅模式变化(用于 useSyncExternalStore) * @returns 取消订阅函数 */ subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e);});emitChange(){for(const e of this.listeners)e();}destroy(){this.stopThemeMonitoring(),this.listeners.clear();}}function Wv(e){const{mode:t,onModeChange:n,adapter:r,lightPresetId:o=$v,darkPresetId:i=Uv,syncNativePageTheme:a=true,apply:s=false}=e,l=window.__ophelThemeManager||new Hv(t,n,r,o,i,a);window.__ophelThemeManager||(window.__ophelThemeManager=l),l.setAdapter(r??null),l.setNativeThemeOverrideEnabled(a),l.setPresets(o,i),void 0!==n&&l.setOnModeChange(n);const c="system"===t?"system":"dark"===t?"dark":"light";return l.getPreference()!==c?l.applyModePreference(c):s&&l.applyTheme(),l}const Gv=new Set(["outline-search-input","conversations-search-input","prompt-search-input"]),Qv=e=>{const t=e.composedPath().find(e=>e instanceof HTMLElement);return t||(e.target instanceof HTMLElement?e.target:null)};function Vv({edgeSnapState:e,panelMode:t,isPanelExpanded:n,findUiElement:r,getQueryRoots:o,isSettingsOpenRef:i}){const[a,s]=z(false),l=P(null),c=P(null),d=P(false),u=P(false),h=P(false),g=P(false),p=P(e),m=P(t);_(()=>{p.current=e,m.current=t;},[e,t]);const f=A(()=>{l.current&&(clearTimeout(l.current),l.current=null);},[]),b=A(()=>{c.current&&(clearTimeout(c.current),c.current=null);},[]),y=A(()=>{s(true);},[]),v=A(()=>{s(false);},[]),w=A(()=>Ja(o()),[o]),x=A(()=>{if(!p.current||"edge-snap"!==m.current)return;if(i.current||d.current||u.current)return;if(w())return;const e=r(".gh-main-panel");e&&s(e.matches(":hover"));},[r,w,i]),k=A((e=0)=>{f(),l.current=setTimeout(()=>{l.current=null,x();},e);},[f,x]),S=A(()=>{y(),b(),c.current=setTimeout(()=>{x(),c.current=null;},3e3);},[b,y,x]),C=A((e=true)=>{h.current=e;},[]),E=A(()=>{g.current=true;},[]),T=A(e=>{d.current=e;},[]),M=A(()=>{f(),b(),e&&"edge-snap"===t&&!a&&y();},[b,f,e,a,t,y]),I=A(()=>{f(),l.current=setTimeout(()=>{i.current||u.current||x();},200);},[f,i,x]);return _(()=>()=>{f(),b();},[b,f]),_(()=>{if(!e||"edge-snap"!==t)return;const n=()=>w();let r=n();const i=new MutationObserver(()=>{const e=n();e&&!r?(y(),f()):!e&&r&&k(500),r=e;});for(const e of o())i.observe(e,{childList:true,subtree:e!==document.body});return h.current?h.current=false:n()&&y(),()=>{i.disconnect(),h.current=false;}},[f,e,o,w,t,k,y]),_(()=>{if(!e||"edge-snap"!==t)return;const n=o().filter(e=>e instanceof ShadowRoot);if(0===n.length)return;const r=e=>{const t=Qv(e);t&&Xa(t)&&(t.closest(".settings-modal-overlay, .settings-modal")||(u.current=true,y(),f()));},a=e=>{const t=Qv(e);t&&Xa(t)&&(t.closest(".settings-modal-overlay, .settings-modal")||(u.current=false,f(),l.current=setTimeout(()=>{u.current||i.current||d.current||x();},300)));},s=e=>{if("Escape"!==e.key)return;const t=(e=>e.composedPath().find(e=>e instanceof HTMLInputElement&&Array.from(Gv).some(t=>e.classList.contains(t)))??null)(e);t&&(e.preventDefault(),e.stopImmediatePropagation(),u.current=false,t.blur(),window.setTimeout(x,0));};return n.forEach(e=>{e.addEventListener("focusin",r,true),e.addEventListener("focusout",a,true),e.addEventListener("keydown",s,true);}),()=>{n.forEach(e=>{e.removeEventListener("focusin",r,true),e.removeEventListener("focusout",a,true),e.removeEventListener("keydown",s,true);});}},[f,e,o,i,t,y,x]),_(()=>{g.current&&n&&e&&"edge-snap"===t&&(g.current=false,k(1500));},[e,n,t,k]),{isEdgePeeking:a,showEdgePeek:y,hideEdgePeek:v,syncEdgePeekVisibility:x,scheduleEdgePeekSync:k,showEdgePeekFromShortcut:S,markSuppressOverlayInit:C,markSyncAfterOpen:E,handlePanelMouseEnter:M,handlePanelMouseLeave:I,handleInteractionChange:T}}class Kv{handlers=new Map;settings=null;isMac=lr();isListening=false;processedEvents=new WeakSet;updateSettings(e){this.settings=ar(e)||null;}register(e,t){this.handlers.set(e,t);}registerAll(e){for(const[t,n]of Object.entries(e))n&&this.handlers.set(t,n);}unregister(e){this.handlers.delete(e);}clearAll(){this.handlers.clear();}startListening(){this.isListening||(window.addEventListener("keydown",this.handleKeyDown,true),document.addEventListener("keydown",this.handleKeyDown,true),this.isListening=true);}stopListening(){this.isListening&&(window.removeEventListener("keydown",this.handleKeyDown,true),document.removeEventListener("keydown",this.handleKeyDown,true),this.isListening=false);}shouldIgnoreEvent(e){const t=e.target;if(!(t&&t instanceof Element))return false;return !("INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName&&!t.isContentEditable&&"true"!==t.getAttribute("contenteditable")&&!t.classList.contains("ProseMirror")||e.ctrlKey||e.metaKey||e.altKey)}matchesBinding(e,t){const n=ir(t);if(!n)return false;const r=or(e.key,e.code).toLowerCase(),o=n.key.toLowerCase();let i=r===o||"arrowup"===o&&"arrowup"===r||"arrowdown"===o&&"arrowdown"===r||"arrowleft"===o&&"arrowleft"===r||"arrowright"===o&&"arrowright"===r;if(!i&&n.shift&&/^[0-9]$/.test(o)&&e.code===`Digit${o}`&&(i=true),!i)return false;const a=!!n.alt===e.altKey,s=!!n.shift===e.shiftKey;let l;if(this.isMac){l=!!n.ctrl===e.metaKey&&!e.ctrlKey;}else l=!!n.ctrl===e.ctrlKey;return a&&s&&l}handleKeyDown=e=>{if(this.processedEvents.has(e))return;if(this.processedEvents.add(e),false===e.isTrusted)return;if(!this.settings?.enabled)return;if(!this.isMac&&e.getModifierState("AltGraph"))return;if(this.shouldIgnoreEvent(e))return;const t={...er,...this.settings.keybindings};for(const[n,r]of Object.entries(t))if(null!==r&&this.matchesBinding(e,r)){const t=this.handlers.get(n);if(t)return e.preventDefault(),e.stopPropagation(),void t()}};trigger(e){const t=this.handlers.get(e);t&&t();}destroy(){this.stopListening(),this.clearAll();}}let Zv=null;let Yv=null;const Jv=new Set,Xv=()=>Yv,ew=e=>{Yv=e,Jv.forEach(e=>e());},tw=e=>(Jv.add(e),()=>Jv.delete(e)),nw=()=>Yv;function rw(e,t){return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(t).flexDirection}function ow(e,t){return t?Math.min(0,e.clientHeight-e.scrollHeight):0}function iw(e,t){return t?0:e.scrollHeight}function aw(){const e=(window.unsafeWindow?window.unsafeWindow:window).document.querySelectorAll("iframe");for(const t of e)try{const e=t.contentDocument||t.contentWindow?.document;if(e){const t=e.querySelector('flt-semantics[style*="overflow-y: scroll"]');if(t&&t.scrollHeight>t.clientHeight)return t}}catch{}return null}function sw(e,t){{const n=aw();if(!n)return Promise.resolve({success:false,reason:"no_flutter_container"});let r;switch(e){case "scrollToTop":n.scrollTop=0,r={success:true,scrollTop:n.scrollTop};break;case "scrollToBottom":n.scrollTop=n.scrollHeight,r={success:true,scrollTop:n.scrollTop};break;case "scrollTo":"number"==typeof t&&(n.scrollTop=t),r={success:true,scrollTop:n.scrollTop};break;case "getScrollInfo":r={success:true,scrollTop:n.scrollTop,scrollHeight:n.scrollHeight};break;default:r={success:false};}return Promise.resolve(r)}}async function lw(e){const t=await sw("getScrollInfo");if(t.success){const e=t.scrollTop||0,n=t.scrollHeight||0;return await sw("scrollToTop"),{container:gw(),previousScrollTop:e,scrollHeight:n}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=n.scrollHeight,o=rw(e,n);return n.scrollTo({top:ow(n,o),behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t,scrollHeight:r}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop,scrollHeight:r.scrollHeight}}async function cw(e){const t=await sw("getScrollInfo");if(t.success){const e=t.scrollTop||0;return await sw("scrollToBottom"),{container:gw(),previousScrollTop:e}}const n=e?.getScrollContainer();if(n&&n.scrollHeight>n.clientHeight){const t=n.scrollTop,r=rw(e,n);return n.scrollTo({top:iw(n,r),behavior:"instant",__bypassLock:true}),{container:n,previousScrollTop:t}}const r=document.documentElement;return {container:r,previousScrollTop:r.scrollTop}}async function dw(e,t){const n=await sw("scrollTo",t);if(n.success)return uw(n.scrollTop||0),{success:true,currentScrollTop:n.scrollTop||0};const r=e?.getScrollContainer();return r&&r.scrollHeight>r.clientHeight?(r.scrollTo({top:t,behavior:"instant",__bypassLock:true}),uw(r.scrollTop),{success:true,currentScrollTop:r.scrollTop}):(document.documentElement.scrollTo({top:t,behavior:"instant",__bypassLock:true}),uw(document.documentElement.scrollTop),{success:true,currentScrollTop:document.documentElement.scrollTop})}function uw(e){ void 0!==document.documentElement.dataset.ophelPositionLock&&(document.documentElement.dataset.ophelPositionLock=String(e));}async function hw(e){const t=await sw("getScrollInfo");if(t.success)return {scrollTop:t.scrollTop||0,scrollHeight:t.scrollHeight||0,clientHeight:0,isFlutterMode:true};const n=e?.getScrollContainer();return n&&n.scrollHeight>n.clientHeight?{scrollTop:n.scrollTop,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight,isFlutterMode:false}:{scrollTop:document.documentElement.scrollTop,scrollHeight:document.documentElement.scrollHeight,clientHeight:document.documentElement.clientHeight,isFlutterMode:false}}function gw(){const e=document.createElement("div");return Object.defineProperty(e,"__isFlutterProxy",{value:true}),e}function pw(e){return true===e.__isFlutterProxy}const mw=1200,fw=2,bw=10,yw=50;function vw(e,t){return "doubao"===e?.getSiteId()&&"undefined"!=typeof window&&"column-reverse"===window.getComputedStyle(t).flexDirection?Math.min(0,t.clientHeight-t.scrollHeight):0}async function ww(e){const{adapter:t,targetHeight:n,loadAll:r=false,onProgress:o,signal:i,allowShortCircuit:a=false}=e;let{previousScrollTop:s,container:l}=await lw(t);if(pw(l)){return {success:true,finalHeight:(await hw(t)).scrollHeight,heightAdded:0,previousScrollTop:s,isFlutterMode:true,silent:true}}let c=l.scrollHeight,d=c,u=0,h=0;for(;;){if(i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(h++,h>=yw)return {success:true,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(l.scrollTop=vw(t,l),l.dispatchEvent(new WheelEvent("wheel",{deltaY:-100,bubbles:true})),await xw(mw),i?.aborted)return {success:false,finalHeight:l.scrollHeight,heightAdded:l.scrollHeight-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(t&&("HTML"===l.tagName||"BODY"===l.tagName)){const e=t.getScrollContainer();e&&e!==l&&"HTML"!==e.tagName&&"BODY"!==e.tagName&&(l=e,c=l.scrollHeight,d=l.scrollHeight,l.scrollTop=vw(t,l));}const e=l.scrollHeight;if(void 0!==n&&e>=n)return {success:true,finalHeight:e,heightAdded:e-c,previousScrollTop:s,isFlutterMode:false,silent:false};if(e>d)d=e,u=0,o?.(`${Math.round(e/1e3)}k`);else {u++;const t=l.scrollHeight>l.clientHeight+100,n=1===h&&e===c;if(n&&a)return {success:true,finalHeight:e,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(n&&t)return {success:true,finalHeight:e,heightAdded:0,previousScrollTop:s,isFlutterMode:false,silent:true};if(u>=(t?fw:bw))return {success:true,finalHeight:e,heightAdded:e-c,previousScrollTop:s,isFlutterMode:false,silent:false}}}}function xw(e){return new Promise(t=>setTimeout(t,e))}function kw(e,t,n){if(!t)return;const r=t.getSessionId(),o=e.getConversations();if(0===o.length)return void Li(se("noConversations"));const i=[...o].sort((e,t)=>(t.updatedAt||0)-(e.updatedAt||0)),a=i.findIndex(e=>e.id===r);let s;s=-1===a?0:"prev"===n?a>0?a-1:i.length-1:a(Zv||(Zv=new Kv),Zv),[]),f=A(async()=>{if(!t)return;const e=await hw(t);ew(e.scrollTop),await ww({adapter:t,loadAll:true,allowShortCircuit:true}),await lw(t),Li(se("scrolledToTop"));},[t]),b=A(async()=>{if(!t)return;const e=await hw(t);ew(e.scrollTop),await cw(t),Li(se("scrolledToBottom"));},[t]),y=A(async()=>{if(!t)return;const e=Xv();if(null===e)return void Li(se("noAnchor"));const n=(await hw(t)).scrollTop;await dw(t,e),ew(n);},[t]),v=A(()=>{n&&(n.refresh(),Li(se("outlineRefreshed")));},[n]),w=A(()=>{if(!n)return;n.getState().isAllExpanded?n.collapseAll():n.expandAll();},[n]),x=A(e=>{n?.setLevel(e);},[n]),k=A(()=>{n?.toggleGroupMode();},[n]),S=A(()=>{n?.toggleBookmarkMode();},[n]),C=A(()=>{n?.setShowUserQueries(true),n?.setLevel(0);},[n]),E=P(null),T=A(async e=>{if(!n)return;const t=n.getState().tree;if(!t||0===t.length)return;const r=e=>{const t=[];for(const n of e)t.push(n),n.children&&n.children.length>0&&!n.collapsed&&t.push(...r(n.children));return t},o=r(t);if(0===o.length)return;let i,a=-1;if(null!==E.current){const e=o.findIndex(e=>e.index===E.current);if(-1!==e){const t=o[e];let r=t.element;if(r&&r.isConnected||(r=await n.resolveOutlineTarget(t,t.queryIndex)),r&&r.isConnected){const t=r.getBoundingClientRect(),n=window.innerHeight;Math.abs(t.top-n/2)<2*n&&(a=e);}}}if(-1===a){const e=n.getScrollContainer();if(e){const t=n.findVisibleItemIndex(e.scrollTop,e.clientHeight);null!==t&&(a=o.findIndex(e=>e.index===t));}}i=-1===a?"prev"===e?o.length-1:0:"prev"===e?Math.max(0,a-1):Math.min(o.length-1,a+1);const s=o[i];if(s){E.current=s.index,n.revealNode(s.index);let e=s.element;if(e&&e.isConnected||(e=await n.resolveOutlineTarget(s,s.queryIndex),e&&(s.element=e)),e&&e.isConnected){e.scrollIntoView({behavior:"smooth",block:"start"});Li(s.text?.replace(/\s+/g," ").trim()||se("locatingOutline"),1e3,{className:"gh-toast--outline-nav",maxWidth:360});}}},[n]),M=A(()=>T("prev"),[T]),I=A(()=>T("next"),[T]),L=A(()=>{Li(se("syncingConversations")),window.dispatchEvent(new CustomEvent("ophel:refreshConversations"));},[]),N=A(()=>{s();},[s]),D=A(()=>{l?.();},[l]),R=A(e=>{d?u&&h&&h():i(),window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:e}}));},[d,i,u,h]),z=A(()=>R(0),[R]),B=A(()=>R(1),[R]),O=A(()=>R(2),[R]),F=A(()=>{if(!e?.features?.outline?.enabled)return void Li(se("outlineDisabled"));!d?i():u&&h&&h(),window.__ophelPendingLocateOutline=true,window.dispatchEvent(new CustomEvent("ophel:locateOutline")),Li(se("locatingOutline"));},[e,d,u,i,h]),$=A(()=>{if(!e?.features?.outline?.enabled)return void Li(se("outlineDisabled"));!d?i():u&&h&&h(),window.__ophelPendingSearchOutline=true,setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:searchOutline"));},50);},[e,d,u,i,h]),U=A(()=>{if(!e?.features?.conversations?.enabled)return void Li(se("conversationsDisabled"));if(t?.isSharePage()||t?.isNewConversation())return void Li(se("noConversationToLocate"));!d?i():u&&h&&h(),window.__ophelPendingLocateConversation=true,window.dispatchEvent(new CustomEvent("ophel:locateConversation")),Li(se("locatingConversation"));},[t,e,d,u,i,h]),j=A(()=>{if(t?.startNewConversation())return;const e=lr(),n=new KeyboardEvent("keydown",{key:"o",code:"KeyO",ctrlKey:!e,metaKey:e,shiftKey:true,bubbles:true});document.dispatchEvent(n);},[t]),H=A(async()=>{if(!o||!t)return;const e=t.getSessionId();if(e)try{await o.exportConversation(e,"markdown")||Li(se("exportFailed"));}catch(n){console.error("Export failed:",n),Li(se("exportFailed"));}else Li(se("exportNeedOpenFirst"));},[o,t]),W=A(async()=>{if(!t)return;const e=t.getLatestReplyText();if(e)try{await navigator.clipboard.writeText(e),Li(se("replyCopied"));}catch{Li(se("copyFailed"));}else Li(se("noReplyToCopy"));},[t]),G=A(()=>{g?g():Li(se("scrollLockToggled"));},[g]),Q=A(()=>{if(p)p();else {const{settings:e,updateNestedSetting:t}=Ai.getState();t("panel","panelMode","edge-snap"===(e?.panel?.panelMode??"edge-snap")?"floating":"edge-snap");}},[p]),V=A(()=>{if(!t)return;const e=t.getSiteId(),n=!ri(Ai.getState().settings,e).enabled;Ai.getState().updateDeepSetting("layout","zenMode",e,{enabled:n}),Li(se(n?"zenModeEnabledToast":"zenModeDisabledToast"));},[t]),K=A(()=>{if(!t)return;const e=t.findTextarea();e?(e.focus(),Li(se("inputFocused"))):Li(se("noTextarea"));},[t]),Z=A(()=>{if(!t)return;if(t.stopGeneration())return void Li(se("generationStopped"));const e=['[data-testid="stop-button"]','button[aria-label*="Stop"]','button[aria-label*="停止"]',".stop-button",'md-icon-button[aria-label*="Stop"]'];for(const t of e){const e=document.querySelector(t);if(e&&null!==e.offsetParent)return e.click(),void Li(se("generationStopped"))}Li(se("notGenerating"));},[t]),Y=A(()=>{o&&kw(o,t,"prev");},[o,t]),J=A(()=>{o&&kw(o,t,"next");},[o,t]),X=A(async()=>{const e=t?.getLastCodeBlockText?.()||"";if(e.trim()){try{await navigator.clipboard.writeText(e),Li(se("codeBlockCopied"));}catch{Li(se("copyFailed"));}return}const n=Array.from(document.querySelectorAll("pre code, pre, pre.code-block, .code-block code")).filter(e=>!e.closest(".gh-root, .gh-user-query-markdown, .gh-markdown-preview"));if(0===n.length)return void Li(se("noCodeBlock"));const r=n[n.length-1].cloneNode(true);r.querySelectorAll('button, [role="button"], svg, [aria-hidden="true"]').forEach(e=>e.remove());const o=(r.textContent||"").replace(/\r\n/g,"\n").replace(/\n+$/,"");if(o.trim())try{await navigator.clipboard.writeText(o),Li(se("codeBlockCopied"));}catch{Li(se("copyFailed"));}else Li(se("noCodeBlock"));},[t]),ee=A(()=>{c?c():(N(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"shortcuts"}}));},100));},[c,N]),te=A(()=>{if(!t)return;t.clickModelSelector()||Li(se("modelSelectorNotFound"));},[t]),ne=A(()=>{window.dispatchEvent(new CustomEvent("ophel:togglePromptQueue"));},[]),re=A((e,t)=>{N(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:e,subTab:t}}));},100);},[N]),oe=A(()=>re("siteSettings","claude"),[re]),ie=A(()=>re("siteSettings","gemini"),[re]),ae=A(()=>re("appearance"),[re]),le=A(()=>re("siteSettings","modelLock"),[re]),ce=A(async()=>{if(location.hostname.includes("claude.ai")||location.hostname.includes("claude.com"))try{const{platform:e}=await r(async()=>{const{platform:e}=await Promise.resolve().then(()=>Ri);return {platform:e}},void 0),t=await e.switchNextClaudeKey();if(t.success)Li(se("claudeKeySwitched")+`: ${t.keyName}`,2e3);else if("claudeOnlyOneKey"===t.error)Li(se("claudeOnlyOneKeyTip"),2e3);else if("noClaudeKeys"===t.error)Li(se("noClaudeKeys"),2e3);else {const e=se(t.error);Li(e!==t.error?e:t.error||se("operationFailed"),2e3);}}catch{Li(se("operationFailed"),2e3);}else Li(se("claudeShortcutOnlyOnSite"),2e3);},[]);return _(()=>{const e=()=>{if("visible"===document.visibilityState&&!document.hasFocus())try{window.focus();}catch{}},t=window.setTimeout(e,150);return window.addEventListener("pageshow",e),()=>{window.clearTimeout(t),window.removeEventListener("pageshow",e);}},[]),_(()=>{m.updateSettings(e?.shortcuts);},[m,e?.shortcuts]),_(()=>{const e={[an]:f,[sn]:b,[ln]:y,[cn]:i,[dn]:Q,[un]:a,[hn]:N,[gn]:z,[pn]:B,[mn]:O,[xn]:v,[Cn]:w,[An]:()=>x(1),[En]:()=>x(2),[Tn]:()=>x(3),[Mn]:()=>x(4),[_n]:()=>x(5),[In]:()=>x(6),[fn]:k,[yn]:S,[bn]:C,[kn]:M,[Sn]:I,[vn]:F,[wn]:$,[Ln]:j,[Nn]:L,[Dn]:U,[qn]:Y,[Rn]:J,[Pn]:H,[zn]:W,[Bn]:X,[On]:G,[Fn]:V,[$n]:K,[Un]:D,[jn]:Z,[Wn]:ee,[Gn]:te,[Qn]:oe,[Vn]:ce,[Kn]:ie,[Zn]:ae,[Yn]:le,[Hn]:ne};return m.registerAll(e),m.startListening(),()=>{m.stopListening(),m.clearAll();}},[m,f,b,y,i,a,Q,N,z,B,O,v,w,x,k,S,C,M,I,F,$,j,L,U,Y,J,H,W,X,G,V,K,D,Z,ee,oe,te,ce,ie,ae,le,ne]),m}const Cw="ophel",Aw="Ophel Atlas",Ew=GM_info?.script?.version??"1.0.0",Tw="undefined"!=typeof window&&window.__OPHEL_USERSCRIPT_ASSET_URLS__?.icon||"",Mw=({checked:e,onChange:t,disabled:n=false,size:r="md"})=>{const o="sm"===r?{w:32,h:18,thumb:14}:{w:36,h:20,thumb:16}; return Le("label",{style:{position:"relative",display:"inline-block",width:`${o.w}px`,height:`${o.h}px`,flexShrink:0},children:[ Ie("input",{type:"checkbox",checked:e,onChange:()=>t(!e),disabled:n,style:{opacity:0,width:0,height:0,position:"absolute"}}), Ie("span",{style:{position:"absolute",cursor:n?"not-allowed":"pointer",top:0,left:0,right:0,bottom:0,backgroundColor:e?"var(--gh-primary, #4285f4)":"var(--gh-input-border, #d1d5db)",borderRadius:`${o.h}px`,transition:"background-color 0.3s"},children:Ie("span",{style:{position:"absolute",height:`${o.thumb}px`,width:`${o.thumb}px`,left:e?o.w-o.thumb-2+"px":"2px",bottom:(o.h-o.thumb)/2+"px",backgroundColor:"var(--gh-bg, #ffffff)",borderRadius:"50%",transition:"left 0.3s"}})})]})};let _w=false;const Iw=({children:e,onClose:t,closeOnOverlayClick:n=true,closeOnEscape:r=true,dialogClassName:o,dialogStyle:i})=>{const a=P(null);_(()=>{(()=>{if(_w)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .gh-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 2147483647;\n }\n .gh-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 280px;\n max-width: 400px;\n box-shadow: var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3));\n }\n .gh-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 12px;\n }\n .gh-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-wrap;\n }\n .gh-dialog-buttons {\n display: flex;\n gap: 8px;\n justify-content: flex-end;\n }\n .gh-dialog-btn {\n padding: 8px 16px;\n border-radius: 6px;\n font-size: 14px;\n cursor: pointer;\n transition: all 0.2s;\n border: none;\n }\n .gh-dialog-btn-secondary {\n border: 1px solid var(--gh-border, #d1d5db);\n background: var(--gh-bg, white);\n color: var(--gh-text, #374151);\n }\n .gh-dialog-btn-secondary:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n .gh-dialog-btn-primary {\n background: var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%));\n color: white;\n }\n .gh-dialog-btn-danger {\n background: var(--gh-text-danger, #ef4444);\n color: white;\n }\n .gh-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-border, #d1d5db);\n border-radius: 6px;\n font-size: 14px;\n box-sizing: border-box;\n margin-bottom: 20px;\n background: var(--gh-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .gh-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n }\n",document.head.appendChild(e),_w=true;})();const e=e=>{r&&"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[r,t]),_(()=>{const e=a.current;if(e)return es(e,{capture:false})},[]);const s=Ie("div",{ref:a,className:"gh-dialog-overlay gh-interactive",...Za,onClick:n?t:void 0,children:Ie("div",{className:o?`gh-dialog ${o}`:"gh-dialog",style:i,onClick:e=>e.stopPropagation(),children:e})});return np(s,document.body)},Lw=({title:e,message:t,confirmText:n,cancelText:r,danger:o=false,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s,extraAction:l})=>Le(Iw,{onClose:s,closeOnOverlayClick:i,children:[ Ie("div",{className:"gh-dialog-title",children:e}), Ie("div",{className:"gh-dialog-message",children:t}), Le("div",{className:"gh-dialog-buttons",style:{justifyContent:l?"space-between":"flex-end"},children:[l&&Le("button",{className:"gh-dialog-btn",style:{background:"transparent",color:"var(--gh-primary, #4285f4)",padding:"8px 12px",textDecoration:"underline"},onClick:l.onClick,children:["↗ ",l.text]}), Le("div",{style:{display:"flex",gap:"8px"},children:[ Ie("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:r||se("cancel")}), Ie("button",{className:"gh-dialog-btn "+(o?"gh-dialog-btn-danger":"gh-dialog-btn-primary"),onClick:a,children:n||se("confirm")})]})]})]}),Nw=({title:e,defaultValue:t="",placeholder:n,confirmText:r,cancelText:o,closeOnOverlayClick:i=true,onConfirm:a,onCancel:s})=>{const[l,c]=z(t),d=P(null);_(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{a(l);}; return Le(Iw,{onClose:s,closeOnOverlayClick:i,children:[ Ie("div",{className:"gh-dialog-title",children:e}), Ie("input",{ref:d,type:"text",className:"gh-dialog-input",value:l,onChange:e=>c(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&u()}), Le("div",{className:"gh-dialog-buttons",children:[ Ie("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:s,children:o||se("cancel")}), Ie("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:u,children:r||se("confirm")})]})]})},Dw=({variant:e="secondary",size:t="md",style:n,children:r,...o})=>{const i="sm"===t?{padding:"4px 8px",fontSize:"12px"}:{padding:"8px 16px",fontSize:"14px"}; return Ie("button",{...o,style:{borderRadius:"6px",cursor:o.disabled?"not-allowed":"pointer",transition:"all 0.2s",fontWeight:500,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"4px",opacity:o.disabled?.5:1,...i,...{primary:{background:"var(--gh-brand-gradient, linear-gradient(135deg, #4285f4 0%, #34a853 100%))",color:"white",border:"none"},secondary:{background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",border:"1px solid var(--gh-input-border, #d1d5db)"},danger:{background:"var(--gh-text-danger, #ef4444)",color:"white",border:"none"},ghost:{background:"transparent",color:"var(--gh-text-secondary, #6b7280)",border:"none"}}[e],...n},children:r})},qw=({value:e,onChange:t,min:n,max:r,defaultValue:o,disabled:i=false,style:a,className:s="settings-input",step:l=1})=>{const[c,d]=z(e.toString()),u=P(false),h=P(null),g=P(null);_(()=>{u.current||d(e.toString());},[e]);const p=A(i=>{let a=parseInt(i);isNaN(a)&&(a=o??e??0),void 0!==n&&ar&&(a=r),d(a.toString()),a!==e&&t(a);},[n,r,o,e,t]),m=A(t=>{if(i)return;let n=parseInt(c);isNaN(n)&&(n=o??e??0);p((n+t).toString());},[c,o,e,i,p]);_(()=>()=>{h.current&&clearTimeout(h.current);},[]);const[f,b]=z(false); return Le("div",{className:s,onMouseEnter:()=>b(true),onMouseLeave:()=>b(false),style:{...a,position:"relative",display:"inline-flex",alignItems:"center"},children:[ Ie("input",{ref:g,type:"text",inputMode:"numeric",pattern:"[0-9]*",style:{width:"100%",paddingRight:"20px",height:"100%",border:"none",background:"transparent",outline:"none",color:"inherit",fontSize:"inherit",fontFamily:"inherit",paddingLeft:"8px",textAlign:"left"},value:c,disabled:i,onChange:e=>{const t=e.target.value.replace(/[^0-9-]/g,"");d(t);},onFocus:()=>{h.current&&(clearTimeout(h.current),h.current=null),u.current=true;},onBlur:()=>{h.current=setTimeout(()=>{document.activeElement!==g.current&&(u.current=false,p(c));},100);},onKeyDown:e=>{"Enter"===e.key?(p(c),g.current?.blur()):"ArrowUp"===e.key?(e.preventDefault(),m(l)):"ArrowDown"===e.key&&(e.preventDefault(),m(-l));}}),!i&&Le("div",{style:{position:"absolute",right:"2px",top:"2px",bottom:"2px",display:"flex",flexDirection:"column",width:"16px",background:"transparent",opacity:f?1:.2,transition:"opacity 0.2s ease",pointerEvents:f?"auto":"none"},children:[ Ie("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"3px 3px 0 0",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)",marginBottom:"1px"},children:Ie(_t,{size:8})}), Ie("button",{type:"button",tabIndex:-1,onClick:e=>{e.preventDefault(),m(-l);},style:{flex:1,border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"0 0 3px 3px",cursor:"pointer",padding:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--gh-text-secondary, #6b7280)"},children:Ie(It,{size:8})})]})]})},Rw=(e,t,n)=>Math.min(n,Math.max(t,e)),Pw=({value:e,onChange:t,onPreviewChange:n,onCancelPreview:r,min:o,max:i,step:a=1,unit:s,defaultValue:l,disabled:c=false,style:d,className:u="",formatValue:h,ariaLabel:g})=>{const p=Rw(Number.isFinite(e)?e:o,o,i),[m,f]=z(p),[b,y]=z(false),v=P(false),w=P(p),x=P(r);_(()=>{x.current=r;},[r]),_(()=>{w.current=m;},[m]),_(()=>()=>{v.current&&(v.current=false,x.current?.());},[]),_(()=>{b||(f(p),w.current=p);},[p,b]);const k=i===o?0:(m-o)/(i-o)*100,S=h?h(m):`${m}${s||""}`,C=void 0===l?void 0:Rw(l,o,i),E=void 0!==C&&m===C,T=A((e=w.current)=>{v.current&&!c&&(v.current=false,t(Rw(e,o,i)));},[c,i,o,t]);_(()=>{if(!b)return;const e=()=>{y(false),T();};return window.addEventListener("pointerup",e),window.addEventListener("mouseup",e),window.addEventListener("touchend",e),()=>{window.removeEventListener("pointerup",e),window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e);}},[T,b]); return Ie("div",{className:`settings-slider ${c?"disabled":""} ${u}`.trim(),style:{...d,"--slider-progress":`${k}%`},children:Le("div",{className:"settings-slider-main",children:[ Le("div",{className:"settings-slider-track",children:[ Ie("input",{type:"range",className:"settings-slider-input",min:o,max:i,step:a,value:m,onChange:e=>{const t=Rw(Number.parseFloat(e.target.value),o,i);f(t),w.current=t,v.current=true,n?.(t);},onPointerDown:()=>y(true),onMouseDown:()=>y(true),onTouchStart:()=>y(true),onBlur:()=>{y(false),T();},onKeyUp:e=>{["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(e.key)&&T();},disabled:c,"aria-label":g,"aria-valuemin":o,"aria-valuemax":i,"aria-valuenow":m,"aria-valuetext":S}), Le("div",{className:"settings-slider-boundary",children:[ Ie("span",{children:h?h(o):`${o}${s||""}`}), Ie("span",{children:h?h(i):`${i}${s||""}`})]})]}), Ie("span",{className:"settings-slider-value",children:S}),void 0!==C&&Ie("button",{type:"button",className:"settings-slider-reset",onClick:()=>{ void 0===C||c||(v.current=false,f(C),w.current=C,t(C));},disabled:c||E,title:se("restore"),"aria-label":se("restore"),children:Ie(St,{size:14})})]})})},zw=({options:e,value:t,onChange:n,placeholder:r,disabled:o=false,emptyText:i,maxMenuHeight:a=260,className:s,buttonClassName:l,menuClassName:c,optionClassName:d,ariaLabel:u,onOpenChange:h})=>{const[g,p]=z(false),[m,f]=z(-1),b=P(null),y=P(null),v=P([]),w=q(()=>e.findIndex(e=>e.value===t),[e,t]),x=w>=0?e[w]:null;_(()=>{h?.(g);},[g,h]),_(()=>{if(!g)return;const t=w>=0?w:e.findIndex(e=>!e.disabled);f(t);},[g,e,w]),_(()=>{if(!g||m<0)return;const e=v.current[m];e?.scrollIntoView({block:"nearest"});},[g,m]),_(()=>{if(!g)return;const e=e=>{const t=b.current;if(!t)return;const n=(e=>{const t=e.composedPath;return "function"==typeof t?t.call(e):[]})(e);if(n.length>0)return void(n.includes(t)||p(false));const r=e.target;r&&!t.contains(r)&&p(false);},t=()=>{p(false);};return window.addEventListener("pointerdown",e,true),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,true),window.removeEventListener("blur",t);}},[g]);const k=e=>{p(false),e&&window.requestAnimationFrame(()=>{y.current?.focus({preventScroll:true});});},S=(t,n)=>{if(0===e.length)return -1;let r=t;for(let o=0;o=e.length&&(r=0),r<0&&(r=e.length-1),!e[r]?.disabled)return r;return -1},C=t=>{const r=e[t];r&&!r.disabled&&(n(r.value),k(true));}; return Le("div",{ref:b,className:s,style:{position:"relative",width:"100%"},children:[ Le("button",{ref:y,type:"button",className:l,disabled:o,"aria-label":u,"aria-haspopup":"listbox","aria-expanded":g,onClick:()=>!o&&p(e=>!e),onKeyDown:e=>{if(!o){if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!g)return void p(true);const t=S(m<0?w:m,"ArrowDown"===e.key?1:-1);return void(t>=0&&f(t))}if("Enter"===e.key||" "===e.key)return e.preventDefault(),void p(e=>!e);"Escape"===e.key&&g&&(e.preventDefault(),p(false));}},title:x?.title,style:{width:"100%",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"8px",textAlign:"left"},children:[ Ie("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:"8px"},children:x?.label||r}), Ie(It,{size:16,style:{flexShrink:0,transition:"transform 0.2s ease",transform:g?"rotate(180deg)":"rotate(0deg)"}})]}),g&&Ie("div",{role:"listbox",tabIndex:-1,className:c,...Za,onKeyDown:t=>{if("ArrowDown"===t.key){t.preventDefault();const e=S(m,1);return void(e>=0&&f(e))}if("ArrowUp"===t.key){t.preventDefault();const e=S(m,-1);return void(e>=0&&f(e))}if("Home"===t.key){t.preventDefault();const n=e.findIndex(e=>!e.disabled);return void(n>=0&&f(n))}if("End"===t.key){t.preventDefault();const n=[...e].reverse().findIndex(e=>!e.disabled);return void(n>=0&&f(e.length-n-1))}return "Enter"===t.key?(t.preventDefault(),void(m>=0&&C(m))):"Escape"===t.key?(t.preventDefault(),void k(true)):void("Tab"===t.key&&k(false))},style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,maxHeight:`${a}px`,overflowY:"auto",zIndex:100,borderRadius:"8px",border:"1px solid var(--gh-input-border, #d1d5db)",boxShadow:"var(--gh-shadow-md, 0 8px 16px rgba(0,0,0,0.12))",background:"var(--gh-bg, #ffffff)",padding:"4px"},children:0===e.length?Ie("div",{style:{padding:"8px 10px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"13px",textAlign:"left"},children:i||"No options"}):e.map((e,n)=>{const r=e.value===t,o=n===m; return Ie("button",{ref:e=>{v.current[n]=e;},type:"button",role:"option","aria-selected":r,className:d,disabled:e.disabled,title:e.title,onMouseEnter:()=>{e.disabled||f(n);},onClick:()=>C(n),style:{width:"100%",border:"none",borderRadius:"6px",padding:"7px 10px",textAlign:"left",background:r?"var(--gh-border-active, #3b82f6)":o?"var(--gh-hover, #f3f4f6)":"transparent",color:r?"#ffffff":"var(--gh-text, #1f2937)",cursor:e.disabled?"not-allowed":"pointer",display:"flex",alignItems:"center",gap:"8px",fontSize:"14px",lineHeight:1.4},children:e.label},e.value)})})]})};function Bw(e,t){if(!e)return null;const n=function(e){const t=e.filter(Boolean).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return 0===t.length?null:new RegExp(`(${t.join("|")})`,"g")}(t);if(!n)return e;const r=[];let o,i=0;for(;null!==(o=n.exec(e));)o.index>i&&r.push(e.slice(i,o.index)),r.push( Ie("span",{className:"placeholder-input-chip",children:o[0]},`${o[0]}-${o.index}`)),i=n.lastIndex;return i{const s=P(null),l=P(null),c=P(e),d=P({start:e.length,end:e.length});_(()=>{c.current=e;const t=e.length;d.current={start:Math.min(d.current.start,t),end:Math.min(d.current.end,t)};},[e]);const u=A(()=>{const e=s.current;if(!e)return;const t=e.selectionStart??c.current.length,n=e.selectionEnd??t;d.current={start:t,end:n};},[]),h=A(e=>{const t=s.current;t&&(t.focus(),t.setSelectionRange(e,e),d.current={start:e,end:e});},[]),g=A(()=>{const e=s.current,t=l.current;e&&t&&(t.style.transform=`translateX(-${e.scrollLeft}px)`);},[]);_(()=>{g();},[g,e]);const p=A(e=>{c.current=e.target.value,t(e.target.value),u(),requestAnimationFrame(g);},[t,u,g]),m=A(e=>{if(a)return;const n=s.current,r=c.current,o=n?.selectionStart??d.current.start,i=n?.selectionEnd??d.current.end,l=`${r.slice(0,o)}${e}${r.slice(i)}`,u=o+e.length;c.current=l,t(l),requestAnimationFrame(()=>{h(u),g();});},[a,t,h,g]),f=["placeholder-input-native",o].filter(Boolean).join(" "); return Le("div",{className:"placeholder-input-field "+(a?"placeholder-input-disabled":""),style:i,children:[ Le("div",{className:"placeholder-input-surface",children:[ Ie("div",{className:"placeholder-input-mirror","aria-hidden":"true",children:Ie("span",{ref:l,className:"placeholder-input-mirror-scroll",children:Bw(e,n)})}), Ie("input",{ref:s,type:"text",dir:"ltr",className:f,value:e,onChange:p,onSelect:u,onClick:u,onKeyUp:u,onScroll:g,placeholder:r,disabled:a})]}), Ie("div",{className:"placeholder-input-list","aria-label":"Title format placeholders",children:n.map(e=>Ie("button",{type:"button",className:"placeholder-input-button",disabled:a,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:e,children:e},e))})]})};let Fw=false;const $w=e=>{if("inbox"===e.id)return (()=>{const e=se("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},Uw=({children:e,onClose:t})=>{_(()=>{(()=>{if(Fw)return;const e=document.createElement("style");e.id="gh-dialog-styles",e.textContent="\n .conversations-dialog-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: var(--gh-overlay-bg, rgba(0,0,0,0.5));\n z-index: 1000003;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .conversations-dialog {\n background: var(--gh-bg, white);\n border-radius: 12px;\n padding: 20px;\n min-width: 320px;\n max-width: min(480px, calc(100vw - 40px));\n box-shadow: var(--gh-shadow-lg, 0 10px 40px rgba(0,0,0,0.2));\n }\n .conversations-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--gh-text, #1f2937);\n margin-bottom: 16px;\n }\n .conversations-dialog-message {\n font-size: 14px;\n color: var(--gh-text-secondary, #4b5563);\n margin-bottom: 20px;\n line-height: 1.5;\n white-space: pre-line;\n word-break: break-word;\n overflow-wrap: break-word;\n }\n .conversations-dialog-section {\n margin-bottom: 16px;\n }\n .conversations-dialog-section label {\n display: block;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n margin-bottom: 8px;\n }\n .conversations-dialog-input {\n width: 100%;\n padding: 10px 12px;\n border: 1px solid var(--gh-input-border, #d1d5db);\n border-radius: 8px;\n font-size: 14px;\n box-sizing: border-box;\n background: var(--gh-input-bg, #ffffff);\n color: var(--gh-text, #1f2937);\n }\n .conversations-dialog-input:focus {\n outline: none;\n border-color: var(--gh-input-focus-border, #4285f4);\n box-shadow: var(--gh-input-focus-shadow, 0 0 0 2px rgba(66,133,244,0.1));\n }\n .conversations-dialog-buttons {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n margin-top: 20px;\n }\n .emoji-grid-hidden-scrollbar::-webkit-scrollbar {\n display: none;\n width: 0;\n height: 0;\n }\n @keyframes gh-highlight-fade {\n 0% { background-color: var(--gh-highlight-pulse, rgba(59, 130, 246, 0.3)); }\n 100% { background-color: transparent; }\n }\n .conversations-folder-select-highlight {\n animation: gh-highlight-fade 2s ease-out;\n }\n",document.head.appendChild(e),Fw=true;})();const e=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t]);const n=Ie("div",{className:"conversations-dialog-overlay",...Za,onClick:t,children:Ie("div",{className:"conversations-dialog",onClick:e=>e.stopPropagation(),children:e})});return np(n,document.body)},jw=({title:e,message:t,confirmText:n,cancelText:r,danger:o,onConfirm:i,onCancel:a})=>Le(Uw,{onClose:a,children:[ Ie("div",{className:"conversations-dialog-title",children:e}), Ie("div",{className:"conversations-dialog-message",children:t}), Le("div",{className:"conversations-dialog-buttons",children:[ Ie(Dw,{variant:"secondary",onClick:a,children:r||se("cancel")}), Ie(Dw,{variant:o?"danger":"primary",onClick:i,children:n||se("confirm")})]})]}),Hw=({folder:e,onConfirm:t,onCancel:n})=>{const r=e?.icon||"📁",[o,i]=z(e?.name.replace(e.icon,"").trim()||""),[a,s]=z(r),[l,c]=z(Wr.includes(r)?r:null),d=P(null);_(()=>{d.current?.focus(),d.current?.select();},[]);const u=()=>{const e=o.trim();e&&t(e,a);}; return Le(Uw,{onClose:n,children:[ Ie("div",{className:"conversations-dialog-title",children:se(e?"conversationsRename":"conversationsAddFolder")}), Le("div",{className:"conversations-dialog-section",children:[ Ie("label",{children:se("conversationsIcon")}), Le("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"4px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"4px",border:"1px solid var(--gh-border, #e5e7eb)",marginBottom:"8px"},children:[ Ie("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:se("conversationsCustomIcon")}), Ie("input",{type:"text",value:a,onChange:e=>{let t=e.target.value;const n=/[^\p{Extended_Pictographic}\u200d\ufe0f]/gu;t&&n.test(t)&&(t=t.replace(n,"")),s(t),t&&!Wr.includes(t)?c(null):Wr.includes(t)&&c(t);},maxLength:4,placeholder:"☺",style:{width:"60px",textAlign:"center",border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",padding:"2px",fontSize:"16px",background:"var(--gh-input-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), Ie("div",{style:{display:"grid",gridTemplateColumns:"repeat(8, 1fr)",gap:"4px",maxHeight:"120px",overflowY:"auto",padding:"2px",scrollbarWidth:"none",msOverflowStyle:"none"},className:"emoji-grid-hidden-scrollbar",children:Wr.map(e=>Ie("button",{type:"button",onClick:()=>(e=>{c(e),s(e);})(e),style:{width:"24px",height:"24px",padding:0,display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:l===e?"#dbeafe":"transparent",cursor:"pointer",borderRadius:"4px",fontSize:"16px",transition:"background 0.15s"},onMouseEnter:t=>{l!==e&&(t.currentTarget.style.background="var(--gh-hover, #f3f4f6)");},onMouseLeave:t=>{l!==e&&(t.currentTarget.style.background="transparent");},children:e},e))})]}), Le("div",{className:"conversations-dialog-section",children:[ Ie("label",{children:se("conversationsFolderName")}), Ie("input",{ref:d,type:"text",className:"conversations-dialog-input",value:o,onChange:e=>i(e.target.value),placeholder:se("conversationsFolderNamePlaceholder"),onKeyDown:e=>"Enter"===e.key&&u()})]}), Le("div",{className:"conversations-dialog-buttons",children:[ Ie(Dw,{variant:"secondary",onClick:n,children:se("cancel")}), Ie(Dw,{variant:"primary",onClick:u,children:se("confirm")})]})]})},Ww=({title:e,currentValue:t,placeholder:n,onConfirm:r,onCancel:o})=>{const[i,a]=z(t),s=P(null);_(()=>{s.current?.focus(),s.current?.select();},[]);const l=()=>{const e=i.trim();e&&e!==t?r(e):o();}; return Le(Uw,{onClose:o,children:[ Ie("div",{className:"conversations-dialog-title",children:e}), Ie("div",{className:"conversations-dialog-section",children:Ie("input",{ref:s,type:"text",className:"conversations-dialog-input",value:i,onChange:e=>a(e.target.value),placeholder:n,onKeyDown:e=>"Enter"===e.key&&l()})}), Le("div",{className:"conversations-dialog-buttons",children:[ Ie(Dw,{variant:"secondary",onClick:o,children:se("cancel")}), Ie(Dw,{variant:"primary",onClick:l,children:se("confirm")})]})]})},Gw=({folders:e,excludeFolderId:t,activeFolderId:n,title:r,onSelect:o,onCancel:i,onCreateFolder:a})=>{const[s,l]=z(""),c=P(null);_(()=>{c.current?.focus();},[]),_(()=>{n&&setTimeout(()=>{const e=document.getElementById(`folder-select-${n}`);e&&(e.scrollIntoView({block:"center",behavior:"smooth"}),e.classList.add("conversations-folder-select-highlight"));},150);},[n]);const d=e.filter(e=>e.id!==t&&(!s||$w(e).toLowerCase().includes(s.toLowerCase()))); return Le(Uw,{onClose:i,children:[ Ie("div",{className:"conversations-dialog-title",children:r||se("conversationsMoveTo")}), Le("div",{style:{display:"flex",gap:"8px",marginBottom:"12px"},children:[ Ie("input",{ref:c,type:"text",className:"conversations-dialog-input",style:{flex:1},placeholder:se("conversationsSearchFolder"),value:s,onChange:e=>l(e.target.value)}),a&&Ie(Dw,{variant:"primary",style:{padding:"8px 12px"},onClick:()=>{i(),a();},title:se("conversationsAddFolder"),children:"+"})]}), Le("div",{className:"conversations-folder-select-list",children:[d.map(e=>Le("div",{id:`folder-select-${e.id}`,className:"conversations-folder-select-item",onClick:()=>o(e.id),children:[e.icon," ",$w(e)]},e.id)),0===d.length&&Ie("div",{style:{padding:"16px",textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)"},children:se("conversationsNoSearchResult")})]}), Ie("div",{className:"conversations-dialog-buttons",children:Ie(Dw,{variant:"secondary",onClick:i,children:se("cancel")})})]})},Qw=({tags:e,conv:t,onCancel:n,onCreateTag:r,onUpdateTag:o,onDeleteTag:i,onSetConversationTags:a,onRefresh:s})=>{const[l,c]=z(null),[d,u]=z(""),[h,g]=z(Gr[0]),[p,m]=z(Gr[0]),[f,b]=z(false),[y,v]=z(false),[w,x]=z(false),[k,S]=z(null),[C,A]=z(new Set(t?.tagIds||[])),E=P(null),T=P(null);_(()=>{E.current?.focus();},[]),_(()=>{A(new Set(t?.tagIds||[]));},[t?.id,t?.tagIds]);const M=(e,t="click")=>{let n=e.startsWith("#")?e:`#${e}`;g(n),"input"!==t&&(m(n),b(false));},I=async()=>{const e=d.trim();if(!e)return;v(true);let t=null;l?(t=await o(l,e,h),t&&(c(null),u(""))):(t=await r(e,h),t&&u("")),v(false),s();}; return Le(Uw,{onClose:n,children:[ Le("div",{className:"conversations-dialog-title",style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("span",{children:se("conversationsManageTags")}), Ie(up,{content:se("close"),children:Ie("span",{style:{cursor:"pointer",padding:"4px",fontSize:"20px",color:"var(--gh-text-secondary, #9ca3af)",lineHeight:1,width:"24px",height:"24px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px"},onClick:n,children:Ie(Re,{size:18})})})]}), Le("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",marginBottom:"16px",background:"var(--gh-bg-secondary, #fafafa)"},children:[ Le("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",fontWeight:500,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("span",{children:se(t?"conversationsSelectTag":"conversationsExistingTags")}), Le("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #9ca3af)"},children:[e.length," 个"]})]}), Ie("div",{style:{maxHeight:"320px",overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none"},children:0===e.length?Ie("div",{style:{padding:"24px 16px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)"},children:se("conversationsNoTags")}):e.map(e=>{const n=C.has(e.id),r=l===e.id; return Le("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 12px",borderBottom:"1px solid var(--gh-border, #f3f4f6)",cursor:t?"pointer":"default",background:r?"var(--gh-bg-warning-light, #fffbeb)":n?"var(--gh-folder-bg-default)":"transparent",transition:"background 0.15s"},onClick:()=>{t&&(async(e,n)=>{if(!t||!a)return;const r=new Set(C);n?r.add(e):r.delete(e),A(r),await a(t.id,Array.from(r)),s();})(e.id,!n);},onMouseEnter:e=>{r||n||(e.currentTarget.style.background="var(--gh-hover, #f9fafb)");},onMouseLeave:e=>{r||n||(e.currentTarget.style.background="transparent");},children:[ Le("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[t&&Ie("input",{type:"checkbox",checked:n,onChange:()=>{},onClick:e=>e.stopPropagation(),style:{cursor:"pointer",width:"16px",height:"16px",accentColor:e.color}}), Le("span",{style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"4px 10px",borderRadius:"4px",fontSize:"13px",color:"white",backgroundColor:e.color,fontWeight:n?500:400,boxShadow:n?"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.2))":"none"},children:[e.name,r&&Ie(zt,{size:10})]})]}), Le("div",{style:{display:"flex",gap:"2px"},children:[ Ie(up,{content:se("edit"),children:Ie("button",{style:{background:r?"#fed7aa":"transparent",border:"none",color:r?"#ea580c":"#9ca3af",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{t.stopPropagation(),(e=>{c(e.id),u(e.name),M(e.color),E.current?.focus();})(e);},onMouseEnter:e=>{r||(e.currentTarget.style.background="#e0f2fe",e.currentTarget.style.color="#0284c7");},onMouseLeave:e=>{r||(e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af");},children:Ie(zt,{size:14})})}), Ie(up,{content:se("delete"),children:Ie("button",{style:{background:"transparent",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",padding:"6px",fontSize:"14px",borderRadius:"4px",transition:"all 0.15s"},onClick:t=>{var n;t.stopPropagation(),n=e.id,S(n);},onMouseEnter:e=>{e.currentTarget.style.background="#fee2e2",e.currentTarget.style.color="#dc2626";},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="#9ca3af";},children:Ie(Re,{size:18})})})]})]},e.id)})})]}), Le("div",{style:{border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",background:l?"var(--gh-bg-warning-light, #fffbeb)":"var(--gh-bg, #ffffff)",transition:"background 0.2s"},children:[ Le("div",{style:{fontSize:"12px",color:l?"var(--gh-text-warning, #b45309)":"var(--gh-text-secondary, #6b7280)",fontWeight:500,marginBottom:"10px",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("span",{children:se(l?"conversationsEditTag":"conversationsNewTag")}),l&&Ie("button",{style:{background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"11px",padding:"2px 6px"},onClick:()=>{c(null),u(""),M(Gr[0]);},children:se("conversationsCancelEdit")})]}), Ie("input",{ref:E,type:"text",className:"conversations-dialog-input",placeholder:se("conversationsTagName"),value:d,onChange:e=>u(e.target.value),onKeyDown:e=>"Enter"===e.key&&I(),style:{marginBottom:"12px",borderColor:l?"#fbbf24":void 0}}), Le("div",{style:{marginBottom:"12px",position:"relative"},children:[ Le("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"8px 10px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",cursor:"pointer",background:"var(--gh-bg-secondary, #fafafa)",transition:"border-radius 0.15s, background-color 0.2s",userSelect:"none"},onClick:()=>x(!w),onMouseEnter:e=>e.currentTarget.style.backgroundColor="var(--gh-hover, #f3f4f6)",onMouseLeave:e=>e.currentTarget.style.backgroundColor="var(--gh-bg-secondary, #fafafa)",children:[ Ie("div",{style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:h,border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",flexShrink:0}}), Ie("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #666)",flex:1},children:se(w?"conversationsCollapseColor":"conversationsSelectColor")}), Ie(It,{size:16,color:"#9ca3af",style:{transition:"transform 0.2s",transform:w?"rotate(180deg)":"rotate(0deg)"}})]}),w&&Le("div",{style:{position:"absolute",top:"100%",left:0,right:0,marginTop:"4px",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"10px",background:"var(--gh-bg, #ffffff)",zIndex:10,boxShadow:"var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15))"},children:[ Ie("div",{style:{display:"grid",gridTemplateColumns:"repeat(10, 1fr)",gap:"6px",marginBottom:"12px"},children:Gr.map(e=>Ie(up,{content:e,children:Ie("div",{style:{width:"100%",aspectRatio:"1",borderRadius:"4px",backgroundColor:e,cursor:"pointer",border:h.toLowerCase()===e.toLowerCase()?"2px solid #333":"1px solid rgba(0,0,0,0.05)",transition:"transform 0.1s",boxSizing:"border-box"},onClick:()=>{M(e),x(false);},onMouseEnter:e=>e.currentTarget.style.transform="scale(1.15)",onMouseLeave:e=>e.currentTarget.style.transform="scale(1)"})},e))}), Le("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Le("div",{style:{position:"relative",width:"28px",height:"28px",borderRadius:"50%",overflow:"hidden",cursor:"pointer",boxShadow:"var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))",border:Gr.includes(h.toUpperCase())?"2px solid transparent":"2px solid #666",flexShrink:0},children:[ Ie("div",{style:{width:"100%",height:"100%",background:Gr.includes(h.toUpperCase())?"conic-gradient(from 180deg, red, yellow, lime, aqua, blue, magenta, red)":h}}), Ie("input",{ref:T,type:"color",value:h,onChange:e=>{M(e.target.value,"picker"),x(false);},style:{position:"absolute",left:"-50%",top:"-50%",width:"200%",height:"200%",opacity:0,cursor:"pointer"}})]}), Le("div",{style:{display:"flex",alignItems:"center",flex:1,background:"var(--gh-bg-secondary, #f3f4f6)",border:"1px solid "+(f?"#ef4444":"var(--gh-border, #e5e7eb)"),borderRadius:"6px",padding:"4px 8px",height:"30px",boxSizing:"border-box"},children:[ Ie("span",{style:{fontSize:"11px",color:"var(--gh-text-secondary, #6b7280)",marginRight:"6px",fontFamily:"monospace",fontWeight:600},children:"HEX"}), Ie("input",{type:"text",value:p,onChange:e=>(e=>{if(m(e),/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(e)){b(false);let t=e;4===e.length&&(t=`#${e[1]}${e[1]}${e[2]}${e[2]}${e[3]}${e[3]}`),M(t,"input");}else b(true);})(e.target.value),onBlur:()=>{f&&(m(h),b(false));},style:{border:"none",background:"transparent",outline:"none",fontSize:"13px",fontFamily:"monospace",width:"100%",color:"var(--gh-text, #374151)",textTransform:"uppercase"}})]})]})]})]}), Ie(Dw,{variant:"primary",style:{width:"100%",...l&&{background:"var(--gh-warning-gradient, linear-gradient(135deg, #f59e0b 0%, #d97706 100%))"}},disabled:!d.trim()||y,onClick:I,children:se(l?"conversationsUpdateTag":"conversationsNewTag")})]}),k&&Ie(jw,{title:se("conversationsDeleteTag"),message:se("confirmDelete"),confirmText:se("delete"),cancelText:se("cancel"),danger:true,onConfirm:async()=>{k&&(await i(k),S(null),s());},onCancel:()=>S(null)})]})},Vw=()=>({url:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",icon:Ie(Rt,{size:14}),label:se("reviewBtn")}),Kw=()=>{const{settings:e,setSettings:t}=Ai();if(!Ei()||!e||e.hasAgreedToTerms)return null; return Le("div",{className:"disclaimer-modal-overlay",children:[ Le("div",{className:"disclaimer-modal",children:[ Le("div",{className:"disclaimer-header",children:[ Ie("img",{src:Tw,alt:"Ophel",className:"disclaimer-icon-img"}), Le("div",{className:"disclaimer-slogan-container",children:[ Ie("span",{className:"sparkle","aria-hidden":"true",children:"✨"}), Ie("h2",{className:"disclaimer-title",children:se("welcomeSlogan")}), Ie("span",{className:"sparkle","aria-hidden":"true",children:"✨"})]})]}), Le("div",{className:"disclaimer-content",children:[ Le("div",{className:"disclaimer-section",children:[ Ie("p",{children:se("disclaimerText")}), Ie("p",{className:"disclaimer-warning",children:se("disclaimerWarning")})]}), Le("div",{className:"disclaimer-section privacy-section",children:[ Le("div",{className:"privacy-header",children:[ Ie(ht,{size:20,className:"privacy-icon"}), Ie("h3",{className:"privacy-title",children:se("privacyTitle")})]}), Ie("p",{className:"privacy-content",children:se("privacyText")})]}), Le("div",{className:"disclaimer-section quote-section",children:[ Ie("p",{className:"disclaimer-quote-text",children:se("communityMotto")}), Le("div",{className:"action-row",children:[ Le("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"star-btn",children:[ Ie(ct,{size:18}), Ie("span",{children:se("giveStar")})]}), Le("a",{href:Vw().url,target:"_blank",rel:"noopener noreferrer",className:"star-btn review-btn",children:[Vw().icon, Ie("span",{children:Vw().label})]})]}), Le("div",{className:"secondary-links",children:[ Ie("a",{href:"https://github.com/urzeye/ophel/pulls",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"PR"}), Ie("span",{className:"divider",children:"/"}), Ie("a",{href:"https://github.com/urzeye/ophel/issues",target:"_blank",rel:"noopener noreferrer",className:"sec-link",children:"Issue"})]})]})]}), Ie("div",{className:"disclaimer-footer",children:Ie("button",{className:"disclaimer-agree-btn",onClick:()=>{t({hasAgreedToTerms:true});},children:se("agreeButton")})})]}), Ie("style",{children:`\n .disclaimer-modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.6);\n backdrop-filter: blur(4px);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 99999;\n font-family: ${pe};\n pointer-events: auto;\n }\n\n .disclaimer-modal {\n background: var(--gh-bg, #ffffff);\n border-radius: 16px;\n width: 90%;\n max-width: 600px;\n box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);\n overflow: hidden;\n color: var(--gh-text, #1f2937);\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n animation: modal-pop 0.3s cubic-bezier(0.16, 1, 0.3, 1);\n }\n\n .disclaimer-header {\n padding: 24px 24px 0;\n text-align: center;\n }\n\n .disclaimer-icon-img {\n width: 64px;\n height: 64px;\n margin-bottom: 20px;\n object-fit: contain;\n border-radius: 50%;\n background: var(--gh-bg, #ffffff);\n padding: 6px;\n border: 1px solid var(--gh-border, rgba(0,0,0,0.1));\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);\n transition: transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);\n /* Ensure centering if parent is flex or block */\n display: inline-block;\n }\n\n .disclaimer-icon-img:hover {\n transform: rotate(360deg) scale(1.1);\n border-color: #3b82f6;\n box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.2);\n }\n\n .disclaimer-slogan-container {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n }\n\n .sparkle {\n font-size: 18px;\n }\n\n .disclaimer-title {\n font-size: 20px;\n font-weight: 700;\n margin: 0;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n }\n\n .disclaimer-content {\n padding: 24px;\n }\n\n .disclaimer-section {\n margin-bottom: 20px;\n }\n\n .disclaimer-section h3 {\n font-size: 16px;\n font-weight: 600;\n margin: 0 0 8px;\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .disclaimer-section p {\n font-size: 14px;\n line-height: 1.6;\n margin: 0;\n color: var(--gh-text-secondary, #4b5563);\n }\n\n .disclaimer-warning {\n margin-top: 8px !important;\n color: #ef4444 !important;\n font-weight: 500;\n background: rgba(239, 68, 68, 0.1);\n padding: 8px 12px;\n border-radius: 6px;\n }\n\n .quote-section {\n text-align: center;\n background: var(--gh-bg-secondary, #f3f4f6);\n padding: 20px;\n border-radius: 12px;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n margin-bottom: 0;\n }\n\n .privacy-section {\n background: rgba(16, 185, 129, 0.1);\n border: 1px solid rgba(16, 185, 129, 0.2);\n border-radius: 12px;\n padding: 16px;\n margin-bottom: 20px;\n }\n\n .privacy-header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n color: #10b981;\n }\n\n .privacy-title {\n font-size: 15px;\n font-weight: 600;\n margin: 0;\n }\n\n .privacy-content {\n font-size: 13px !important;\n color: #059669 !important;\n line-height: 1.5 !important;\n margin: 0;\n }\n\n :host-context([data-gh-mode="dark"]) .privacy-content {\n color: #34d399 !important;\n }\n\n .disclaimer-quote-text {\n font-size: 15px;\n font-weight: 600;\n line-height: 1.5;\n color: var(--gh-text, #1f2937) !important;\n margin: 0 !important;\n font-style: italic;\n }\n\n .action-row {\n display: flex;\n align-items: center;\n gap: 12px;\n flex-wrap: wrap;\n justify-content: center;\n }\n\n .star-btn {\n display: flex;\n align-items: center;\n gap: 8px;\n background: #24292e; /* GitHub Dark */\n color: white;\n padding: 8px 20px;\n border-radius: 20px;\n text-decoration: none;\n font-weight: 600;\n font-size: 14px;\n transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n border: 1px solid rgba(255,255,255,0.1);\n }\n\n .star-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2);\n background: #2f363d;\n border-color: rgba(255,255,255,0.2);\n color: white;\n }\n\n .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .star-btn:active {\n transform: scale(0.96);\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn {\n background: #3b82f6;\n border: none;\n }\n\n :host-context([data-gh-mode="dark"]) .star-btn:hover {\n background: #2563eb;\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn {\n background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);\n }\n\n :host-context([data-gh-mode="dark"]) .review-btn:hover {\n background: linear-gradient(135deg, #4338ca 0%, #6d28d9 100%);\n }\n\n .secondary-links {\n display: flex;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .sec-link {\n color: var(--gh-text-secondary, #6b7280);\n text-decoration: none;\n transition: color 0.2s;\n }\n\n .sec-link:hover {\n color: #3b82f6;\n text-decoration: underline;\n }\n\n .divider {\n opacity: 0.5;\n }\n\n .disclaimer-footer {\n padding: 0 24px 24px;\n }\n\n .disclaimer-agree-btn {\n width: 100%;\n padding: 12px;\n background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: transform 0.1s, opacity 0.2s;\n }\n\n .disclaimer-agree-btn:hover {\n opacity: 0.9;\n }\n\n .disclaimer-agree-btn:active {\n transform: scale(0.98);\n }\n\n @keyframes modal-pop {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n }\n `})]})},Zw=({isVisible:e,text:t,hint:n,tone:r="default",blockPageInteraction:o=false,onStop:i})=>{if(_(()=>{if(!e||!o)return;const t=e=>{e.isTrusted&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation());},n=["keydown","keyup","keypress","beforeinput","input","wheel","pointerdown","pointerup","mousedown","mouseup","click","dblclick","contextmenu","touchstart","touchmove","touchend","dragstart","drop"],r={capture:true,passive:false};return n.forEach(e=>{window.addEventListener(e,t,r);}),()=>{n.forEach(e=>{window.removeEventListener(e,t,r);});}},[o,e]),!e)return null;const a="export"===r,s={background:a?"color-mix(in srgb, var(--gh-bg, #ffffff) 94%, transparent)":"var(--gh-bg, #fff)",padding:a?"20px 24px":"24px 32px",borderRadius:a?"10px":"12px",display:"flex",flexDirection:"column",alignItems:"center",gap:a?"10px":"12px",boxShadow:a?"0 18px 48px rgba(15, 23, 42, 0.22), 0 0 0 1px color-mix(in srgb, var(--gh-primary, #4285f4) 18%, var(--gh-border, #d1d5db))":"0 4px 20px rgba(0, 0, 0, 0.15)",minWidth:a?"260px":"200px",maxWidth:"min(360px, calc(100vw - 40px))",border:a?"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 16%, var(--gh-border, #e5e7eb))":void 0},l=a?{width:"28px",height:"28px",border:"3px solid color-mix(in srgb, var(--gh-primary, #4285f4) 18%, transparent)",borderTopColor:"var(--gh-primary, #4285f4)",borderRadius:"999px",animation:"gh-loading-spin 0.8s linear infinite"}:{fontSize:"32px"},c={color:"var(--gh-text, #333)",fontSize:"14px",fontWeight:a?650:500,textAlign:"center"},d=Le("div",{className:"gh-loading-mask "+(a?"gh-loading-mask--export":""),style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:a?"rgba(15, 23, 42, 0.34)":"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,pointerEvents:"auto",backdropFilter:a?"blur(2px)":void 0,WebkitBackdropFilter:a?"blur(2px)":void 0},role:"status","aria-live":"polite","aria-busy":"true",children:[a&&Ie("style",{children:"\n @keyframes gh-loading-spin {\n to { transform: rotate(360deg); }\n }\n "}), Le("div",{className:"gh-loading-content",style:s,children:[ Ie("div",{className:"gh-loading-spinner",style:l,"aria-hidden":"true",children:a?null:"⏳"}), Ie("div",{className:"gh-loading-text",style:c,children:t||se("loadingHistory")}), Ie("div",{className:"gh-loading-hint",style:{color:"var(--gh-text-secondary, #9ca3af)",fontSize:"12px",textAlign:"center",lineHeight:1.5},children:n||se("loadingHint")}),i&&Ie("button",{className:"gh-loading-stop-btn",style:{marginTop:"8px",padding:"8px 20px",background:"var(--gh-primary, #4285f4)",color:"white",border:"none",borderRadius:"6px",fontSize:"13px",cursor:"pointer"},onClick:i,children:se("stopLoading")})]})]});return document?.body?np(d,document.body):d},Yw=({isOpen:e,onClose:t,tips:n,isStatic:r=false,onMouseEnter:o,onMouseLeave:i})=>{const a=P(null);return _(()=>{if(!e||r)return;const n=e=>{"Escape"===e.key&&(e.stopPropagation(),t());};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n);}},[e,r,t]),_(()=>{if(!e||r)return;const n=e=>{const n="function"==typeof e.composedPath?e.composedPath()[0]:e.target;a.current&&!a.current.contains(n)&&t();},o=window.setTimeout(()=>{document.addEventListener("click",n);},10);return ()=>{window.clearTimeout(o),document.removeEventListener("click",n);}},[e,r,t]),e?Ie("div",{ref:a,role:"dialog","aria-label":se("featureTipsCategory"),className:"gh-magic-codex-popover "+(r?"static":"floating"),onPointerDown:e=>e.stopPropagation(),onPointerUp:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),onDoubleClick:e=>e.stopPropagation(),onMouseEnter:o,onMouseLeave:i,style:{position:r?"relative":"absolute",top:r?"auto":"36px",left:r?"auto":"-4px",width:r?"100%":"max-content",margin:r?"0 auto":"0",maxWidth:r?"100%":"calc(var(--panel-width, 320px) - 24px)",textAlign:"left",backgroundColor:r?"var(--gh-bg-secondary, #f9fafb)":"var(--gh-bg, #ffffff)",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"16px",boxShadow:r?"inset 0 1px 0 rgba(255,255,255,0.1)":"var(--gh-shadow-lg, 0 12px 32px -4px rgba(0,0,0,0.15))",zIndex:1e4,overflow:"hidden",display:"flex",flexDirection:"column",animation:"gh-popover-enter 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)"},children:Ie("div",{className:"gh-hide-scrollbar",style:{padding:"10px",display:"flex",flexDirection:"column",gap:"2px",maxHeight:"420px",overflowY:"auto",userSelect:"none"},children:n.map((e,t)=>Le("div",{className:"gh-interactive",style:{display:"flex",alignItems:"flex-start",gap:"12px",padding:"7px 12px",borderRadius:"10px",fontSize:"13px",color:"var(--gh-text-secondary, #4b5563)",lineHeight:"1.5",backgroundColor:r?"transparent":"var(--gh-bg, transparent)",transition:"background-color 0.2s ease, transform 0.1s ease"},children:[ Ie("div",{style:{fontSize:"18px",display:"flex",alignItems:"center",justifyContent:"center",width:"28px",height:"28px",flexShrink:0,borderRadius:"8px",backgroundColor:"var(--gh-bg-tertiary, rgba(0,0,0,0.04))",boxShadow:"inset 0 1px 0 rgba(255,255,255,0.2)"},children:e.icon}), Ie("div",{style:{flex:1,display:"flex",flexDirection:"column",alignSelf:"center",gap:"2px"},children:Ie("span",{style:{whiteSpace:"normal",wordBreak:"break-word",color:"var(--gh-text, #374151)"},children:e.text})})]},t))})}):null};function Jw(e,t,n){const r=se(e,{[t]:"___SC___"}).split("___SC___");return 1===r.length?r[0]:Le("span",{style:{display:"inline"},children:[r[0], Ie("span",{style:{fontFamily:"monospace",background:"var(--gh-bg-secondary, #f3f4f6)",border:"1px solid var(--gh-border, #e5e7eb)",padding:"2px 6px",borderRadius:"4px",fontSize:"11px",fontWeight:500,color:"var(--gh-text, #1f2937)",display:"inline-flex",alignItems:"center",margin:"0 4px",verticalAlign:"bottom"},children:n}),r[1]]})}function Xw(e,t,n){const r=e??er,o=e=>{const o=r[e];if(void 0===o){const r=er[e];return r?sr(r,t):n}return o?sr(o,t):n},i=(e=>{const n=r[e];if(void 0===n){const n=er[e];return n?sr(n,t):null}return n?sr(n,t):null})("togglePanelMode");return [{icon:"👻",text:Jw("tip1","modifier",t?"⌘ Cmd":"Ctrl")},{icon:"↔️",text:i?Jw("featureTip-panel-mode-toggle-path","shortcut",i):se("featureTip-panel-mode-toggle-path-dblclick")},{icon:"🔍",text:Jw("tip4","shortcut",o("openGlobalSearch"))},{icon:"🚀",text:Jw("tip3","shortcut",o("showShortcuts"))},{icon:"📋",text:Jw("tip5","shortcut",o("copyLatestReply"))},{icon:"🧭",text:Jw("tip6","shortcut",o("prevHeading")+"/"+o("nextHeading"))}]}const ex=10;const tx=({size:e=18,color:t="currentColor",className:n=""})=>Ie("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1024 1024",width:e,height:e,className:n,style:{display:"block"},children:Ie("path",{d:"M163.84 619.52l-57.6 219.52a38.4 38.4 0 0 0 8.96 35.84 37.76 37.76 0 0 0 25.6 10.24h14.72L355.84 832h6.4l551.68-576a92.8 92.8 0 0 0 24.32-74.24 112.64 112.64 0 0 0-32-78.08l-52.48-50.56a106.24 106.24 0 0 0-74.88-32.64 88.96 88.96 0 0 0-64 26.24l-550.4 571.52z m694.4-424.32l-54.4 56.32-88.96-93.44 53.12-56.96a25.6 25.6 0 0 1 34.56 0l53.12 53.76a30.72 30.72 0 0 1 8.32 20.48 22.4 22.4 0 0 1-5.76 16zM261.76 628.48l394.88-411.52 89.6 94.08-394.88 410.88z m-73.6 167.68l28.8-109.44L293.76 768z m693.12-376.32M938.88 1001.6h-832a35.2 35.2 0 0 1-35.2-35.2 34.56 34.56 0 0 1 35.2-35.2h832a35.2 35.2 0 0 1 35.2 35.2 35.2 35.2 0 0 1-35.2 35.2z",fill:t})});let nx=false;const rx=({anchorEl:e,onClose:t,children:n})=>{const r=P(null),[o,i]=z(null);if(_(()=>{if((()=>{if(nx)return;const e=document.createElement("style");e.id="gh-menu-styles",e.textContent="\n .conversations-folder-menu {\n background: var(--gh-bg, white);\n border: 1px solid var(--gh-border, #e5e7eb);\n border-radius: 6px;\n box-shadow: var(--gh-shadow, 0 4px 12px rgba(0,0,0,0.15));\n z-index: 10000000;\n padding: 3px;\n min-width: 80px;\n }\n .conversations-folder-menu button {\n display: block;\n width: 100%;\n padding: 6px 10px;\n border: none;\n background: none;\n text-align: left;\n font-size: 12px;\n color: var(--gh-text, #374151);\n cursor: pointer;\n border-radius: 4px;\n white-space: nowrap;\n }\n .conversations-folder-menu button:hover {\n background: var(--gh-hover, #f3f4f6);\n }\n",document.head.appendChild(e),nx=true;})(),!e)return;const n=n=>{const o=n.composedPath(),i=r.current&&o.includes(r.current),a=o.includes(e);i||a||t();},o=setTimeout(()=>{document.addEventListener("click",n,true);},0);return ()=>{clearTimeout(o),document.removeEventListener("click",n,true);}},[e,t]),_(()=>{if(!e||!r.current)return;const t=e.getBoundingClientRect(),n=r.current.getBoundingClientRect(),o=window.innerWidth,a=window.innerHeight,s=n.width||150,l=n.height||200;let c=t.left,d=t.bottom+4;c+s>o-10&&(c=t.right-s),c<10&&(c=10),d+l>a-10&&(d=t.top-l-4),d<10&&(d=10),i({left:c,top:d});},[e]),!e)return null;const a=Ie("div",{ref:r,className:"conversations-folder-menu",...Za,style:{position:"fixed",top:o?`${o.top}px`:"-9999px",left:o?`${o.left}px`:"-9999px",zIndex:2147483647,pointerEvents:"auto"},children:n});return np(a,document.body)},ox=({onClick:e,danger:t,children:n})=>Ie("button",{onClick:e,style:t?{color:"var(--gh-text-danger, #ef4444)"}:void 0,children:n}),ix=({folder:e,anchorEl:t,onClose:n,onRename:r,onDelete:o})=>Le(rx,{anchorEl:t,onClose:n,children:[ Ie(ox,{onClick:()=>{n(),r();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsRename")}), Ie(tx,{size:13})]})}), Ie(ox,{danger:true,onClick:()=>{n(),o();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsDelete")}), Ie(Bt,{size:13})]})})]}),ax=({conversation:e,anchorEl:t,onClose:n,onRename:r,onTogglePin:o,onSetTags:i,onMoveTo:a,onExport:s,onDelete:l})=>Le(rx,{anchorEl:t,onClose:n,children:[ Ie(ox,{onClick:()=>{n(),r();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsRename")}), Ie(tx,{size:13})]})}), Ie(ox,{onClick:()=>{n(),o();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:e.pinned?se("conversationsUnpin"):se("conversationsPin")}), Ie(Ot,{size:13,filled:e.pinned})]})}), Ie(ox,{onClick:()=>{n(),i();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsSetTags")}), Ie(Nt,{size:13})]})}), Ie(ox,{onClick:()=>{n(),a();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsMoveTo")}), Ie(ze,{size:13})]})}), Ie(ox,{onClick:()=>{n(),s();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("export")}), Ie(Ve,{size:13})]})}), Ie(ox,{danger:true,onClick:()=>{n(),l();},children:Le("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px"},children:[ Ie("span",{children:se("conversationsDelete")}), Ie(Bt,{size:13})]})})]}),sx=({anchorEl:e,onClose:t,onExportMarkdown:n,onExportJSON:r,onExportTXT:o})=>Le(rx,{anchorEl:e,onClose:t,children:[ Ie(ox,{onClick:()=>{t(),n();},children:Le("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Ie(Ut,{size:14}), Ie("span",{children:se("exportToMarkdown")})]})}), Ie(ox,{onClick:()=>{t(),r();},children:Le("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Ie(jt,{size:14}), Ie("span",{children:se("exportToJSON")})]})}), Ie(ox,{onClick:()=>{t(),o();},children:Le("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[ Ie(Ht,{size:14}), Ie("span",{children:se("exportToTXT")})]})})]});e(".gh-panel-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-folder-item.expanded{border-bottom-left-radius:0!important;border-bottom-right-radius:0!important;border-bottom:none!important}.conversations-list{width:100%!important;box-sizing:border-box!important;margin:0!important;border-top-left-radius:0!important;border-top-right-radius:0!important;border-top:none!important}.conversations-toolbar-btn{background:transparent!important;border:1px solid transparent!important;box-shadow:none!important;color:var(--gh-text-secondary, #6b7280)!important;border-radius:6px!important;transition:all .2s ease!important;min-width:28px!important;height:28px!important;margin:0!important;padding:0!important;cursor:pointer;display:flex;align-items:center;justify-content:center}.conversations-toolbar-btn:hover{background:#7f7f7f26!important;color:var(--gh-text, #374151)!important}.conversations-toolbar-btn.active{background:var(--gh-primary, #3b82f6)!important;color:#fff!important;border-color:var(--gh-primary, #3b82f6)!important}.conversations-toolbar-btn svg{fill:currentColor!important;width:16px!important;height:16px!important}.conversations-content{display:flex;flex-direction:column;flex:1;min-height:200px;overflow-x:hidden;overflow-y:auto}.conversations-content.is-dragging-any{-webkit-user-select:none;user-select:none}.conversations-content.is-dragging-any .conversations-folder-item,.conversations-content.is-dragging-any .conversations-item,.conversations-folder-item:active,.conversations-item:active{cursor:grabbing}.conversations-toolbar{display:flex;gap:6px;padding:8px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);flex-shrink:0;background:var(--gh-bg, #ffffff)}.conversations-toolbar-btn{padding:5px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;transition:all .2s;display:flex;align-items:center;justify-content:center;min-width:32px;height:32px;flex-shrink:0}.conversations-toolbar-btn svg{width:16px;height:16px}.conversations-toolbar-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-text-secondary, #9ca3af)}.conversations-toolbar-btn.batch-mode.active{background:var(--gh-border-active);color:#fff;border-color:var(--gh-border-active)}.conversations-toolbar-btn:disabled{opacity:.6;cursor:wait}.conversations-folder-select-dropdown{width:100%}.conversations-folder-select{padding:4px 8px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;background:var(--gh-bg-secondary, #f9fafb);font-size:13px;color:var(--gh-text, #374151);cursor:pointer;min-width:80px;height:32px;width:100%;line-height:1.35;font-family:inherit;appearance:none;-webkit-appearance:none}.conversations-folder-select-icon{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;width:16px;min-width:16px;height:18px;font-size:15px;line-height:1}.conversations-folder-select:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-select:focus{outline:none;border-color:var(--gh-border-active)}.conversations-folder-select:disabled{opacity:.6;cursor:not-allowed}.conversations-folder-select-menu{scrollbar-width:thin}.conversations-folder-select-option{font-family:inherit}.conversations-folder-list{flex:1;overflow-y:auto;padding:8px;scrollbar-width:none;-ms-overflow-style:none}.conversations-folder-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-content{scrollbar-width:none;-ms-overflow-style:none}.conversations-content::-webkit-scrollbar{display:none;width:0;height:0}.conversations-unsupported-mask{position:absolute;inset:0;z-index:12;display:flex;align-items:center;justify-content:center;padding:16px;background:linear-gradient(180deg,#f8fafceb,#f8fafcd1);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);pointer-events:all}.conversations-unsupported-card{width:100%;max-width:280px;border-radius:16px;padding:16px 18px 18px;background:var(--gh-bg, #ffffff);border:1px solid rgba(148,163,184,.25);box-shadow:0 16px 32px #0f172a1f;text-align:center;color:var(--gh-text, #374151)}.conversations-unsupported-icon{width:44px;height:44px;margin:0 auto 10px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:20px;color:#6a3a00;background:linear-gradient(135deg,#ffd29a,#ffb86b);box-shadow:0 8px 18px #ffab5859}.conversations-unsupported-title{font-size:14px;font-weight:600;margin-bottom:6px}.conversations-unsupported-desc{font-size:12px;color:var(--gh-text-secondary, #6b7280);line-height:1.4}:host([data-theme=\"dark\"]) .conversations-unsupported-mask,.gh-root[data-theme=dark] .conversations-unsupported-mask,body[data-gh-mode=dark] .conversations-unsupported-mask,html[data-theme=dark] .conversations-unsupported-mask{background:linear-gradient(180deg,#0a0a0aeb,#0a0a0adb)}:host([data-theme=\"dark\"]) .conversations-unsupported-card,.gh-root[data-theme=dark] .conversations-unsupported-card,body[data-gh-mode=dark] .conversations-unsupported-card,html[data-theme=dark] .conversations-unsupported-card{background:#1b1b1b;border:1px solid rgba(255,255,255,.08);box-shadow:0 18px 36px #0000008c;color:var(--gh-text, #e3e3e3)}:host([data-theme=\"dark\"]) .conversations-unsupported-icon,.gh-root[data-theme=dark] .conversations-unsupported-icon,body[data-gh-mode=dark] .conversations-unsupported-icon,html[data-theme=dark] .conversations-unsupported-icon{color:#f7d6a8;background:linear-gradient(135deg,#6c420c,#c37a24);box-shadow:0 10px 20px #00000080}.conversations-folder-item{display:flex;align-items:center;justify-content:space-between;position:relative;padding:10px 12px;border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);cursor:pointer;transition:background-color .2s,border .2s,box-shadow .2s,outline .2s,transform .2s;flex-wrap:wrap}.conversations-folder-item+.conversations-folder-item,.conversations-list+.conversations-folder-item{margin-top:4px}.conversations-folder-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-folder-item.default{background:var(--gh-folder-bg-default)}.conversations-folder-item.expanded{border:2px solid var(--gh-border-active);box-shadow:0 2px 8px var(--gh-shadow-sm);border-radius:8px 8px 0 0}.conversations-folder-info{display:flex;align-items:center;gap:8px;flex:1;min-width:0;position:relative}.conversations-folder-icon{font-size:18px;width:24px;height:24px;display:flex;align-items:center;justify-content:center;line-height:1;flex-shrink:0}.conversations-folder-name{font-size:14px;font-weight:500;color:var(--gh-text, #1f2937);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;-webkit-user-select:none;user-select:none}.conversations-folder-count{font-size:12px;color:var(--gh-text-secondary, #6b7280);flex-shrink:0;-webkit-user-select:none;user-select:none}.conversations-folder-menu-btn{width:24px;height:24px;border:none;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;border-radius:4px;font-size:14px}.conversations-folder-menu-btn:hover{background:var(--gh-border, #e5e7eb)}.conversations-folder-controls{display:flex;align-items:center;gap:4px;flex-shrink:0}.conversations-folder-item.is-dragging{opacity:.74;background:color-mix(in srgb,var(--gh-primary, #4285f4) 9%,var(--gh-bg, #fff))!important;outline:1px dashed var(--gh-primary, #4285f4);outline-offset:-2px;box-shadow:0 8px 18px #4285f42e,inset 0 0 0 1px color-mix(in srgb,var(--gh-primary, #4285f4) 18%,transparent);transform:scale(.985)}.conversations-folder-item.is-drag-over{background:color-mix(in srgb,var(--gh-primary, #4285f4) 8%,var(--gh-bg, #fff))!important;outline:2px dashed color-mix(in srgb,var(--gh-primary, #4285f4) 70%,transparent);outline-offset:-3px;box-shadow:inset 0 3px 0 var(--gh-primary, #4285f4),0 6px 16px #4285f429;transform:translateY(-1px)}.conversations-folder-item.is-drag-over:after{content:\"\";position:absolute;top:-3px;left:50%;width:36px;height:5px;border-radius:999px;background:var(--gh-primary, #4285f4);box-shadow:0 2px 8px #4285f44d;pointer-events:none;transform:translate(-50%)}.conversations-folder-item.is-drag-over-conv{background:color-mix(in srgb,var(--gh-primary, #4285f4) 10%,var(--gh-bg, #fff))!important;outline:2px dashed var(--gh-primary, #4285f4)!important;outline-offset:-3px;box-shadow:0 0 0 3px color-mix(in srgb,var(--gh-primary, #4285f4) 12%,transparent),0 8px 18px #4285f42e;transform:translateY(-1px)}.conversations-folder-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:100px}.conversations-folder-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-folder-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-empty{text-align:center;padding:40px 20px;color:var(--gh-text-secondary, #9ca3af);font-size:14px}.conversations-search-bar{padding:6px 12px;border-bottom:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-search-wrapper{display:flex;align-items:center;gap:0;position:relative}.conversations-search-wrapper.has-filter .conversations-tag-search-btn{border-radius:0;border-right:none}.conversations-search-input-group{flex:1;position:relative;height:32px;min-width:0}.conversations-search-input{width:100%;height:100%;padding:0 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px 0 0 8px;font-size:14px;box-sizing:border-box;transition:all .2s;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-search-input:focus{outline:none;border-color:var(--gh-border-active);z-index:1;position:relative}.conversations-pin-filter-btn{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-pin-filter-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-pin-filter-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-result-bar{text-align:center;padding:6px;color:var(--gh-border-active);font-size:13px;background:var(--gh-folder-bg-default);border-radius:4px;margin-top:8px;display:none}.conversations-result-bar.visible{display:block}.conversations-tag{display:inline-flex;align-items:center;padding:2px 6px;border-radius:4px;font-size:11px;margin:0;color:#fff;background-color:var(--gh-text-secondary, #9ca3af);line-height:1.2;max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;flex-shrink:0}.conversations-tag-list{display:flex;align-items:center;gap:4px;border:none;padding:0;margin:0;flex-shrink:0;min-width:0;max-width:52%;overflow:hidden}.conversations-tag-list:empty{display:none}.conversations-tag-more{color:var(--gh-text-secondary, #6b7280);background:var(--gh-bg-secondary, #f3f4f6);border:1px solid var(--gh-border, #e5e7eb)}.conversations-hidden-tags-tooltip{display:flex;flex-direction:column;gap:6px;min-width:110px}.conversations-hidden-tag-item{display:flex;align-items:center;gap:6px;font-size:12px;line-height:1.25}.conversations-hidden-tag-dot{width:8px;height:8px;border-radius:999px;flex-shrink:0}.conversations-tag-search-btn{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:14px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s}.conversations-tag-search-btn:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-tag-search-btn.active{color:var(--gh-border-active);background:var(--gh-folder-bg-default);box-shadow:inset 0 0 0 1px var(--gh-border-active)}.conversations-tag-search-btn.empty{opacity:.5}.conversations-search-clear{cursor:pointer;width:32px;height:32px;color:var(--gh-text-tertiary, #9ca3af);font-size:18px;display:flex;align-items:center;justify-content:center;border:1px solid var(--gh-input-border, #d1d5db);border-left:none;border-radius:0 8px 8px 0;background:var(--gh-bg, white);box-sizing:border-box;transition:all .2s;-webkit-user-select:none;user-select:none}.conversations-search-clear:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #ef4444)}.conversations-search-clear.disabled{opacity:.3;cursor:default;background:var(--gh-bg-secondary, #f9fafb);pointer-events:none}.conversations-tag-filter-menu{position:absolute;top:calc(100% + 4px);right:0;width:200px;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;display:flex;flex-direction:column;overflow:hidden;animation:fadeIn .2s}.conversations-tag-filter-list{overflow-y:auto;flex:1;padding:4px;display:flex;flex-direction:column;gap:2px}.conversations-tag-filter-footer{padding:4px;border-top:1px solid var(--gh-border, #e5e7eb);background:var(--gh-bg-secondary, #f9fafb);flex-shrink:0}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px;cursor:pointer;border-radius:6px;font-size:13px;color:var(--gh-text, #374151);width:100%;box-sizing:border-box;overflow:hidden}.conversations-tag-filter-item span:not(.conversations-tag-dot){white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}.conversations-tag-filter-item.selected{background:var(--gh-folder-bg-default);color:var(--gh-primary, #3b82f6);font-weight:500}.conversations-tag-filter-item.selected:after{content:\"✓\";margin-left:auto;font-size:14px;font-weight:700}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;display:inline-block;flex-shrink:0;border:1px solid rgba(0,0,0,.05)}.conversations-tag-filter-divider{height:1px;background:var(--gh-border, #e5e7eb);margin:4px 0;flex-shrink:0}.conversations-tag-filter-action{color:var(--gh-border-active);font-weight:500;justify-content:center}.conversations-tag-manager-list{max-height:250px;overflow-y:auto;border:1px solid var(--gh-border, #e5e7eb);border-radius:4px;margin-bottom:12px;padding:4px}.conversations-tag-manager-item{display:flex;align-items:center;justify-content:space-between;padding:8px;border-bottom:1px solid var(--gh-hover, #f3f4f6)}.conversations-tag-manager-item:last-child{border-bottom:none}.conversations-tag-manager-item:hover{background:var(--gh-bg-secondary, #f9fafb)}.conversations-tag-preview{padding:2px 8px;border-radius:4px;font-size:12px;color:#fff;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:middle;display:inline-block}.conversations-tag-actions{display:flex;gap:4px;flex-shrink:0}.conversations-tag-btn{width:24px;height:24px;border:none;background:transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;color:var(--gh-text-tertiary, #9ca3af);border-radius:4px;transition:all .2s}.conversations-tag-btn:hover{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #ef4444)}.conversations-tag-btn.edit:hover{background:var(--gh-folder-bg-default, #e0f2fe);color:var(--gh-primary, #3b82f6)}.conversations-color-picker{display:grid;grid-template-columns:repeat(10,1fr);gap:6px;margin:12px 0}.conversations-color-item{width:24px;height:24px;border-radius:4px;cursor:pointer;border:2px solid transparent;transition:transform .1s}.conversations-color-item:hover{transform:scale(1.1)}.conversations-color-item.selected{border-color:var(--gh-text, #374151);transform:scale(1.1);box-shadow:0 2px 4px #0003}.conversations-list{width:calc(100% - 8px);margin-left:4px;margin-right:4px;padding:8px;background:var(--gh-bg-secondary);border:2px solid var(--gh-border-active);border-top:none;border-radius:0 0 8px 8px;margin-top:-4px;max-height:300px;overflow-y:auto;overflow-x:hidden;scrollbar-width:none;-ms-overflow-style:none}.conversations-list::-webkit-scrollbar{display:none}.conversations-list-empty{padding:12px;color:var(--gh-text-secondary, #9ca3af);font-size:13px;text-align:center}.conversations-item{display:flex;align-items:center;padding:8px 34px 8px 12px;margin-bottom:4px;border-radius:6px;background:var(--gh-bg, white);cursor:pointer;transition:background-color .2s;gap:8px;position:relative}.conversations-item.is-dragging{opacity:.5}.conversations-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item:before{content:\"\";position:absolute;left:0;top:50%;transform:translateY(-50%) scaleY(0);width:4px;height:80%;background-color:var(--gh-primary, #428cf1);border-radius:0 4px 4px 0;transition:transform .2s}.conversations-item:hover:before{transform:translateY(-50%) scaleY(1)}.conversations-item-title{display:block;font-size:14px;color:var(--gh-text, #374151);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.35}.conversations-item-main{flex:1;min-width:0}.conversations-item-headline{display:flex;align-items:center;gap:6px;min-width:0}.conversations-item-meta{display:flex;align-items:center;gap:6px;position:absolute;top:50%;right:8px;transform:translateY(-50%)}.conversations-item-time{display:none}.conversations-item-menu-btn{width:26px;height:26px;border:none;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;border-radius:6px;font-size:12px;opacity:0;pointer-events:none;transform:translate(4px);transition:opacity .18s ease,transform .18s ease,background-color .2s,color .2s;flex-shrink:0;display:flex;align-items:center;justify-content:center}.conversations-folder-checkbox,.conversations-item-checkbox{appearance:none;-webkit-appearance:none;width:16px;height:16px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:4px;background-color:var(--gh-bg, #ffffff);cursor:pointer;position:relative;margin:0;padding:0;display:inline-flex;align-items:center;justify-content:center;transition:all .2s}.conversations-folder-checkbox:checked,.conversations-item-checkbox:checked{background-color:var(--gh-primary, #4285f4);border-color:var(--gh-primary, #4285f4)}.conversations-folder-checkbox:checked:after,.conversations-item-checkbox:checked:after{content:\"\";width:10px;height:10px;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E\");background-size:contain;background-repeat:no-repeat;background-position:center;display:block}.conversations-folder-checkbox:hover,.conversations-item-checkbox:hover{border-color:var(--gh-primary, #4285f4)}.conversations-item:hover .conversations-item-menu-btn,.conversations-item:focus-within .conversations-item-menu-btn{opacity:1;pointer-events:auto;transform:translate(0);background:var(--gh-active-bg, rgba(0, 0, 0, .07));color:var(--gh-text-secondary, #6b7280)}.conversations-item-menu-btn:hover{background:var(--gh-hover, rgba(0, 0, 0, .12))!important;color:var(--gh-primary, #4285f4)!important}.conversations-content.is-narrow .conversations-item{padding-right:34px}.conversations-content.is-narrow .conversations-item-title{font-size:13px}.conversations-content.is-narrow .conversations-tag{max-width:72px}.conversations-content.is-narrow .conversations-tag-list{max-width:46%}@media(hover:none){.conversations-item-menu-btn{opacity:.72;pointer-events:auto;transform:none}}.conversations-item-menu{background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000002;padding:4px;min-width:120px}.conversations-item-menu button{display:block;width:100%;padding:8px 12px;border:none;background:none;text-align:left;font-size:13px;color:var(--gh-text, #374151);cursor:pointer;border-radius:4px}.conversations-item-menu button:hover{background:var(--gh-hover, #f3f4f6)}.conversations-item-menu button.danger{color:var(--gh-text-danger, #dc2626)}.conversations-item-menu button.danger:hover{background:var(--gh-bg-danger, #fef2f2)}.conversations-item.locate-highlight{background:var(--gh-outline-locate-bg)!important;border:2px solid var(--gh-outline-locate-border)!important;border-radius:6px;box-shadow:inset 0 0 8px var(--gh-outline-locate-shadow);animation:conversationsLocatePulse .6s ease-in-out 2}@keyframes conversationsLocatePulse{0%,to{transform:scale(1)}50%{transform:scale(1.01)}}.conversations-folder-checkbox{margin-right:8px;width:16px;height:16px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-item-checkbox{width:16px;height:16px;margin-right:8px;cursor:pointer;accent-color:var(--gh-checkbox-bg, #4f46e5);flex-shrink:0}.conversations-batch-bar{position:sticky;bottom:0;left:0;right:0;background:var(--gh-bg, white);padding:8px 12px;display:flex;align-items:center;justify-content:space-between;border-radius:8px;margin-top:8px;border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 -2px 10px #0000000d}.conversations-batch-info{color:var(--gh-text, #374151);font-size:13px;font-weight:500}.conversations-batch-btns{display:flex;gap:8px}.conversations-batch-btn{padding:4px 10px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:6px;font-size:12px;cursor:pointer;transition:all .2s;background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151)}.conversations-batch-btn:hover{background:var(--gh-border, #e5e7eb);border-color:var(--gh-text-tertiary, #9ca3af)}.conversations-batch-btn.danger{background:var(--gh-bg-danger-hover, #fee2e2);color:var(--gh-text-danger, #dc2626);border-color:var(--gh-bg-danger-hover, #fecaca)}.conversations-batch-btn.danger:hover{background:var(--gh-bg-danger-hover, #fecaca);border-color:var(--gh-text-danger, #f87171)}.conversations-batch-btn.cancel{background:transparent;border:none;color:var(--gh-text-secondary, #6b7280)}.conversations-batch-btn.cancel:hover{background:var(--gh-hover, #f3f4f6);color:var(--gh-text, #374151);border:none}.conversations-dialog-overlay{position:fixed;inset:0;background:#00000080;z-index:1000003;display:flex;align-items:center;justify-content:center}.conversations-dialog{background:var(--gh-bg, white);border-radius:12px;padding:20px;min-width:320px;box-shadow:0 10px 40px #0003}.conversations-dialog-title{font-size:16px;font-weight:600;color:var(--gh-text, #1f2937);margin-bottom:16px}.conversations-dialog-message{font-size:14px;color:var(--gh-badge-text, #4b5563);margin-bottom:20px;line-height:1.5;white-space:pre-line}.conversations-dialog-section{margin-bottom:16px}.conversations-dialog-section label{display:block;font-size:13px;color:var(--gh-text-secondary, #6b7280);margin-bottom:8px}.conversations-dialog-input{width:100%;padding:10px 12px;border:1px solid var(--gh-input-border, #d1d5db);border-radius:8px;font-size:14px;box-sizing:border-box;background:var(--gh-input-bg, #ffffff);color:var(--gh-text, #1f2937)}.conversations-dialog-input:focus{outline:none;border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f41a}.conversations-dialog-buttons{display:flex;justify-content:flex-end;gap:8px;margin-top:20px}.conversations-folder-select-list{max-height:250px;overflow-y:auto;margin:12px 0}.conversations-folder-select-item{padding:12px 16px;border-radius:8px;cursor:pointer;transition:all .2s;font-size:14px}.conversations-folder-select-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-emoji-picker{display:flex;flex-wrap:wrap;gap:4px}.conversations-emoji-btn{width:36px;height:36px;border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;background:var(--gh-bg-secondary, #f9fafb);font-size:18px;cursor:pointer;transition:all .2s}.conversations-emoji-btn:hover{background:var(--gh-hover, #f3f4f6);border-color:var(--gh-input-border, #d1d5db)}.conversations-emoji-btn.selected{background:var(--gh-selected-gradient, #e0e7ff);border-color:var(--gh-primary, #4285f4);box-shadow:0 0 0 2px #4285f433}.conversations-highlight{background:#ffd50066;padding:0 2px;border-radius:2px}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.conversations-tag-filter-list,.conversations-tag-manager-list{max-height:200px;overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none}.conversations-tag-filter-list::-webkit-scrollbar,.conversations-tag-manager-list::-webkit-scrollbar{display:none;width:0;height:0}.conversations-tag-filter-menu{position:absolute;top:100%;right:0;background:var(--gh-bg, white);border:1px solid var(--gh-border, #e5e7eb);border-radius:8px;box-shadow:0 4px 12px #00000026;z-index:1000;min-width:150px;max-height:250px;overflow:hidden}.conversations-tag-filter-item{display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:pointer;font-size:13px;color:var(--gh-text, #374151)}.conversations-tag-filter-item:hover{background:var(--gh-hover, #f3f4f6)}.conversations-tag-filter-item.selected{background:#3b82f61a}.conversations-tag-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}.conversations-tag-filter-footer{border-top:1px solid var(--gh-border, #e5e7eb)}.conversations-tag-filter-action{color:var(--gh-primary, #3b82f6)!important}");const lx=30,cx=()=>{const e=se("conversationsInbox");return "conversationsInbox"===e?"Inbox":e},dx=e=>{if("inbox"===e.id)return cx();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},ux=(e,t)=>{if(!t)return e;return e.split(new RegExp(`(${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})`,"gi")).map((e,n)=>e.toLowerCase()===t.toLowerCase()?Ie("span",{className:"conversations-highlight",children:e},n):e)},hx=({manager:e,onInteractionStateChange:t})=>{const n={[uo]:"ChatGLM",[ko]:"Z.ai",[vo]:"Qianwen",[wo]:"Qwen Studio",[fo]:"ima"},{settings:r}=Ai(),[i,a]=z([]),[s,l]=z({}),[c,d]=z([]),[u,h]=z("inbox"),[g,p]=z(null),[m,f]=z(false),[b,y]=z(new Set),[v,w]=z(false),[x,k]=z(false),[S,C]=z(""),[E,T]=z(false),[M,I]=z(new Set),[L,N]=z(null),[D,R]=z(false),[B,O]=z(false),[F,$]=z(false),U=ce(),j=e.siteAdapter?.getSiteId?.(),H=!(!j||!n[j]),W=j?n[j]||j:"",G=se("conversationsUnsupportedTitle",{site:W}),Q=se("conversationsUnsupportedDesc"),V=se("conversationsUnsupportedSync",{site:W}),K=H,[Z,Y]=z(null),[J,X]=z(null),[ee,te]=z(null),[ne,re]=z(null),[oe,ie]=z(null),[ae,le]=z(null),de=P(null),ue=P(null),he=P(null),ge=P(null),pe=P(null),me=P(null),fe=P(null);_(()=>{const e=he.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>{$(e.clientWidth<=340);};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);const be=A(async()=>{a([...e.getFolders()]),l({...e.getAllConversations()}),d([...e.getTags()]),h(e.getLastUsedFolderId());},[e]);_(()=>{be();},[be]),_(()=>{const t=e.onDataChange(()=>{be();});return ()=>t()},[e,be]);const ye=A(e=>{if(!e&&!E&&0===M.size)return void N(null);const t=new Set,n=new Set,r=new Map,o=e.toLowerCase();i.forEach(n=>{e&&dx(n).toLowerCase().includes(o)&&t.add(n.id);}),Object.values(s).forEach(t=>{let i=true;if(e&&!t.title.toLowerCase().includes(o)&&(i=false),E&&!t.pinned&&(i=false),M.size>0){const e=t.tagIds?.some(e=>M.has(e));e||(i=false);}i&&(n.add(t.id),r.set(t.id,t.folderId));}),N({folderMatches:t,conversationMatches:n,conversationFolderMap:r,totalCount:n.size});},[i,s,E,M]);_(()=>{ye(S);},[E,M,ye,S]),_(()=>{if(!D)return;const e=e=>{const t=e.composedPath(),n=me.current&&t.includes(me.current),r=fe.current&&t.includes(fe.current);n||r||R(false);},t=setTimeout(()=>{document.addEventListener("click",e,true);},0);return ()=>{clearTimeout(t),document.removeEventListener("click",e,true);}},[D]),_(()=>{const e=!!(J||Z||D||B||x);t?.(e);},[J,Z,D,B,x,t]);const ve=q(()=>{const e=new Map;return c.forEach(t=>e.set(t.id,t)),e},[c]),we=q(()=>{const t=e.getSidebarConversationOrder(),n=new Map;for(let e=0;eL.conversationMatches.has(e.id)):a;t.sort((e,t)=>{if(e.pinned&&!t.pinned)return -1;if(!e.pinned&&t.pinned)return 1;const r=n.get(e.id)??-1,o=n.get(t.id)??-1;return -1===r&&-1===o?(t.updatedAt||0)-(e.updatedAt||0):-1===r?1:-1===o?-1:r-o}),i.set(e,t);}return i},[s,L,e]),xe=P(we);xe.current=we;const ke=e=>we.get(e)||[],[Se,Ce]=z({}),Ae=P(new Map),Ee=A(async()=>{if(H)Li(V);else {w(true);try{const t=!1!==await(e.siteAdapter?.loadAllConversations?.()),n=e.siteAdapter?.getConversationList?.()?.length||0,{newCount:r,updatedCount:o,deletedCount:i}=await e.syncConversations(u,!1,{syncDeleted:t});be(),Li(0===n?se("conversationsSyncNoSidebarItems"):se("conversationsSyncResult").replace("{scanned}",String(n)).replace("{added}",String(r)).replace("{updated}",String(o)).replace("{deleted}",String(i)));}finally{w(false);}}},[H,V,e,u,be]),Te=A(()=>{if(e.siteAdapter?.isSharePage?.()||e.siteAdapter?.isNewConversation?.())return;const t=e.siteAdapter?.getSessionId?.();if(!t||"default"===t||"app"===t)return;const n=e.getConversation(t);if(!n)return void Ee();p(n.folderId);const r=(we.get(n.folderId)||[]).findIndex(e=>e.id===t);if(r>=0){const e=r+1;Ce(t=>({...t,[n.folderId]:Math.max(t[n.folderId]||lx,e)}));}setTimeout(()=>{const e=he.current;if(!e)return;const n=e.querySelector(`.conversations-item[data-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("locate-highlight"),setTimeout(()=>n.classList.remove("locate-highlight"),2e3));},100);},[e,Ee,we]);_(()=>{const e=()=>{window.__ophelPendingLocateConversation=false,Te();};return window.__ophelPendingLocateConversation&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateConversation",e),()=>{window.removeEventListener("ophel:locateConversation",e);}},[Te]),_(()=>{const e=()=>{Ee();};return window.addEventListener("ophel:refreshConversations",e),()=>{window.removeEventListener("ophel:refreshConversations",e);}},[Ee]);const Me=()=>{y(new Set),f(false);},Ne=S||E||M.size>0,De=P(null);_(()=>{g!==De.current&&(De.current=g,g&&Ce(e=>({...e,[g]:Math.max(e[g]??0,lx)})));},[g]),_(()=>{if(L){const e=new Set(L.conversationFolderMap.values());Ce(t=>{const n={...t};for(const r of e)r in n||(n[r]=lx);return n});}},[L]);const qe=P(null);_(()=>{if("undefined"==typeof IntersectionObserver)return;const e=new IntersectionObserver(t=>{for(const n of t)if(n.isIntersecting){const t=n.target.dataset.folderId;if(t){const r=xe.current.get(t)?.length||0;Ce(e=>{const n=e[t]||lx,o=Math.min(n+lx,r);return o===n?e:{...e,[t]:o}}),e.unobserve(n.target);}}},{rootMargin:"100px"});qe.current=e;for(const[,t]of Ae.current)t&&e.observe(t);return ()=>e.disconnect()},[]);const Pe=A(t=>{m?y(e=>{const n=new Set(e);return n.has(t.id)?n.delete(t.id):n.add(t.id),n}):e.siteAdapter?.navigateToConversation(t.id,t.url);},[m,e]),Be=e=>{const t=ke(e);return t.length>0&&t.every(e=>b.has(e.id))},Oe=e=>{if(!L)return true;const t=L.folderMatches.has(e.id),n=Array.from(L.conversationFolderMap.values()).includes(e.id);return t||n},Fe=q(()=>i.map(e=>{const t=dx(e),n=`${e.icon?`${e.icon} `:""}${t}`.trim();return {value:e.id,title:n,label:Le(_e,{children:[e.icon&&Ie("span",{className:"conversations-folder-select-icon",children:e.icon}), Ie("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}}),[i,U]); return Le(_e,{children:[ Ie(Zw,{isVisible:x,text:`${se("delete")}...`}), Le("div",{ref:he,className:`conversations-content ${F?"is-narrow":""} ${oe||ee?"is-dragging-any":""}`,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[K&&Ie("div",{className:"conversations-unsupported-mask","aria-hidden":"true",children:Le("div",{className:"conversations-unsupported-card",children:[ Ie("div",{className:"conversations-unsupported-icon",children:"!"}), Ie("div",{className:"conversations-unsupported-title",children:G}), Ie("div",{className:"conversations-unsupported-desc",children:Q})]})}), Le("div",{className:"conversations-toolbar",children:[ Ie(up,{content:se("conversationsSelectFolder"),triggerStyle:{flex:1,minWidth:0},children:Ie(zw,{className:"conversations-folder-select-dropdown",buttonClassName:"conversations-folder-select",menuClassName:"conversations-folder-select-menu",optionClassName:"conversations-folder-select-option",options:Fe,value:u,ariaLabel:se("conversationsSelectFolder"),onOpenChange:O,onChange:t=>{h(t),e.setLastUsedFolder(t);}})}), Ie(up,{content:se("conversationsSync"),children:Ie("button",{className:"conversations-toolbar-btn sync",disabled:v||H,onClick:Ee,children:Ie(v?wt:xt,{size:18})})}), Ie(up,{content:se("conversationsLocate"),children:Ie("button",{className:"conversations-toolbar-btn locate",onClick:Te,children:Ie(et,{size:18})})}), Ie(up,{content:se("conversationsBatchMode"),children:Ie("button",{className:"conversations-toolbar-btn batch-mode "+(m?"active":""),onClick:()=>{m&&y(new Set),f(!m);},children:Ie(yt,{size:18})})}), Ie(up,{content:se("conversationsAddFolder"),children:Ie("button",{className:"conversations-toolbar-btn add-folder",onClick:()=>{t?.(true),Y({type:"folder"});},children:Ie(vt,{size:18})})})]}), Le("div",{className:"conversations-search-bar",children:[ Le("div",{className:"conversations-search-wrapper",style:{position:"relative"},children:[ Ie("div",{className:"conversations-search-input-group",children:Ie("input",{ref:ge,type:"text",className:"conversations-search-input",placeholder:se("conversationsSearchPlaceholder"),value:S,onChange:e=>{return t=e.target.value,C(t),pe.current&&clearTimeout(pe.current),void(pe.current=setTimeout(()=>ye(t),150));var t;}})}), Ie(up,{content:se("conversationsFilterPinned"),children:Ie("div",{className:"conversations-pin-filter-btn "+(E?"active":""),style:{userSelect:"none"},onClick:()=>T(!E),children:Ie(Ot,{size:16})})}), Ie(up,{content:se("conversationsFilterByTags"),children:Ie("div",{ref:fe,className:"conversations-tag-search-btn "+(M.size>0?"active":""),style:{userSelect:"none"},onClick:()=>{const e=!D;e&&t?.(true),R(e);},children:Ie(Nt,{size:16})})}),D&&Le("div",{ref:me,className:"conversations-tag-filter-menu",children:[ Ie("div",{className:"conversations-tag-filter-list",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:0===c.length?Ie("div",{className:"conversations-tag-filter-item",style:{color:"var(--gh-text-tertiary, #9ca3af)",cursor:"default"},children:se("conversationsNoTags")}):c.map(e=>Le("div",{className:"conversations-tag-filter-item "+(M.has(e.id)?"selected":""),onClick:()=>{const t=new Set(M);t.has(e.id)?t.delete(e.id):t.add(e.id),I(t);},children:[ Ie("span",{className:"conversations-tag-dot",style:{backgroundColor:e.color}}), Ie("span",{children:e.name})]},e.id))}), Ie("div",{className:"conversations-tag-filter-footer",children:Ie("div",{className:"conversations-tag-filter-item conversations-tag-filter-action",onClick:()=>{R(false),t?.(true),Y({type:"tagManager",conv:void 0});},children:se("conversationsManageTags")})})]}), Ie(up,{content:se("conversationsClearAll"),children:Ie("div",{className:"conversations-search-clear "+(Ne?"":"disabled"),onClick:Ne?()=>{C(""),T(false),I(new Set),N(null);}:void 0,children:Ie(Re,{size:14})})})]}),S&&L&&Le("div",{className:"conversations-result-bar visible",children:[L.totalCount," ",se("conversationsSearchResult")]})]}), Ie("div",{className:"conversations-folder-list",children:0===i.filter(Oe).length?Ie("div",{className:"conversations-empty",children:se(L?"conversationsNoSearchResult":"conversationsEmpty")}):i.filter(Oe).map((n,a)=>{const l=(c=n.id,L?Array.from(L.conversationFolderMap.values()).includes(c):g===c);var c;const d=(e=>ke(e).length)(n.id),u=dx(n),h=r?.features?.conversations?.folderRainbow??false;let f="transparent";return n.isDefault?f="var(--gh-folder-bg-default)":h?f=`var(--gh-folder-bg-${a%8})`:l&&(f="var(--gh-folder-bg-expanded, rgba(59, 130, 246, 0.08))"),Le(o.Fragment,{children:[ Le("div",{className:["conversations-folder-item",l?"expanded":"",n.isDefault?"default":"",ee===n.id?"is-dragging":"",ne===n.id&&ee!==n.id?"is-drag-over":"",ae===n.id?"is-drag-over-conv":""].filter(Boolean).join(" "),"data-folder-id":n.id,style:{background:f},draggable:!n.isDefault,onDragStart:e=>{if(n.isDefault)return void e.preventDefault();e.target.closest('button, input, textarea, select, [role="button"], [data-no-row-drag="true"]')?e.preventDefault():(te(n.id),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",n.id));},onDragEnd:()=>{te(null),re(null),ue.current=null;},onClick:()=>(e=>{p(g===e?null:e);})(n.id),onDragEnter:e=>{if(ee){if(n.isDefault||n.id===ee)return;e.preventDefault(),ue.current=n.id,re(n.id);}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.preventDefault(),de.current=n.id,le(n.id));}},onDragOver:e=>{if(ee){if(n.isDefault||n.id===ee)return;e.preventDefault(),e.dataTransfer.dropEffect="move",ue.current=n.id,re(n.id);}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.preventDefault(),e.dataTransfer.dropEffect="move",de.current=n.id,le(n.id));}},onDragLeave:e=>{const t=e.relatedTarget;if(!t||!e.currentTarget.contains(t))if(ee){const e=n.id;setTimeout(()=>{ue.current===e&&re(null);},0);}else if(oe){const e=n.id;setTimeout(()=>{de.current===e&&le(null);},0);}},onDrop:t=>{if(t.preventDefault(),ee){if(n.isDefault||n.id===ee)return;const t=i.filter(Oe).filter(e=>!e.isDefault),r=t.findIndex(e=>e.id===ee),o=t.findIndex(e=>e.id===n.id);if(-1===r||-1===o)return;const a=[...t],[s]=a.splice(r,1);a.splice(o,0,s);const l=i.filter(e=>!e.isDefault).filter(e=>!a.some(t=>t.id===e.id));e.reorderFolders([...a,...l].map(e=>e.id)),be(),te(null),re(null),ue.current=null;}else if(oe){const t=s[oe];t&&t.folderId!==n.id&&(e.moveConversation(oe,n.id),be()),ie(null),le(null),de.current=null;}},children:[ Le("div",{className:"conversations-folder-info",children:[m&&Ie("input",{type:"checkbox",className:"conversations-folder-checkbox",checked:Be(n.id),ref:e=>{e&&(e.indeterminate=(e=>{const t=ke(e),n=t.filter(e=>b.has(e.id));return n.length>0&&n.length((e,t)=>{const n=ke(e),r=new Set(b);t?n.forEach(e=>r.add(e.id)):n.forEach(e=>r.delete(e.id)),y(r);})(n.id,e.target.checked),onClick:e=>e.stopPropagation()}), Ie("span",{className:"conversations-folder-icon",style:{userSelect:"none"},children:n.icon}), Ie(up,{content:u,children:Ie("span",{className:"conversations-folder-name",children:S&&L?.folderMatches.has(n.id)?ux(u,S):u})})]}), Le("div",{className:"conversations-folder-controls",children:[ Le("span",{className:"conversations-folder-count",children:["(",d,")"]}), Ie("button",{className:"conversations-folder-menu-btn",style:{userSelect:"none",visibility:n.isDefault?"hidden":"visible",pointerEvents:n.isDefault?"none":"auto"},onClick:e=>{e.stopPropagation(),t?.(true),X({type:"folder",folder:n,anchorEl:e.currentTarget});},children:Ie(Mt,{size:20})})]})]}),l&&Ie("div",{className:"conversations-list","data-folder-id":n.id,children:(()=>{const e=ke(n.id);if(0===e.length) return Ie("div",{className:"conversations-list-empty",children:se("conversationsEmpty")});const r=Se[n.id]||lx,o=e.slice(0,r),i=e.length>r; return Le(_e,{children:[o.map(e=>Ie(gx,{conv:e,batchMode:m,isSelected:b.has(e.id),isNarrowLayout:F,searchQuery:S,searchResult:L,tagMap:ve,draggedConvId:oe,onConversationClick:Pe,onSelectionChange:y,onInteractionStateChange:t,onMenuChange:X,onDragStart:e=>{ie(e),de.current=null;},onDragEnd:()=>{ie(null),le(null),de.current=null;}},e.id)),i&&Ie("div",{className:"conversations-load-more-sentinel","data-folder-id":n.id,ref:e=>{const t=Ae.current.get(n.id);t&&t!==e&&qe.current?.unobserve(t),e?(Ae.current.set(n.id,e),qe.current?.observe(e)):Ae.current.delete(n.id);},style:{height:"1px",margin:0,padding:0}})]})})()})]},n.id)})}),m&&b.size>0&&Le("div",{className:"conversations-batch-bar",children:[ Ie("span",{className:"conversations-batch-info",children:se("batchSelected").replace("{n}",String(b.size))}), Le("div",{className:"conversations-batch-btns",children:[ Ie(up,{content:se("exportToClipboard"),children:Ie("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:async()=>{const t=Array.from(b)[0];await e.exportConversation(t,"clipboard");},children:Ie(Tt,{size:16})})}), Ie(up,{content:se("batchExport"),children:Ie("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:e=>{t?.(true),X({type:"export",anchorEl:e.currentTarget});},children:Ie(Ve,{size:16})})}), Ie(up,{content:se("batchMove"),children:Ie("button",{className:"conversations-batch-btn",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"folderSelect",convIds:Array.from(b)});},children:Ie(ze,{size:16})})}), Ie(up,{content:se("batchDelete"),children:Ie("button",{className:"conversations-batch-btn danger",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:()=>{t?.(true),Y({type:"confirm",title:se("batchDelete"),message:se("confirmDeleteSelectedConvs",{count:String(b.size)}),danger:true,onConfirm:async()=>{if(!x){Y(null),k(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversations(Array.from(b));if(0===t.localDeletedCount)return void Li(se("deleteError"));t.remoteAttemptedCount>0&&t.remoteFailedCount>0&&Li(`已删除 ${t.localDeletedCount} 个,本地成功,云端失败 ${t.remoteFailedCount} 个`),Me(),await be();}finally{k(false);}}}});},children:Ie(Bt,{size:16})})}), Ie(up,{content:se("batchExit"),children:Ie("button",{className:"conversations-batch-btn cancel",style:{padding:"4px 6px",minWidth:"auto",marginLeft:"4px"},onClick:Me,children:Ie(Re,{size:16})})})]})]})]}),"confirm"===Z?.type&&Ie(jw,{title:Z.title,message:Z.message,danger:Z.danger,onConfirm:Z.onConfirm,onCancel:()=>Y(null)}),"folder"===Z?.type&&Ie(Hw,{folder:Z.folder,onConfirm:async(t,n)=>{let r=null;if(Z.folder)await e.updateFolder(Z.folder.id,{name:t,icon:n});else {const o=await e.createFolder(t,n);o&&(r=o.id);}be(),Z.returnToSelect?Y({type:"folderSelect",conv:Z.returnToSelect.conv,convIds:Z.returnToSelect.convIds,activeFolderId:r||void 0}):Y(null);},onCancel:()=>Y(null)}),"rename"===Z?.type&&Ie(Ww,{title:se("conversationsRename"),currentValue:Z.conv.title,onConfirm:async t=>{await e.renameConversation(Z.conv.id,t),be(),Y(null);},onCancel:()=>Y(null)}),"folderSelect"===Z?.type&&Ie(Gw,{folders:i,excludeFolderId:Z.conv?.folderId,activeFolderId:Z.activeFolderId,onSelect:async t=>{if(Z.conv)await e.moveConversation(Z.conv.id,t);else if(Z.convIds){for(const n of Z.convIds)await e.moveConversation(n,t);Me();}be(),Y(null);},onCancel:()=>Y(null),onCreateFolder:()=>Y({type:"folder",returnToSelect:{conv:Z.conv,convIds:Z.convIds}})}),"tagManager"===Z?.type&&Ie(Qw,{tags:c,conv:Z.conv,onCancel:()=>Y(null),onCreateTag:async(t,n)=>e.createTag(t,n),onUpdateTag:async(t,n,r)=>e.updateTag(t,n,r),onDeleteTag:async t=>e.deleteTag(t),onSetConversationTags:async(t,n)=>e.setConversationTags(t,n),onRefresh:()=>be()}),"folder"===J?.type&&Ie(ix,{folder:J.folder,anchorEl:J.anchorEl,onClose:()=>X(null),onRename:()=>{X(null),Y({type:"folder",folder:J.folder});},onDelete:()=>{X(null);const t=dx(J.folder),n=cx(),r=se("conversationsDeleteConfirm",{folder:t,inbox:n});Y({type:"confirm",title:se("conversationsDelete"),message:"conversationsDeleteConfirm"===r?`Delete folder "${t}"? Conversations will be moved to ${n}.`:r,danger:true,onConfirm:async()=>{await e.deleteFolder(J.folder.id),be(),Y(null);}});}}),"conversation"===J?.type&&Ie(ax,{conversation:J.conv,anchorEl:J.anchorEl,onClose:()=>X(null),onRename:()=>{X(null),Y({type:"rename",conv:J.conv});},onTogglePin:async()=>{X(null),await e.togglePin(J.conv.id),be();},onSetTags:()=>{X(null),Y({type:"tagManager",conv:J.conv});},onMoveTo:()=>{X(null),Y({type:"folderSelect",conv:J.conv});},onExport:()=>{const e=J.conv,t=J.anchorEl;X({type:"export-conv",conv:e,anchorEl:t});},onDelete:()=>{X(null),Y({type:"confirm",title:se("conversationsDelete"),message:se("conversationsDeleteConvMsg",{title:J.conv.title}),danger:true,onConfirm:async()=>{if(!x){Y(null),k(true),await new Promise(e=>setTimeout(e,0));try{const t=await e.deleteConversation(J.conv.id);if(!t.localDeleted)return void Li(se("deleteError"));t.remoteAttempted&&!t.remoteSuccess&&Li(se("deleteConvRemoteError")),await be();}finally{k(false);}}}});}}),"export"===J?.type&&Ie(sx,{anchorEl:J.anchorEl,onClose:()=>X(null),onExportMarkdown:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"markdown");},onExportJSON:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"json");},onExportTXT:async()=>{X(null);const t=b.size>0?Array.from(b)[0]:e.siteAdapter.getSessionId();await e.exportConversation(t,"txt");}}),"export-conv"===J?.type&&Ie(sx,{anchorEl:J.anchorEl,onClose:()=>X(null),onExportMarkdown:async()=>{X(null),await e.exportConversation(J.conv.id,"markdown");},onExportJSON:async()=>{X(null),await e.exportConversation(J.conv.id,"json");},onExportTXT:async()=>{X(null),await e.exportConversation(J.conv.id,"txt");}})]})},gx=o.memo(({conv:e,batchMode:t,isSelected:n,isNarrowLayout:r,searchQuery:o,searchResult:i,tagMap:a,draggedConvId:s,onConversationClick:l,onSelectionChange:c,onInteractionStateChange:d,onMenuChange:u,onDragStart:h,onDragEnd:g})=>{const p=e.tagIds||[],m=r?1:2,f=p.map(e=>a.get(e)).filter(e=>!!e),b=f.slice(0,m),y=f.slice(m).length; return Le("div",{className:"conversations-item "+(s===e.id?"is-dragging":""),"data-id":e.id,draggable:true,onDragStart:t=>{h(e.id),t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.id);},onDragEnd:g,onClick:()=>l(e),children:[t&&Ie("input",{type:"checkbox",className:"conversations-item-checkbox",checked:n,onChange:()=>{},onClick:t=>{t.stopPropagation(),c(t=>{const n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n});}}), Ie("div",{className:"conversations-item-main",children:Le("div",{className:"conversations-item-headline",children:[ Ie(up,{content:e.title,triggerStyle:{flex:1,minWidth:0,overflow:"hidden",display:"block"},children:Le("span",{className:"conversations-item-title",style:{userSelect:"none"},children:[e.pinned&&Ie(Ot,{size:12,color:"var(--gh-primary, #3b82f6)",style:{display:"inline-block",marginRight:"4px",verticalAlign:"middle"}}),o&&i?.conversationMatches.has(e.id)?ux(e.title||"无标题",o):e.title||"无标题"]})}),p.length>0&&Le("div",{className:"conversations-tag-list",children:[b.map(e=>Ie("span",{className:"conversations-tag",style:{backgroundColor:e.color},children:e.name},e.id)),y>0&&Ie(up,{content:Ie("div",{className:"conversations-hidden-tags-tooltip",children:f.map(e=>Le("div",{className:"conversations-hidden-tag-item",children:[ Ie("span",{className:"conversations-hidden-tag-dot",style:{backgroundColor:e.color}}), Ie("span",{children:e.name})]},e.id))}),delay:120,triggerStyle:{display:"inline-flex"},children:Le("span",{className:"conversations-tag conversations-tag-more",children:["+",y]})})]})]})}), Ie("div",{className:"conversations-item-meta",children:Ie("button",{className:"conversations-item-menu-btn",title:se("more"),onClick:t=>{t.stopPropagation(),d?.(true),u({type:"conversation",conv:e,anchorEl:t.currentTarget});},children:Ie(Mt,{size:20})})})]})});function px(e,t){if(e<1e3)return e.toString();if("zh-CN"===t||"zh-TW"===t){if(e>=1e4)return (e/1e4).toFixed(1).replace(/\.0$/,"")+"w";if(e>=1e3)return (e/1e3).toFixed(1).replace(/\.0$/,"")+"k"}return e>=1e3?e>=1e6?(e/1e6).toFixed(1).replace(/\.0$/,"")+"m":(e/1e3).toFixed(1).replace(/\.0$/,"")+"k":e.toString()}const mx=e=>{let t=0;for(const n of e)t+=1,n.children.length>0&&(t+=mx(n.children));return t},fx=e=>"conversation"===e.kind?se("outlineSourceConversation"):"document"===e.kind?se("outlineSourceDocument"):e.label,bx=(e,t,n,r,o,i)=>{const a={},s={},l=new Map,c=e=>{const t=l.get(e.index);if(void 0!==t)return t;let n=!!e.isBookmarked;if(!n&&e.children&&e.children.length>0)for(const r of e.children)if(c(r)){n=true;break}return l.set(e.index,n),n},d=(e,l,u,h,g)=>{a[e.index]=l;const p=c(e);let m;if(i)if(p||g){const t=!r||e.isMatch||e.hasMatchedDescendant;m=!u&&t;}else m=false;else {const i=e.relativeLevel===n,a=e.relativeLevel<=t||h;if(i)m=!r||(e.isMatch||e.hasMatchedDescendant);else {const t=!r||e.isMatch||e.hasMatchedDescendant||h;m=r&&!o?t&&!u:r&&o?t&&a&&!u:a&&!u;}u&&(m=false);}e.forceVisible&&(m=true),s[e.index]=m;const f=e.collapsed||u,b=e.forceExpanded||h,y=g||e.isBookmarked&&!(e=>!(!e.children||0===e.children.length)&&e.children.some(c))(e);e.children&&e.children.length>0&&e.children.forEach(t=>d(t,e.index,f,b,y));};return e.forEach(e=>d(e,null,false,false,false)),{parentMap:a,visibleMap:s}},yx=({node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,setItemRef:i,visibleMap:a,searchQuery:s,extractUserQueryText:l})=>{const c=e.children&&e.children.length>0,d=c&&!e.collapsed,u=a[e.index]??true,h=["outline-item",`outline-level-${e.relativeLevel}`,e.isUserQuery?"user-query-node":"",e.isGhost?"ghost-node":"",u?"":"outline-hidden"].filter(Boolean).join(" "),[g,p]=z(false),[m,f]=z(false); return Le(_e,{children:[ Ie(up,{content:e.wordCount&&e.wordCount>0?Le("div",{children:[e.text, Le("div",{style:{fontSize:"12px",opacity:.8,marginTop:"2px"},children:["(",px(e.wordCount,ce())," ",se("words"),")"]})]}):e.text,disabled:m,triggerStyle:{width:"100%",display:"block"},triggerClassName:u?"":"outline-hidden",delay:500,children:Le("div",{className:h,"data-index":e.index,"data-level":e.relativeLevel,ref:t=>i(e.index,t),onClick:()=>n(e),children:[ Ie("span",{className:"outline-item-toggle "+(c?d?"expanded":"":"invisible"),onClick:n=>{c&&(n.stopPropagation(),t(e));},children:Ie(It,{size:16,style:{transform:"rotate(-90deg)"}})}),e.isUserQuery&&Le("span",{className:"user-query-badge",children:[ Ie("span",{className:"user-query-badge-icon",children:"💬"}), Ie("span",{className:"user-query-badge-number",children:e.queryIndex})]}), Ie("span",{className:"outline-item-text "+(e.isGhost?"ghost-text":""),children:(()=>{if(s&&e.isMatch)try{const t=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(${t})`,"gi"),r=e.text.split(n); return Ie(_e,{children:r.map((e,t)=>e.toLowerCase()===s.toLowerCase()?Ie("mark",{style:{backgroundColor:"var(--gh-search-highlight-bg)",color:"inherit",padding:0,borderRadius:"2px"},children:e},t):e)})}catch{return e.text}return e.text})()}), Ie("span",{className:"outline-item-bookmark-wrapper "+(e.isBookmarked?"active":""),children:Ie(up,{content:e.isBookmarked?se("removeBookmark"):se("addBookmark"),children:Ie("span",{className:"outline-item-bookmark-btn "+(e.isBookmarked?"active":""),onClick:t=>o(t,e),onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),children:Ie(gt,{size:14,filled:e.isBookmarked,color:e.isBookmarked?"#f59e0b":"currentColor"})})})}), Ie(up,{content:se("copy"),children:Ie("span",{className:"outline-item-copy-btn",onClick:async t=>{t.stopPropagation(),t.preventDefault();let n=e.text;if(e.element&&e.element.isConnected)if(e.isUserQuery&&l){const t=l(e.element);t&&(n=t);}else {const t=e.element.textContent;t&&(n=t.trim());}try{await navigator.clipboard.writeText(n),p(!0),setTimeout(()=>p(!1),1500);}catch(r){console.error("[DEBUG] Clipboard API failed, trying fallback:",r);try{const e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.left="-9999px",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),p(!0),setTimeout(()=>p(!1),1500);}catch(o){console.error("[DEBUG] Fallback copy also failed:",o);}}},onMouseEnter:()=>f(true),onMouseLeave:()=>f(false),children:g? Ie(Kt,{size:14,color:"#10b981"}): Ie(Tt,{size:14})})})]})}),c&&e.children.map((e,c)=>Ie(yx,{node:e,onToggle:t,onClick:n,onCopy:r,onToggleBookmark:o,setItemRef:i,visibleMap:a,searchQuery:s,extractUserQueryText:l},`${e.level}-${e.text}-${c}`))]})},vx=({manager:e,onJumpBefore:t,isCodexOpen:n=false})=>{const{settings:r}=Ai(),i=r,a=o.useMemo(()=>lr(),[]),s=se("shortcutNotSet"),l=o.useMemo(()=>Xw(i.shortcuts?.keybindings,a,s),[i.shortcuts?.keybindings,i.language,a,s]),c=e.getState(),[d,u]=z(c.tree),[h,g]=z(e.getSearchQuery()),[p,m]=z(c.isAllExpanded),[f,b]=z(c.includeUserQueries),[y,v]=z("bottom"),[w,x]=z(c.expandLevel??6),[k,S]=z(c.levelCounts),[C,E]=z(c.displayLevel),[T,M]=z(c.minRelativeLevel),[I,L]=z(c.searchLevelManual),[N,D]=z(c.matchCount),[R,B]=z(c.bookmarkMode),[O,F]=z(c.sources),[$,U]=z(c.activeSourceId),j=P(null),H=P(null),W=P(0),G=P(false),Q=P(null),V=P(null),K=P(new Map),Z=P(0),Y=P(null),J=P(0),X=P(false),ee=P(null),te=P({parentMap:{},visibleMap:{},hasData:false});_(()=>(e.setActive(true),()=>{e.setActive(false);}),[e]),_(()=>{const e=()=>{H.current&&(H.current.focus(),H.current.select());};return window.addEventListener("ophel:searchOutline",e),window.__ophelPendingSearchOutline&&(delete window.__ophelPendingSearchOutline,setTimeout(e,100)),()=>{window.removeEventListener("ophel:searchOutline",e);}},[]),_(()=>{const t=()=>{const t=e.getState(),n=mx(t.tree),o=W.current;"latest"===(r?.features?.outline?.followMode||"current")&&n>o&&(G.current=true),u([...t.tree]),g(e.getSearchQuery()),m(t.isAllExpanded),x(t.expandLevel??6),S(t.levelCounts||{}),b(t.includeUserQueries),E(t.displayLevel),M(t.minRelativeLevel),L(t.searchLevelManual),D(t.matchCount),B(t.bookmarkMode),F(t.sources),U(t.activeSourceId),W.current=n;};return t(),e.subscribe(t)},[e,r?.features?.outline?.followMode]),_(()=>{if(G.current&&j.current){const e=j.current;requestAnimationFrame(()=>{e.scrollTo({top:e.scrollHeight,behavior:"smooth"});}),G.current=false;}},[d]);const ne=A((...e)=>{if(0===e.length)return;const t=t=>{t.classList.remove(...e);};K.current.forEach(t);const n=e.map(e=>`.outline-item.${e}`).join(", ");j.current?.querySelectorAll(n).forEach(t);},[]),re=A(e=>{ne(e);},[ne]),oe=A(e=>{const t=null!==e&&K.current.get(e)||null;K.current.forEach(e=>{e!==t&&e.classList.remove("sync-highlight","sync-highlight-visible");}),j.current?.querySelectorAll(".outline-item.sync-highlight, .outline-item.sync-highlight-visible").forEach(e=>{e!==t&&e.classList.remove("sync-highlight","sync-highlight-visible");}),t&&(t.classList.remove("sync-highlight-visible"),t.classList.add("sync-highlight"));},[]),ie=A(e=>{Q.current=e;},[]),ae=A(e=>{oe(e),V.current=e;},[oe]),le=A((e,t)=>{const n=K.current;t?(n.set(e,t),e!==V.current&&t.classList.remove("sync-highlight","sync-highlight-visible"),e===V.current&&oe(e)):n.delete(e);},[oe]),ce=A(t=>{J.current+=1;const n=Y.current;n&&(clearTimeout(n.timer),Y.current=null),re("highlight"),t?.clearForceVisible&&e.clearForceVisible();},[e,re]),de=A(e=>{if(null===e)return null;const{parentMap:t,visibleMap:n,hasData:r}=te.current;if(!r)return e;let o=e;for(;null!=o;){if(n[o])return o;o=t[o];}return null},[]),ue=q(()=>bx(d,C,T,h,I,R),[d,C,T,h,I,R]),{parentMap:he,visibleMap:ge}=ue,pe=q(()=>O.filter(e=>e.available),[O]),me=q(()=>{const e=t=>{for(const n of t){if(ge[n.index])return true;if(n.children&&n.children.length>0&&e(n.children))return true}return false};return e(d)},[d,ge]);te.current={parentMap:he,visibleMap:ge,hasData:d.length>0},_(()=>{const e=de(Q.current);ae(e);},[he,ge,d.length,de,ae]),_(()=>{if("current"!==(r?.features?.outline?.followMode||"current"))return ie(null),void ae(null);let t,n=null,o=0,i=0,a=null,s=null,l=null;const c=new Map,d=()=>{e.markScrollPositionsStale();},u=t=>{if(c.has(t))return;const n=new MutationObserver(()=>{s||(s=setTimeout(()=>{s=null;const t="undefined"!=typeof window?window.requestIdleCallback?.bind(window):void 0;if(t){if(null!==l)return;l=t(()=>{l=null,e.markScrollPositionsStale();},{timeout:500});}else e.markScrollPositionsStale();},300));});n.observe(t,{childList:true,subtree:true,characterData:true}),c.set(t,n);},h=()=>{if(!n)return;const t=n.scrollTop,r=n.clientHeight,o=n.scrollHeight;o!==i&&(i=o,e.markScrollPositionsStale());const a=e.findVisibleItemIndex(t,r);if(null===a)return ie(null),void ae(null);ie(a);const s=de(a);ae(s),null!==s&&requestAnimationFrame(()=>{if(X.current)return;const e=j.current;if(!e)return;const t=K.current.get(s)||null;if(!t)return;const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();if(r.topn.bottom){const t=r.top-n.top-n.height/2+r.height/2;e.scrollBy({top:t,behavior:"instant"});}});},g=()=>{const r=e.getScrollContainer();r?(n=r,i=r.scrollHeight,n.addEventListener("scroll",h,{passive:true}),window.addEventListener("resize",d,{passive:true}),(e=>{try{u(e);}catch(t){console.warn("[OutlineTab] Failed to attach MutationObserver:",t);}})(r),"undefined"!=typeof ResizeObserver&&(a=new ResizeObserver(()=>{i=n?.scrollHeight||0,e.markScrollPositionsStale();}),a.observe(n)),h()):o<20?(o++,t=setTimeout(g,300)):console.warn("[OutlineTab] Failed to find scroll container after retries");};return g(),()=>{if(n&&n.removeEventListener("scroll",h),window.removeEventListener("resize",d),s&&clearTimeout(s),null!==l){const e="undefined"!=typeof window?window.cancelIdleCallback?.bind(window):void 0;e&&e(l),l=null;}c.forEach(e=>e.disconnect()),c.clear(),a&&(a.disconnect(),a=null),t&&clearTimeout(t);}},[e,d.length,r?.features?.outline?.followMode,de,ie,ae]),_(()=>{const e=j.current;if(!e)return;const t=()=>{const t=e.scrollTop+e.clientHeight>=e.scrollHeight-10;v(t?"top":"bottom");};return e.addEventListener("scroll",t),t(),()=>e.removeEventListener("scroll",t)},[]),_(()=>{const e=j.current;if(!e)return;const t=()=>{X.current=true,ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{X.current=false;},1500);};return e.addEventListener("wheel",t,{passive:true}),()=>{e.removeEventListener("wheel",t),ee.current&&clearTimeout(ee.current);}},[]);const fe=A(t=>{e.toggleNode(t);},[e]),be=A(async n=>{const r=++Z.current;ce({clearForceVisible:true}),ae(de(Q.current));let o=n.element,i=false;if(!o||!o.isConnected){t&&(await t(),i=true);const r=await e.resolveOutlineTarget(n,n.queryIndex);r&&(o=r,n.element=o);}if(r===Z.current)if(o&&o.isConnected){if(t&&!i&&await t(),r!==Z.current)return;if(e.scrollToOutlineTarget(o),ie(n.index),ae(de(n.index)),void 0!==document.documentElement.dataset.ophelPositionLock){const t=e.getScrollContainer();t&&(document.documentElement.dataset.ophelPositionLock=String(t.scrollTop));}o.classList.add("outline-highlight"),setTimeout(()=>o?.classList.remove("outline-highlight"),2e3);}else if(n.isGhost&&void 0!==n.scrollTop){const t=e.getScrollContainer();t&&(t.scrollTo({top:n.scrollTop,behavior:"smooth"}),ie(n.index),ae(de(n.index)),Li(se("bookmarkContentMissing"),3e3));}},[ce,de,e,t,ie,ae]),ye=A((e,t)=>{e.stopPropagation();const n=t.text;navigator.clipboard.writeText(n);},[]),ve=A(t=>e.extractUserQueryText(t),[e]),we=A(t=>{e.setSearchQuery(t.target.value);},[e]),xe=A(()=>{e.setSearchQuery("");},[e]),ke=A(()=>{p?e.collapseAll():e.expandAll();},[e,p]),Se=A((t,n)=>{t.stopPropagation(),e.toggleBookmark(n);},[e]),Ce=A(()=>{e.toggleBookmarkMode();},[e]),Ae=A(()=>{e.toggleGroupMode();},[e]),Ee=A(()=>{const e=j.current;e&&("bottom"===y?e.scrollTo({top:e.scrollHeight,behavior:"smooth"}):e.scrollTo({top:0,behavior:"smooth"}));},[y]),Te=A(()=>{const t=e.getScrollContainer();if(!t)return;h&&(e.setSearchQuery(""),g(""));const n=e=>{const t=[];return e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&t.push(...n(e.children));}),t},r=n(d),o=t.getBoundingClientRect(),i=o.top,a=o.bottom;let s=null;for(const e of r){if(!e.element||!e.element.isConnected)continue;const t=e.element.getBoundingClientRect();if(t.top>=i&&t.topi){s=e;break}}if(!s){let e=1/0;for(const t of r){if(!t.element||!t.element.isConnected)continue;const n=t.element.getBoundingClientRect(),r=Math.abs(n.top-i);r{if(l!==J.current)return;const t=j.current;if(!t)return;const n=t.querySelector(`.outline-item[data-index="${s.index}"]`);if(!n)return;n.scrollIntoView({behavior:"instant",block:"center"}),n.classList.add("highlight");const r=setTimeout(()=>{n.classList.remove("highlight"),e.clearForceVisible(),Y.current=null;},3e3);Y.current={element:n,timer:r};},50);},[d,h,e,ce]);_(()=>()=>{ce({clearForceVisible:true});},[ce]);const Me=A(t=>{e.setLevel(t);},[e]);return _(()=>{const e=()=>{window.__ophelPendingLocateOutline=false,Te();};return window.__ophelPendingLocateOutline&&setTimeout(()=>{e();},100),window.addEventListener("ophel:locateOutline",e),()=>{window.removeEventListener("ophel:locateOutline",e);}},[Te]),Le("div",{className:"gh-outline-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ Le("div",{className:"outline-fixed-toolbar",style:{padding:"8px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",flexDirection:"column",gap:"8px",backgroundColor:"var(--gh-bg, #fff)"},children:[ Le("div",{style:{display:"flex",gap:"4px",alignItems:"center"},children:[ Le("div",{style:{display:"flex",gap:"2px"},children:[ Ie(up,{content:se(f?"outlineOnlyUserQueries":"outlineShowUserQueries"),children:Ie("button",{onClick:Ae,className:"outline-toolbar-btn "+(f?"active-subtle":""),children:Ie(Vt,{size:15})})}), Ie(up,{content:se("bookmarkMode"),children:Ie("button",{onClick:Ce,className:"outline-toolbar-btn "+(R?"active-subtle":""),children:Ie(gt,{size:16,filled:R,color:"currentColor"})})}), Ie(up,{content:se(R?"bookmarkModeDisabled":p?"outlineCollapseAll":"outlineExpandAll"),children:Ie("button",{onClick:R?void 0:ke,disabled:R,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:R?"var(--gh-text-disabled, #9ca3af)":"var(--gh-text, #374151)",cursor:R?"not-allowed":"pointer",opacity:R?.5:1,display:"flex",alignItems:"center",justifyContent:"center"},children:Ie(p?Xe:Je,{size:16})})}), Ie(up,{content:se("outlineLocateCurrent"),children:Ie("button",{onClick:Te,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:"var(--gh-text, #374151)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:Ie(et,{size:16})})}), Ie(up,{content:se("bottom"===y?"outlineScrollBottom":"outlineScrollTop"),children:Ie("button",{onClick:Ee,style:{width:"26px",height:"26px",padding:0,border:"1px solid var(--gh-input-border, #d1d5db)",borderRadius:"4px",backgroundColor:"var(--gh-bg, #fff)",color:"var(--gh-text, #374151)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"14px"},children:Ie("bottom"===y?nt:tt,{size:16})})})]}), Le("div",{className:"outline-search-wrapper",style:{flex:1,position:"relative",display:"flex",alignItems:"center"},children:[ Ie("input",{ref:H,type:"text",className:"outline-search-input",placeholder:se("outlineSearch"),value:h,onChange:we,style:{width:"100%",padding:"4px 24px 4px 8px",borderRadius:"4px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"12px",boxSizing:"border-box",height:"26px",backgroundColor:"var(--gh-input-bg, #fff)",color:"var(--gh-text, #374151)"}}),h&&Ie("button",{className:"outline-search-clear",onClick:xe,style:{position:"absolute",right:"4px",background:"none",border:"none",color:"var(--gh-text-tertiary, #9ca3af)",cursor:"pointer",fontSize:"14px",padding:0,display:"flex",alignItems:"center",justifyContent:"center"},children:Ie(Re,{size:14})})]})]}), Ie("div",{className:"outline-level-slider-container",style:{padding:"0 4px"},children:Le("div",{className:"outline-level-dots",style:{display:"flex",justifyContent:"space-between",position:"relative",padding:"6px 0",alignItems:"center"},children:[ Ie("div",{className:"outline-level-line-bg",style:{position:"absolute",top:"50%",left:"4px",right:"4px",height:"4px",background:"var(--gh-border, #e5e7eb)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px"}}), Ie("div",{className:"outline-level-progress",style:{position:"absolute",top:"50%",left:"4px",height:"4px",background:R?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)",zIndex:0,transform:"translateY(-50%)",borderRadius:"2px",width:`calc((${w} / 6) * (100% - 8px))`,transition:"width 0.2s ease"}}),[0,1,2,3,4,5,6].map(e=>{let t="";t=R?se("bookmarkModeDisabled"):0===e?se(f?"outlineOnlyUserQueries":"outlineCollapseAll"):`H${e}: ${k[e]||0}`;const n=e<=w; return Ie(up,{content:t,children:Ie("div",{className:`outline-level-dot ${n?"active":""} ${R?"disabled":""}`,"data-level":e,onClick:R?void 0:()=>Me(e),style:{width:"14px",height:"14px",borderRadius:"50%",backgroundColor:n?R?"var(--gh-text-disabled, #9ca3af)":"var(--gh-primary, #3b82f6)":"var(--gh-slider-dot-bg, #d1d5db)",border:n?"2px solid var(--gh-bg, #fff)":"none",zIndex:1,cursor:R?"not-allowed":"pointer",position:"relative",transition:"all 0.2s ease",boxSizing:"border-box",boxShadow:n?R?"0 0 0 1px var(--gh-text-disabled, #9ca3af)":"0 0 0 1px var(--gh-primary, #3b82f6)":"none",opacity:R?.5:1}})},e)})]})})]}),h&&Le("div",{className:"outline-result-bar",style:{textAlign:"center",padding:"6px 8px",margin:"0 8px 0 8px",color:"var(--gh-border-active)",fontSize:"13px",background:N>0?"var(--gh-folder-bg-default)":"transparent",borderRadius:"4px",border:0===N?"1px dashed var(--gh-border, #e5e7eb)":"none",flexShrink:0},children:[N," ",se("outlineSearchResult")]}),pe.length>1&&!h&&Ie("div",{className:"outline-source-switch","aria-label":se("outlineSourceSwitchLabel"),children:pe.map(t=>Ie("button",{type:"button",className:"outline-source-switch-option "+($===t.id?"active":""),onClick:()=>e.setActiveSource(t.id),children:Ie("span",{children:fx(t)})},t.id))}), Ie("div",{ref:j,className:`gh-outline-tree-container gh-panel-bookmark-mode-${r?.features?.outline?.panelBookmarkMode||"always"}`,style:{flex:1,overflowY:"auto",padding:h?"0 8px 8px 8px":"8px"},children:(()=>{const e=t=>t.some(t=>t.isBookmarked||t.children&&t.children.length>0&&e(t.children)),t=e(d),r=0===d.length,o=!h&&(r||!me),i=se(f&&0===C?"outlineEmptyDescUserQueryOnly":"outlineEmptyDescDefault"),a=i.indexOf(","),s=i.indexOf(",");let c=-1;c=a>=0&&s>=0?Math.min(a,s):Math.max(a,s);const u=c>=0?i.slice(0,c).trim():i,g=c>=0?i.slice(c+1).trim():"";return !R||t||h?o?Le("div",{className:"outline-empty-state",children:[ Ie("div",{className:"outline-empty-state-icon","aria-hidden":"true",children:Ie(je,{size:20,color:"currentColor"})}), Ie("div",{className:"outline-empty-state-title",children:se("outlineEmpty")}), Le("div",{className:"outline-empty-state-desc",children:[ Ie("span",{className:"outline-empty-state-desc-line",children:u}),g&&Ie("span",{className:"outline-empty-state-desc-line",children:g})]}), Ie("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!n&&Ie(Yw,{isOpen:true,onClose:()=>{},tips:l,isStatic:true})})]}):Ie("div",{className:"outline-list",children:d.map((e,t)=>Ie(yx,{node:e,onToggle:fe,onClick:be,onCopy:ye,onToggleBookmark:Se,setItemRef:le,visibleMap:ge,searchQuery:h,extractUserQueryText:ve},`${e.level}-${e.text}-${t}`))}):Le("div",{className:"outline-empty-state",children:[ Ie("div",{className:"outline-empty-state-icon",style:{background:"rgba(245, 158, 11, 0.1)",color:"#f59e0b"},"aria-hidden":"true",children:Ie(gt,{size:20,filled:true,color:"#f59e0b"})}), Ie("div",{className:"outline-empty-state-title",children:se("outlineNoBookmarks")}), Ie("div",{className:"outline-empty-state-desc",children:se("outlineAddBookmarkHint")}), Ie("div",{style:{marginTop:"32px",width:"100%",display:"flex",justifyContent:"center"},children:!n&&Ie(Yw,{isOpen:true,onClose:()=>{},tips:l,isStatic:true})})]})})()})]})},wx=({variables:e,onConfirm:t,onCancel:n})=>{const[r,o]=z(e.map(e=>({name:e.raw,value:e.options?e.options[0]:e.defaultValue??""}))),i=P(null);_(()=>{setTimeout(()=>{i.current?.focus();},100);},[]);const a=()=>{const e={};r.forEach(t=>{e[t.name]=t.value;}),t(e);},s=(e,t)=>{o(n=>{const r=[...n];return r[e]={...r[e],value:t},r});}; return Ie(Iw,{onClose:n,closeOnOverlayClick:false,dialogClassName:"prompt-modal-content",dialogStyle:{width:"400px",maxWidth:"90%",maxHeight:"80vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)",animation:"slideUp 0.2s ease-out",padding:0},children:Le("div",{onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),a()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),n());},style:{display:"flex",flexDirection:"column",flex:1,minHeight:0},children:[ Le("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("h3",{style:{margin:0,fontSize:"16px",fontWeight:600,color:"var(--gh-text, #374151)"},children:se("promptVariableTitle")}), Ie("button",{onClick:n,style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:Ie(Re,{size:18})})]}), Ie("div",{style:{padding:"16px",overflowY:"auto",flex:1},children:e.map((e,t)=>Le("div",{style:{marginBottom:"16px",display:"flex",flexDirection:"column",gap:"6px"},children:[ Ie("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",wordBreak:"break-all"},children:e.name}),e.options? Ie("select",{value:r[t]?.value??"",onChange:e=>s(t,e.target.value),style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",cursor:"pointer",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";},children:e.options.map(e=>Ie("option",{value:e,children:e},e))}): Ie("input",{ref:0===t?i:void 0,type:"text",value:r[t]?.value??"",onChange:e=>s(t,e.target.value),placeholder:e.defaultValue?`${se("promptVariablePlaceholder")} (${se("default")}: ${e.defaultValue})`:se("promptVariablePlaceholder"),style:{width:"100%",padding:"8px 12px",borderRadius:"6px",border:"1px solid var(--gh-input-border, #d1d5db)",fontSize:"14px",outline:"none",background:"var(--gh-input-bg, white)",color:"var(--gh-text, #374151)",boxSizing:"border-box",transition:"border-color 0.2s, box-shadow 0.2s"},onFocus:e=>{e.target.style.borderColor="var(--gh-primary, #4285f4)",e.target.style.boxShadow="0 0 0 2px rgba(66, 133, 244, 0.1)";},onBlur:e=>{e.target.style.borderColor="var(--gh-input-border, #d1d5db)",e.target.style.boxShadow="none";}})]},e.raw))}), Le("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ Ie("button",{onClick:n,style:{padding:"8px 16px",borderRadius:"6px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",color:"var(--gh-text, #374151)",fontSize:"14px",cursor:"pointer"},children:se("cancel")}), Ie("button",{onClick:a,style:{padding:"8px 16px",borderRadius:"6px",border:"none",background:"var(--gh-primary, #4285f4)",color:"white",fontSize:"14px",cursor:"pointer",fontWeight:500},children:se("confirm")})]})]})})},xx=e=>{const t=e.indexOf(":");if(-1===t)return {raw:e,name:e};const n=e.substring(0,t),r=e.substring(t+1);if(r.includes("|")){return {raw:e,name:n,options:r.split("|").filter(e=>e.length>0)}}return {raw:e,name:n,defaultValue:r}},kx=e=>{const t=/\{\{([^\s{}]+)\}\}/g,n=new Set,r=[];let o;for(;null!==(o=t.exec(e));){const e=o[1];n.has(e)||(n.add(e),r.push(xx(e)));}return r},Sx=e=>e.replace(/\r\n?/g,"\n"),Cx=e=>Sx(e).split("\n").map(e=>e.trim()).filter(Boolean),Ax=({manager:e,adapter:t,onPromptSelect:n,selectedPromptId:r})=>{const o=Ai(e=>e.settings.features?.prompts?.doubleClickToSend??false),i=Ai(e=>e.settings.features?.prompts?.submitShortcut??"enter"),a=Ai(e=>e.settings.features?.prompts?.promptQueue??false),[s,l]=z([]),[c,d]=z([]),[u,h]=z(Co),[g,p]=z(""),[m,f]=z(false),[b,y]=z(null),[v,w]=z(false),[x,k]=z({show:false,title:"",message:"",onConfirm:()=>{}}),[S,C]=z({show:false,title:"",defaultValue:"",onConfirm:()=>{}}),[E,T]=z(null),M=P(null),I=P(null),[L,N]=z({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),[D,q]=z({show:false,prompts:[]}),[R,B]=z(false),[O,F]=z({show:false,prompt:null}),$=P(null),U=P(null),j=P(null),[H,W]=z(null),[G,Q]=z(null),V=P(null),K=P(null),Z=A(()=>{const t=e.getPrompts(),n=e.getCategories();l(t),d(n),h(e=>{if(e===Co)return e;if(!n.includes(e))return Co;return t.some(t=>t.category===e)?e:Co});},[e]),Y=A((t,n=false)=>{const r=e.getPrompts().find(e=>e.id===t);if(!r)return false;const o=kx(r.content);return 0!==o.length&&(N({show:true,prompt:r,variables:o,submitAfterInsert:n,enqueueAfterResolve:false,enqueueSplitByLine:false}),true)},[e]),J=A(t=>{const r=e.getPrompts().find(e=>e.id===t);return !!r&&(h(Co),p(""),n?.(null),W(r.id),true)},[e,n]);_(()=>{const e=window,t=t=>{const r=t.detail,o=r?.promptId;if(!o)return;Y(o,Boolean(r?.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);};window.addEventListener("ophel:openPromptVariableDialog",t);const r=e.__ophelPendingPromptVariableDialog;if(r?.promptId){Y(r.promptId,Boolean(r.submitAfterInsert))&&(n?.(null),e.__ophelPendingPromptVariableDialog=null);}return ()=>{window.removeEventListener("ophel:openPromptVariableDialog",t);}},[n,Y]),_(()=>{const e=window,t=t=>{const n=t.detail,r=n?.promptId;if(!r)return;J(r)&&(e.__ophelPendingLocatePrompt=null);};window.addEventListener("ophel:locatePrompt",t);const n=e.__ophelPendingLocatePrompt;if(n?.promptId){J(n.promptId)&&(e.__ophelPendingLocatePrompt=null);}return ()=>{window.removeEventListener("ophel:locatePrompt",t);}},[J]),_(()=>{Z();},[Z]),_(()=>()=>{null!==$.current&&window.clearTimeout($.current),null!==U.current&&window.clearTimeout(U.current);},[]),_(()=>{R&&V.current&&fp(V.current,{size:14,color:"#6b7280"});},[R,b?.content]),_(()=>{O.show&&K.current&&fp(K.current,{size:14,color:"#6b7280"});},[O.show,O.prompt]);const X=(e,t,n)=>{k({show:true,title:e,message:t,onConfirm:n});},ee=async(e,t=false)=>{const n=kx(e.content);if(n.length>0)N({show:true,prompt:e,variables:n,submitAfterInsert:t,enqueueAfterResolve:false,enqueueSplitByLine:false});else {if(t)return void(await ne(e,e.content));await te(e,e.content);}},te=async(t,r)=>{await e.insertPrompt(r)?(e.updateLastUsed(t.id),n?.(t),Li(`${se("inserted")}: ${t.title}`)):Li(se("insertFailed"));},ne=async(r,o)=>{const a=await(async({adapter:e,manager:t,content:n,submitShortcut:r})=>{const o=n.trim();if(!o)return {status:"insert-failed"};const i=Ai.getState().settings.features?.prompts?.promptQueue??false;return e?.isGenerating()&&i?(Pv.getState().enqueue(o),{status:"queued",count:1}):await t.insertPrompt(o)?await t.submitPrompt(r)?{status:"sent"}:{status:"send-failed"}:{status:"insert-failed"}})({adapter:t,manager:e,content:o,submitShortcut:i});if("insert-failed"!==a.status){if(e.updateLastUsed(r.id),"send-failed"===a.status)return Li(se("promptSendFailed")),void n?.(r);n?.(null),"queued"!==a.status?Li(`${se("promptSent")}: ${r.title}`):Li(se("promptQueued",{count:String(a.count)}),2500);}else Li(se("insertFailed"));},re=(t,n,r=false)=>{const o=(({content:e,splitByLine:t=false,context:n})=>{if(!Ai.getState().settings.features?.prompts?.promptQueue)return {status:"disabled"};const r=t?Cx(e):[e.trim()].filter(Boolean);if(0===r.length)return {status:"empty"};const o=Pv.getState().enqueueMany(r);return 0===o.length?{status:"empty"}:{status:"queued",count:o.length}})({content:n,splitByLine:r,context:{}});"disabled"!==o.status?"empty"!==o.status?(e.updateLastUsed(t.id),Li(se("promptQueued",{count:String(o.count)}),2500)):Li(se("promptEnqueueEmpty"),2500):Li(se("promptQueueEnableHint"),3e3);},oe=(e,t=false)=>{if(!a)return void Li(se("promptQueueEnableHint"),3e3);const n=kx(e.content);n.length>0?N({show:true,prompt:e,variables:n,submitAfterInsert:false,enqueueAfterResolve:true,enqueueSplitByLine:t}):re(e,e.content,t);},ie=()=>{const t=D.prompts;e.setPrompts(t),Z(),q({show:false,prompts:[]}),Li(se("promptImportSuccess").replace("{count}",t.length.toString()));},ae=()=>{const t=D.prompts,n=e.getPrompts(),r=new Set(n.map(e=>e.id)),o=t.filter(e=>r.has(e.id)),i=t.filter(e=>!r.has(e.id));o.forEach(t=>{e.updatePrompt(t.id,{title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),i.forEach(t=>{e.addPrompt({title:t.title,content:t.content,category:t.category,pinned:t.pinned});}),Z(),q({show:false,prompts:[]});const a=`已合并:更新 ${o.length} 个,新增 ${i.length} 个`;Li(se("promptMergeSuccess")?.replace("{updated}",o.length.toString()).replace("{added}",i.length.toString())||a);},le=async()=>{if(!b?.title||!b?.content)return void Li(se("fillTitleContent"));const t=b.category||se("uncategorized");let n=false;if(b.id){const r=s.find(e=>e.id===b.id),o=r?.category;if(o&&o!==t&&u===o){0===s.filter(e=>e.category===o&&e.id!==b.id).length&&(n=true);}await e.updatePrompt(b.id,{title:b.title,content:b.content,category:t}),Li(se("promptUpdated")),n&&h(t);}else await e.addPrompt({title:b.title,content:b.content,category:t}),Li(se("promptAdded"));ce(),Z();},ce=A(()=>{f(false),y(null);},[]),de=A(()=>{w(false);},[]),ue=A(()=>{k(e=>({...e,show:false}));},[]),he=A(()=>{C(e=>({...e,show:false}));},[]),ge=A(()=>{F({show:false,prompt:null});},[]),pe=A(()=>{q({show:false,prompts:[]});},[]),me=A(()=>{N({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false});},[]),fe=A(()=>{Q(null);},[]),be=e=>{if(e)y({...e});else {const e=u===Co||u===Ao?c[0]||se("uncategorized"):u;y({title:"",content:"",category:e});}f(true);},ye=(t,n)=>{var r;n.stopPropagation(),n.preventDefault(),r=se("newCategoryName"),C({show:true,title:r,defaultValue:t,onConfirm:async n=>{n&&n.trim()&&n!==t&&(await e.renameCategory(t,n.trim()),Li(se("categoryRenamedTo").replace("{name}",n.trim())),u===t&&h(n.trim()),Z());}});},ve=A(()=>{const e=[I.current,M.current?.getRootNode(),document],t=new Set;e.forEach(e=>{e&&!t.has(e)&&(t.add(e),e.querySelectorAll(".drop-above, .drop-below").forEach(e=>{e.classList.remove("drop-above","drop-below");}));}),I.current=null;},[]),we=()=>{M.current&&M.current.classList.remove("dragging"),ve(),T(null),M.current=null;},xe=(()=>{let t;if(u===Ao){if(t=e.getPrompts().filter(e=>e.lastUsedAt).sort((e,t)=>(t.lastUsedAt||0)-(e.lastUsedAt||0)).slice(0,10),g){const e=g.toLowerCase();t=t.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e));}}else t=e.filterPrompts(g,u);return u!==Ao&&(t=t.sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:0)),t})();_(()=>{if(!(S.show||x.show||v||m||O.show||D.show||L.show))return;const e=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.(),S.show?he():x.show?ue():L.show?me():v?de():m?ce():O.show?ge():D.show&&pe());};return document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);}},[de,ue,ce,pe,ge,he,me,x.show,D.show,v,m,O.show,S.show,L.show]),_(()=>{if(!H)return;const e=j.current;if(!e)return;const t="undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(H):H.replace(/["\\]/g,"\\$&"),n=e.querySelector(`.prompt-item[data-prompt-id="${t}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),null!==U.current&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{W(e=>e===H?null:e),U.current=null;},2200));},[H,s,g,u]); return Le("div",{className:"gh-prompts-tab",style:{display:"flex",flexDirection:"column",height:"100%"},children:[ Le("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",display:"flex",gap:"8px",alignItems:"center"},children:[ Ie("input",{type:"text",className:"prompt-search-input",placeholder:se("searchPlaceholder"),value:g,onChange:e=>p(e.target.value),style:{flex:1,padding:"6px 10px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"8px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}), Ie(up,{content:se("promptImport"),children:Ie("button",{onClick:()=>{const e=document.createElement("input");e.type="file",e.accept=".json",e.onchange=async e=>{const t=e.target.files?.[0];if(t)try{const e=await t.text(),n=JSON.parse(e);if(!Array.isArray(n))return void Li(se("promptImportFailed"));q({show:!0,prompts:n});}catch{Li(se("promptImportFailed"));}},e.click();},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:Ie(Qe,{size:16})})}), Ie(up,{content:se("promptExport"),children:Ie("button",{onClick:()=>{const t=e.getPrompts(),n=JSON.stringify(t,null,2),r=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${Cw}-prompts-${(new Date).toISOString().split("T")[0]}.json`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o),Li(se("promptExportSuccess"));},style:{width:"32px",height:"32px",border:"1px solid var(--gh-border, #d1d5db)",background:"var(--gh-bg, white)",borderRadius:"6px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"16px",flexShrink:0},children:Ie(Ve,{size:16})})})]}), Le("div",{style:{display:"flex",alignItems:"center",background:"var(--gh-bg, white)",borderBottom:"1px solid var(--gh-border, #e5e7eb)",userSelect:"none"},children:[ Le("div",{className:"prompt-category-bar",style:{flex:1,minWidth:0,padding:"6px 0 6px 10px",display:"flex",gap:"5px",flexWrap:"nowrap",overflowX:"auto",scrollbarWidth:"none"},onWheel:e=>{0!==e.deltaY&&(e.currentTarget.scrollLeft+=e.deltaY);},children:[ Ie("span",{onClick:()=>h(Co),style:{padding:"4px 10px",background:u===Co?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"12px",fontSize:"12px",color:u===Co?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:u===Co?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:se("allCategory")}),c.map(e=>{const t=(e=>{let t=0;for(let n=0;nh(e),style:{padding:"4px 10px",background:u===e?"var(--gh-primary, #4285f4)":`var(--gh-category-${t})`,borderRadius:"12px",fontSize:"12px",color:u===e?"white":"#4b5563",cursor:"pointer",flexShrink:0,border:u===e?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent",maxWidth:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})},e)})]}), Le("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"6px 8px",flexShrink:0,borderLeft:"1px solid var(--gh-border, #e5e7eb)"},children:[ Ie(up,{content:se("promptRecentUsed"),children:Ie("span",{onClick:()=>h(Ao),style:{padding:"3px 6px",display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1,background:u===Ao?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",borderRadius:"10px",color:u===Ao?"white":"#4b5563",cursor:"pointer",border:u===Ao?"1px solid var(--gh-primary, #4285f4)":"1px solid transparent"},children:Ie(Gt,{size:14})})}),c.length>0&&Ie(up,{content:se("manageCategory"),children:Ie("button",{onClick:()=>w(true),style:{padding:"3px 6px",background:"transparent",border:"1px dashed var(--gh-border, #d1d5db)",borderRadius:"10px",color:"var(--gh-text-secondary, #9ca3af)",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Ie(Oe,{size:13})})})]})]}), Ie("div",{ref:j,style:{flex:1,overflowY:"auto",padding:"8px",scrollbarWidth:"none"},children:0===xe.length?Ie("div",{style:{textAlign:"center",padding:"40px 20px",color:"var(--gh-text-tertiary, #9ca3af)",fontSize:"14px"},children:"暂无提示词"}):xe.map(t=>{const n=r===t.id,i=H===t.id,a=n||i; return Le("div",{"data-prompt-id":t.id,className:`prompt-item ${a?"selected":""} ${i?"located":""} ${E===t.id?"dragging":""}`,onClick:()=>{return e=t,W(null),void(o?(null!==$.current&&(window.clearTimeout($.current),$.current=null),$.current=window.setTimeout(()=>{$.current=null,ee(e);},340)):ee(e));var e;},onDoubleClick:()=>{return e=t,null!==$.current&&(window.clearTimeout($.current),$.current=null),void(o&&ee(e,true));var e;},draggable:true,onDragStart:e=>((e,t,n)=>{e.target.closest('button, input, textarea, select, [role="button"], [data-no-row-drag="true"]')?e.preventDefault():(T(t),M.current=n,I.current=n.getRootNode(),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",t),n.classList.add("dragging"));})(e,t.id,e.currentTarget),onDragOver:e=>((e,t)=>{if(e.preventDefault(),e.dataTransfer.dropEffect="move",!E||E===t)return;const n=e.currentTarget,r=n.getBoundingClientRect(),o=r.top+r.height/2,i=n.getRootNode();I.current=i,ve(),e.clientY(async(t,n)=>{if(t.preventDefault(),!E||E===n)return void we();const r=e.getPrompts(),o=r.findIndex(e=>e.id===E),i=r.findIndex(e=>e.id===n);if(-1===o||-1===i)return void we();const a=[...r],[s]=a.splice(o,1),l=t.currentTarget.getBoundingClientRect(),c=t.clientYe.id===n);oe.id)),Li(se("orderUpdated")),Z(),we();})(n,t.id),style:{background:a?"linear-gradient(135deg, #e8f0fe 0%, #f1f8e9 100%)":"var(--gh-bg, white)",border:a?"1px solid var(--gh-primary, #4285f4)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",padding:"12px",marginBottom:"8px",cursor:"pointer",transition:"all 0.2s",position:"relative",userSelect:"none"},children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:"8px"},children:[ Ie("div",{style:{fontWeight:600,fontSize:"14px",color:"var(--gh-text, #1f2937)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:"8px"},children:t.title}), Ie("span",{style:{fontSize:"11px",padding:"2px 6px",background:"var(--gh-hover, #f3f4f6)",borderRadius:"4px",color:"var(--gh-text-secondary, #6b7280)",flexShrink:0},children:t.category||se("uncategorized")})]}), Ie("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #6b7280)",lineHeight:1.4,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:t.content}), Le("div",{className:"prompt-item-actions",style:{position:"absolute",top:"8px",right:"8px",gap:"2px"},children:[ Ie(up,{content:t.pinned?se("promptUnpin"):se("promptPin"),children:Ie("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),e.togglePin(t),Z();})(t.id,n),className:"prompt-action-btn"+(t.pinned?" active":""),children:Ie(Ot,{size:16,filled:t.pinned})})}), Ie(up,{content:se("promptMarkdownPreview"),children:Ie("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),F({show:true,prompt:t});},className:"prompt-action-btn",children:Ie(Ft,{size:16})})}), Ie(up,{content:se("copy"),children:Ie("button",{onClick:e=>(async(e,t)=>{t.stopPropagation(),t.preventDefault();try{await navigator.clipboard.writeText(e),Li(se("copied"));}catch{const t=document.createElement("textarea");t.value=e,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Li(se("copied"));}})(t.content,e),className:"prompt-action-btn",children:Ie(Tt,{size:16})})}), Ie(up,{content:se("more"),children:Ie("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),Q({prompt:t,anchorEl:e.currentTarget});},className:"prompt-action-btn",children:Ie(Mt,{size:16})})}), Ie(up,{content:se("edit"),children:Ie("button",{onClick:e=>{e.stopPropagation(),e.preventDefault(),be(t);},className:"prompt-action-btn",children:Ie(zt,{size:16})})}), Ie(up,{content:se("delete"),children:Ie("button",{onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),X(se("confirmDelete"),"确定删除该提示词?",async()=>{await e.deletePrompt(t),Li(se("deleted")),Z();});})(t.id,n),className:"prompt-action-btn danger",children:Ie(Bt,{size:16})})})]})]},t.id)})}), Ie("div",{style:{padding:"12px"},children:Le("button",{onClick:()=>be(),style:{width:"100%",padding:"10px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",fontSize:"14px",fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",boxShadow:"var(--gh-btn-shadow)",transition:"transform 0.2s, box-shadow 0.2s"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Ie("span",{children:"+"}), Ie("span",{children:se("addPrompt")})]})}),m?np( Ie("div",{className:"prompt-modal gh-interactive",...Za,style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:Le("div",{className:"prompt-modal-content",onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"500px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow, 0 20px 50px rgba(0,0,0,0.3))"},children:[ Ie("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:se(b?.id?"editPrompt":"addNewPrompt")}), Le("div",{style:{marginBottom:"16px"},children:[ Ie("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:se("title")}), Ie("input",{type:"text",value:b?.title||"",onChange:e=>y({...b,title:e.target.value}),style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}})]}), Le("div",{style:{marginBottom:"16px"},children:[ Ie("label",{style:{display:"block",fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)",marginBottom:"6px"},children:se("category")}), Ie("input",{type:"text",value:b?.category||"",onChange:e=>y({...b,category:e.target.value}),placeholder:se("categoryPlaceholder"),style:{width:"100%",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)"}}),c.length>0&&Ie("div",{style:{marginTop:"6px",display:"flex",gap:"4px",flexWrap:"wrap",userSelect:"none"},children:c.map(e=>Ie("span",{onClick:()=>y({...b,category:e}),style:{padding:"2px 8px",fontSize:"11px",background:b?.category===e?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:b?.category===e?"var(--gh-text-on-primary, white)":"var(--gh-text-secondary, #6b7280)",borderRadius:"10px",cursor:"pointer",transition:"all 0.15s"},children:e},e))})]}), Ie("div",{style:{marginBottom:"16px"},children:Le("div",{children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[ Ie("label",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-text, #374151)"},children:se("content")}), Ie("button",{onClick:()=>B(!R),style:{padding:"2px 8px",fontSize:"12px",background:R?"var(--gh-primary, #4285f4)":"var(--gh-hover, #f3f4f6)",color:R?"white":"var(--gh-text-secondary, #6b7280)",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"4px",cursor:"pointer"},children:se("promptMarkdownPreview")})]}), Ie("textarea",{value:b?.content||"",onChange:e=>y({...b,content:e.target.value}),style:{width:"100%",minHeight:"120px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",resize:"vertical",boxSizing:"border-box",fontFamily:"inherit",background:"var(--gh-bg, #ffffff)",color:"var(--gh-text, #1f2937)",display:R?"none":"block"}}),R&&Le(_e,{children:[ Ie("div",{className:"gh-markdown-preview",style:{width:"100%",minHeight:"120px",maxHeight:"200px",padding:"8px 12px",border:"1px solid var(--gh-border, #d1d5db)",borderRadius:"6px",fontSize:"14px",boxSizing:"border-box",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text, #1f2937)",overflowY:"auto",lineHeight:1.6},ref:V,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{mp(t,{size:14});});}},dangerouslySetInnerHTML:{__html:qp(Hh(b?.content||""))}}), Ie("style",{children:"\n/* highlight.js GitHub Dark 主题\n 面板(Shadow DOM)通过 var() 跟随 Ophel 主题变量;\n 主文档注入(用户提问)var() 不可用,fallback 为 #1e1e1e */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview :not(pre) > code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview .gh-code-wrapper {\n position: relative;\n margin: 12px 0;\n}\n.gh-markdown-preview pre {\n margin: 0;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]})]})}), Le("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end",marginTop:"24px"},children:[ Ie(Dw,{variant:"ghost",onClick:ce,style:{background:"var(--gh-hover, #f3f4f6)"},children:se("cancel")}), Ie(Dw,{variant:"primary",onClick:le,children:se(b?.id?"save":"add")})]})]})}),document.body):null,v?np( Ie("div",{className:"prompt-modal gh-interactive",...Za,style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:2147483646,animation:"fadeIn 0.2s"},children:Le("div",{onClick:e=>e.stopPropagation(),style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"90%",maxWidth:"400px",padding:"24px",animation:"slideUp 0.3s",boxShadow:"var(--gh-shadow-lg, 0 20px 50px rgba(0,0,0,0.3))"},children:[ Ie("div",{style:{fontSize:"18px",fontWeight:600,marginBottom:"20px",color:"var(--gh-text, #1f2937)"},children:se("categoryManage")}), Ie("div",{style:{maxHeight:"300px",overflowY:"auto"},children:0===c.length?Ie("div",{style:{textAlign:"center",color:"var(--gh-text-tertiary, #9ca3af)",padding:"20px"},children:se("categoryEmpty")}):c.map(t=>{const n=s.filter(e=>e.category===t).length; return Le("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 0",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ Le("div",{children:[ Ie("div",{style:{fontWeight:500,color:"var(--gh-text, #374151)"},children:t}), Le("div",{style:{fontSize:"12px",color:"var(--gh-text-tertiary, #9ca3af)"},children:[n," ",se("promptCountSuffix")]})]}), Le("div",{style:{display:"flex",gap:"8px"},children:[ Ie(up,{content:se("rename"),children:Ie(Dw,{size:"sm",onClick:e=>ye(t,e),style:{color:"var(--gh-primary, #4285f4)"},children:se("rename")})}), Ie(up,{content:se("delete"),children:Ie(Dw,{size:"sm",onClick:n=>((t,n)=>{n.stopPropagation(),n.preventDefault(),X(se("confirmDeleteCategory"),se("confirmDeleteCategoryMsg").replace("{name}",t),async()=>{await e.deleteCategory(t),Li(se("categoryDeletedMsg").replace("{name}",t)),u===t&&h(Co),Z();});})(t,n),style:{border:"1px solid var(--gh-border-danger, #fecaca)",background:"var(--gh-bg-danger, #fef2f2)",color:"var(--gh-text-danger, #ef4444)"},children:se("delete")})})]})]},t)})}), Ie("div",{style:{marginTop:"20px",display:"flex",justifyContent:"flex-end"},children:Ie(Dw,{variant:"ghost",onClick:de,style:{background:"var(--gh-hover, #f3f4f6)"},children:se("close")})})]})}),document.body):null,O.show&&O.prompt?np( Ie("div",{className:"prompt-preview-modal gh-interactive",...Za,onClick:e=>{e.target===e.currentTarget&&ge();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001,animation:"fadeIn 0.2s ease-out"},children:Le("div",{style:{width:"90%",maxWidth:"600px",maxHeight:"80vh",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",overflow:"hidden",display:"flex",flexDirection:"column",animation:"slideUp 0.3s ease-out"},children:[ Le("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Le("div",{children:[ Ie("div",{style:{fontSize:"16px",fontWeight:600,color:"var(--gh-text, #1f2937)"},children:O.prompt.title}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:O.prompt.category})]}), Ie("button",{onClick:ge,style:{width:"28px",height:"28px",border:"none",background:"var(--gh-hover, #f3f4f6)",borderRadius:"6px",cursor:"pointer",fontSize:"16px",display:"flex",alignItems:"center",justifyContent:"center"},children:Ie(Re,{size:16})})]}), Ie("div",{className:"gh-markdown-preview",style:{flex:1,padding:"20px",overflowY:"auto"},ref:K,onClick:e=>{const t=e.target.closest(".gh-code-copy-btn");if(t){const e=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(e).then(()=>{mp(t,{size:14});});}},dangerouslySetInnerHTML:{__html:qp(Hh(O.prompt.content))}}), Ie("style",{children:"\n/* highlight.js GitHub Dark 主题\n 面板(Shadow DOM)通过 var() 跟随 Ophel 主题变量;\n 主文档注入(用户提问)var() 不可用,fallback 为 #1e1e1e */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview :not(pre) > code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview .gh-code-wrapper {\n position: relative;\n margin: 12px 0;\n}\n.gh-markdown-preview pre {\n margin: 0;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]})}),document.body):null,D.show?np( Ie("div",{className:"import-dialog gh-interactive",...Za,onClick:e=>{e.target===e.currentTarget&&pe();},style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"var(--gh-overlay-bg, rgba(0, 0, 0, 0.5))",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10001},children:Le("div",{style:{width:"90%",maxWidth:"400px",background:"var(--gh-bg, white)",borderRadius:"12px",boxShadow:"var(--gh-shadow-lg)",padding:"24px"},children:[ Ie("div",{style:{fontSize:"16px",fontWeight:600,marginBottom:"12px",color:"var(--gh-text)"},children:se("promptImportTitle")}), Le("div",{style:{fontSize:"14px",color:"var(--gh-text-secondary)",marginBottom:"20px",lineHeight:1.6},children:[se("promptImportMessage2").replace("{count}",D.prompts.length.toString()), Le("ul",{style:{margin:"8px 0 0 0",paddingLeft:"20px"},children:[ Ie("li",{children:se("promptImportOverwriteDesc")}), Ie("li",{children:se("promptImportMergeDesc")})]})]}), Le("div",{style:{display:"flex",gap:"12px",justifyContent:"flex-end"},children:[ Ie(Dw,{variant:"ghost",onClick:pe,style:{background:"var(--gh-hover, #f3f4f6)"},children:se("cancel")}), Ie(Dw,{variant:"ghost",onClick:ae,style:{background:"var(--gh-primary-light, #e3f2fd)",color:"var(--gh-primary, #4285f4)"},children:se("promptMerge")}), Ie(Dw,{variant:"primary",onClick:ie,children:se("promptOverwrite")})]})]})}),document.body):null,x.show&&Ie(Lw,{title:x.title,message:x.message,danger:true,closeOnOverlayClick:false,onConfirm:()=>{ue(),x.onConfirm();},onCancel:ue}),S.show&&Ie(Nw,{title:S.title,defaultValue:S.defaultValue,closeOnOverlayClick:false,onConfirm:e=>{he(),S.onConfirm(e);},onCancel:he}),L.show&&Ie(wx,{variables:L.variables,onConfirm:async e=>{const{prompt:t,submitAfterInsert:n,enqueueAfterResolve:r,enqueueSplitByLine:o}=L;if(!t)return;const i=((e,t)=>e.replace(/\{\{([^\s{}]+)\}\}/g,(e,n)=>n in t?t[n]:e))(t.content,e);N({show:false,prompt:null,variables:[],submitAfterInsert:false,enqueueAfterResolve:false,enqueueSplitByLine:false}),await new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e());});}),n?await ne(t,i):r?re(t,i,o):await te(t,i);},onCancel:me}),G&&Le(rx,{anchorEl:G.anchorEl,onClose:fe,children:[ Ie(ox,{onClick:()=>{oe(G.prompt),fe();},children:Le("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie(rn,{size:14}), Ie("span",{children:se("promptAddToQueue")})]})}), Ie(ox,{onClick:()=>{oe(G.prompt,true),fe();},children:Le("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie(on,{size:14}), Ie("span",{children:se("promptSplitLinesToQueue")})]})})]}), Ie("style",{children:"\n @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }\n @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }\n "})]})},Ex=({onClose:e,isOpen:t,isLauncherPeeking:n=false,launcherPeekAnchorRect:r=null,isScrolling:o,promptManager:i,conversationManager:a,outlineManager:s,adapter:l,onThemeToggle:c,themeMode:d,selectedPromptId:u,onPromptSelect:h,edgeSnapState:g,isEdgePeeking:p=false,onEdgeSnap:m,onUnsnap:f,onInteractionStateChange:b,onOpenSettings:y,onMouseEnter:v,onMouseLeave:w})=>{const x=A(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:k,updateNestedSetting:S,setSettings:C}=Ai(),E=k||Jo,T=E.features?.order||Jo.features.order,M=l?.getSiteId()||"_default",I=Xo(E,M),L=d||("dark"===I.mode?"dark":"light"),N="light"===L?I.lightStyleId||"google-gradient":I.darkStyleId||"classic-dark",R="dark"===L?"brand":"currentColor",O=Array.isArray(E.theme?.customStyles)?E.theme.customStyles.find(e=>e.id===N):null,{panelRef:F,headerRef:$}=function(e={}){const{edgeSnapHide:t=false,edgeSnapState:n,snapThreshold:r=30,onEdgeSnap:o,onUnsnap:i}=e,a=P(null),s=P(null),l=P(false),c=P(false),d=P({x:0,y:0}),u=P(null),h=P(null),g=P(false),p=P(null),m=A((e,t,n,r)=>{const o=Math.max(r,t-n-r),i=Math.max(1,o-r);return Math.min(1,Math.max(0,(e-r)/i))},[]),f=A((e,t,n,r)=>{const o=Math.max(r,t-n-r);return r+e*Math.max(1,o-r)},[]),b=A((e,t=window.innerWidth,n=window.innerHeight)=>({xRatio:m(e.left,t,e.width,0),yRatio:m(e.top,n,e.height,ex)}),[m]),y=A(e=>{if(e.target.closest(".gh-panel-controls"))return;const t=a.current;if(!t)return;e.preventDefault(),u.current=n||null;const r=t.getBoundingClientRect();d.current={x:e.clientX-r.left,y:e.clientY-r.top},c.current=false,l.current=true,document.body.style.userSelect="none";},[n]),v=A(e=>{if(!l.current)return;const t=a.current;t&&(e.preventDefault(),c.current||(c.current=true,u.current&&(i?.(),u.current=null),t.classList.remove("edge-snapped-left","edge-snapped-right"),t.style.right="auto",t.style.transform="none",g.current=false,t.classList.add("dragging")),t.style.left=e.clientX-d.current.x+"px",t.style.top=e.clientY-d.current.y+"px");},[i]),w=A((e,t,n=300,r)=>{const o=a.current;if(!o)return;null!==h.current&&(cancelAnimationFrame(h.current),h.current=null);const i=parseFloat(o.style.left)||o.getBoundingClientRect().left,s=parseFloat(o.style.top)||o.getBoundingClientRect().top,l=performance.now(),c=a=>{const d=a-l;let u=Math.min(d/n,1);u=1-Math.pow(1-u,3);const g=i+(e-i)*u,p=s+(t-s)*u;o.style.left=`${g}px`,o.style.top=`${p}px`,u<1?h.current=requestAnimationFrame(c):(h.current=null,r?.());};h.current=requestAnimationFrame(c);},[]),x=A(()=>{if(!l.current)return;const e=a.current,n=c.current;if(l.current=false,u.current=null,document.body.style.userSelect="",e?.classList.remove("dragging"),n&&e&&!t){const t=e.getBoundingClientRect();p.current=b(t);}if(t&&n&&e){const t=e.getBoundingClientRect(),n=window.innerWidth,i=t.width,a=t.top;t.left{o?.("left");}):n-t.right{o?.("right");}):p.current=b(t,n,window.innerHeight);}},[t,o,r,w,b]),k=A(()=>{const e=a.current;if(!e)return;if(n)return;const t=window.innerWidth,r=window.innerHeight,o=e.getBoundingClientRect();if(!p.current){const n=e.style.left;if(!Boolean(n&&"auto"!==n&&"none"===e.style.transform)){const t="none"!==e.style.transform,n=o.height+20<=r;if((t||g.current)&&n)return void(g.current&&(e.style.top="50%",e.style.transform="translateY(-50%)",g.current=false));t&&(g.current=true);let i=o.top;return i+o.height+ex>r&&(i=r-o.height-ex),i.5&&(e.style.top=i+"px",e.style.transform="none"))}p.current=b(o,t,r);}const i=p.current;let s=i?f(i.xRatio,t,o.width,0):o.left,l=i?f(i.yRatio,r,o.height,ex):o.top;s+o.width+0>t&&(s=t-o.width-0),l+o.height+ex>r&&(l=r-o.height-ex),s<0&&(s=0),l.5||Math.abs(l-o.top)>.5)&&(e.style.left=s+"px",e.style.top=l+"px",e.style.right="auto",e.style.transform="none");},[n,f,b]);return _(()=>{n&&(p.current=null);},[n]),_(()=>{const e=s.current;if(e)return e.addEventListener("mousedown",y),document.addEventListener("mousemove",v),document.addEventListener("mouseup",x),window.addEventListener("resize",k),()=>{e.removeEventListener("mousedown",y),document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",x),window.removeEventListener("resize",k),null!==h.current&&(cancelAnimationFrame(h.current),h.current=null);}},[y,v,x,k]),{panelRef:a,headerRef:s}}({edgeSnapHide:!n&&"edge-snap"===E.panel?.panelMode,edgeSnapState:n?null:g,snapThreshold:E.panel?.edgeSnapThreshold??30,onEdgeSnap:m,onUnsnap:f}),U=P(E.panel?.panelMode),j=P(null),H=P(null);D(()=>{const e=E.panel?.panelMode,t=U.current;if(U.current=e,t===e||!F.current)return;const n=F.current;if(n.classList.remove("dragging"),"edge-snap"===t&&"floating"===e){n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="";const e=j.current;j.current=null;const t=e??n.getBoundingClientRect(),r=t?Math.min(t.right,window.innerWidth)-Math.max(t.left,0):0;if(t.width>0&&r>=.5*t.width)n.style.left=`${t.left}px`,n.style.top=`${t.top}px`,n.style.right="auto",n.style.transform="none";else {const e=E.panel?.defaultPosition??"right",r=E.panel?.defaultEdgeDistance??0,o=t?t.top:null;null!==o&&o>=0&&o{n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="",H.current=null;},400);}return ()=>{H.current&&(clearTimeout(H.current),H.current=null),n.removeAttribute("data-edge-snap-transitioning"),n.style.pointerEvents="";}},[E.panel?.panelMode,E.panel?.defaultEdgeDistance,E.panel?.defaultPosition,F]);const W=P(E.panel?.defaultEdgeDistance),G=P(E.panel?.defaultPosition);D(()=>{const e=E.panel?.defaultEdgeDistance,t=W.current;W.current=e;const n=E.panel?.defaultPosition,r=G.current;G.current=n;if((e!==t||n!==r)&&F.current&&"floating"===E.panel?.panelMode){const t=F.current,r=e??0;"left"===(n??"right")?(t.style.left=`${r}px`,t.style.right="auto"):(t.style.right=`${r}px`,t.style.left="auto"),t.style.top="50%",t.style.transform="translateY(-50%)";}},[E.panel?.defaultEdgeDistance,E.panel?.defaultPosition,E.panel?.panelMode,F]);const Q=E.panel?.defaultPosition??"right",V=E.panel?.defaultEdgeDistance??40,K="edge-snap"===(E.panel?.panelMode??"edge-snap"),Z=E.panel?.width??320,Y=E.panel?.height??85,J=q(()=>{if(!n||!r||"undefined"==typeof window)return {};const e=window.innerWidth,t=window.innerHeight,o=10,i=Math.max(500,t*Y/100),a=r.left+r.width/2,s=r.top+r.height/2,l=a>e/2?r.left-Z:r.right,c=Math.max(o,e-Z-o),d=Math.min(Math.max(l,o),c),u=s-i/2,h=Math.max(o,t-i-o);return {left:`${d}px`,right:"auto",top:`${Math.min(Math.max(u,o),h)}px`,transform:"none"}},[n,r,Y,Z]),X=n?J:K?{left:"",right:""}:"left"===Q?{left:`${V}px`,right:"auto"}:{right:`${V}px`,left:"auto"},[ee,te]=z(false),[ne,re]=z(false),oe=E.hasSeenOphelAdvancedGuide??false,ie="shortcutNotSet",ae=se(ie),le=ae===ie?"未设置":ae,ce=e=>{e&&!oe&&C&&C({hasSeenOphelAdvancedGuide:true});},de=A(e=>!(e instanceof Element)||!e.closest('.gh-panel-controls, [data-no-header-press-hint="true"]'),[]),ue=A(()=>{re(false);},[]),he=A(e=>{de(e.target)?re(true):ue();},[ue,de]),ge=q(()=>Xw(E.shortcuts?.keybindings,lr(),le),[E.shortcuts?.keybindings,E.language,le]),me=P(null),fe=A(()=>{oe||(me.current&&clearTimeout(me.current),te(true),ce(true));},[oe,ce]),be=A(()=>{me.current&&clearTimeout(me.current),me.current=setTimeout(()=>{te(false);},300);},[]),ye=A(e=>{const t=e.target;if(t instanceof Element&&t.closest(".gh-panel-controls"))return;const n=E.panel?.panelMode??"edge-snap";"edge-snap"===n&&F.current&&(j.current=F.current.getBoundingClientRect()),S("panel","panelMode","edge-snap"===n?"floating":"edge-snap");},[E.panel?.panelMode,S]);_(()=>()=>{me.current&&clearTimeout(me.current);},[]);const ve=A(()=>{te(false);},[]),we=e=>e&&e.length>0?e[0]:cr,[xe,ke]=z(cr),[Se,Ce]=z(false);_(()=>{k&&!Se&&(ke(we(k.features?.order)),Ce(true));},[k,Se]),_(()=>{Se&&T&&T.length>0&&(T.includes(xe)||ke(we(T)));},[T,Se,xe]),_(()=>{const e=()=>{ke(dr);},t=()=>{ke(ur);},n=e=>{const t=e.detail?.index;"number"==typeof t&&T[t]&&ke(T[t]);};return window.addEventListener("ophel:locateOutline",e),window.addEventListener("ophel:searchOutline",e),window.addEventListener("ophel:locateConversation",t),window.addEventListener("ophel:switchTab",n),()=>{window.removeEventListener("ophel:locateOutline",e),window.removeEventListener("ophel:searchOutline",e),window.removeEventListener("ophel:locateConversation",t),window.removeEventListener("ophel:switchTab",n);}},[T]),_(()=>{if(!t)return;const e=F.current;return e?es(e):void 0},[t,F]);const Ae=null!==B(tw,nw),[Ee,Te]=z(0);_(()=>{if(0===Ee)return;const e=setTimeout(()=>Te(0),400);return ()=>clearTimeout(e)},[Ee]);const[Me,qe]=z(false),[Re,ze]=z(""),Fe=P(false),je=A(async()=>{Fe.current=false;const e=new AbortController,t=setInterval(()=>{Fe.current&&e.abort();},100);let n=setTimeout(()=>{Fe.current||(qe(true),ze(se("loadingHistory")));},1600);try{const t=await ww({adapter:l||null,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{ze(`${se("loadingHistory")} ${e}`);}});ew(t.previousScrollTop),n&&(clearTimeout(n),n=null),qe(!1),ze(""),t.success&&!t.silent&&Li(se("historyLoaded"),2e3);}finally{clearInterval(t),n&&clearTimeout(n);}},[l]),We=A(()=>{Fe.current=true;},[]),Qe=A(async()=>{const{previousScrollTop:e}=await cw(l||null);ew(e);},[l]),Ve=A(async()=>{const e=Xv();if(null===e)return;Te(e=>e+1);const t=(await hw(l||null)).scrollTop;await dw(l||null,e),ew(t);},[l]),Ke=A(async()=>{const e=await hw(l||null);ew(e.scrollTop);},[l]);if(!t)return null;const Ze=T.filter(e=>e!==hr&&((e!==cr||false!==E.features?.prompts?.enabled)&&((e!==ur||false!==E.features?.conversations?.enabled)&&(e!==dr||false!==E.features?.outline?.enabled)))); return Le(_e,{children:[ Ie(Zw,{isVisible:Me,text:Re,onStop:We}), Le("div",{ref:F,onMouseEnter:v,onMouseLeave:w,className:`gh-main-panel gh-interactive ${!n&&g?`edge-snapped-${g}`:""} ${n?"launcher-peek":""} ${p?"edge-peek":""} ${o?"scroll-hidden":""}`,style:{position:"fixed",top:"50%",...X,transform:n?"none":"translateY(-50%)",width:`${Z}px`,height:`${Y}vh`, // @ts-ignore - 注入 CSS 变量供吸附计算使用 "--panel-width":`${Z}px`,minHeight:"500px",backgroundColor:"var(--gh-bg, #ffffff)",backgroundImage:"var(--gh-bg-image, none)",backgroundBlendMode:"overlay",animation:"var(--gh-bg-animation, none)",borderRadius:"12px",boxShadow:"var(--gh-shadow, 0 10px 40px rgba(0,0,0,0.15))",display:"flex",flexDirection:"column",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)",zIndex:9999,fontFamily:pe},children:[O?Ie("style",{children:O.css}):null, Le("div",{ref:$,onPointerDown:he,onPointerUp:ue,onPointerLeave:ue,onPointerCancel:ue,onDoubleClick:ye,className:"gh-panel-header",style:{position:"relative",padding:"10px 14px",borderRadius:"12px 12px 0 0",display:"flex",alignItems:"center",justifyContent:"space-between",userSelect:"none"},children:[ Le("div",{style:{position:"relative"},onMouseEnter:fe,onMouseLeave:be,children:[ Le("div",{className:"gh-interactive",role:"button",tabIndex:0,"aria-label":se("panelTitle"),"data-tip-target":"header-title","data-no-header-press-hint":"true",onClick:()=>{te(e=>!e),ce(true);},onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),te(e=>!e));},style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer",position:"relative",border:"none",background:"transparent",padding:0,color:"inherit"},children:[ Le("div",{style:{position:"relative",display:"flex",alignItems:"center"},children:[ Ie(Qt,{size:18,color:R}),!oe&&Ie("div",{style:{position:"absolute",top:"-2px",right:"-2px",width:"6px",height:"6px",backgroundColor:"var(--gh-danger, #ef4444)",borderRadius:"50%",boxShadow:"0 0 0 2px var(--gh-bg, #ffffff)",animation:"pulse-red 2s infinite"}})]}), Ie("span",{style:{fontSize:"18px",fontWeight:600,userSelect:"none"},children:se("panelTitle")})]}), Ie(Yw,{isOpen:ee,onClose:ve,tips:ge,onMouseEnter:fe,onMouseLeave:be})]}), Le("div",{className:"gh-panel-controls","data-no-header-press-hint":"true",style:{display:"flex",gap:"1px",alignItems:"center"},children:[ Ie(up,{content:"edge-snap"===(E.panel?.panelMode??"edge-snap")?se("pinPanel"):se("snapToEdge"),children:Ie("button",{type:"button","aria-label":"edge-snap"===(E.panel?.panelMode??"edge-snap")?se("pinPanel"):se("snapToEdge"),onClick:()=>{const e=E.panel?.panelMode??"edge-snap";"edge-snap"===e&&F.current&&(j.current=F.current.getBoundingClientRect()),S("panel","panelMode","edge-snap"===e?"floating":"edge-snap");},className:"gh-header-icon-btn",children:"edge-snap"===(E.panel?.panelMode??"edge-snap")?Ie(Yt,{size:14}):Ie(Zt,{size:14})})}),c&&Ie(up,{content:se("toggleTheme"),children:Ie("button",{onClick:e=>{c?.(x(e.currentTarget));},className:"gh-header-icon-btn",children:Ie("dark"===d?Ne:De,{size:14})})}),E.tab?.openInNewTab&&Ie(up,{content:se("newTabTooltip"),children:Ie("button",{onClick:()=>window.open(window.location.origin,"_blank"),className:"gh-header-icon-btn",children:Ie(Be,{size:14})})}), Ie(up,{content:se("tabSettings"),children:Ie("button",{"data-tip-target":"settings-btn",onClick:()=>{y?.();},className:"gh-header-icon-btn",children:Ie(Oe,{size:14})})}), Ie(up,{content:se("collapse"),children:Ie("button",{onClick:e,"aria-label":se("collapse"),className:"gh-header-icon-btn",children:Ie($e,{size:14})})})]})]}), Le("div",{style:{position:"absolute",top:"56px",left:"50%",width:"max-content",maxWidth:"85%",transform:`translate(-50%, ${ne?"8px":"-4px"})`,opacity:ne?1:0,pointerEvents:"none",transition:"all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)",background:"var(--gh-bg-secondary, rgba(255, 255, 255, 0.85))",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"var(--gh-text, #1f2937)",border:"1px solid var(--gh-border, rgba(0,0,0,0.1))",padding:"6px 12px",borderRadius:"12px",fontSize:"12px",fontWeight:500,display:"flex",textAlign:"left",alignItems:"flex-start",gap:"8px",boxShadow:"var(--gh-shadow-lg, 0 8px 24px rgba(0,0,0,0.12))",zIndex:10},children:[ Ie("span",{style:{fontSize:"14px",flexShrink:0,marginTop:"1px"},children:"👻"}), Ie("span",{style:{lineHeight:"1.5"},children:se("tip1",{modifier:lr()?"⌘ Cmd":"Ctrl"})})]}), Ie("div",{className:"gh-panel-tabs",style:{display:"flex",borderBottom:"1px solid var(--gh-border, #e5e7eb)",padding:"0",background:"var(--gh-bg-secondary, #f9fafb)"},children:Ze.map(e=>{let t=null;return e===dr?t=Ue:e===cr?t=He:e===ur&&(t=Ge),Le("button",{"data-tip-target":e===dr?"outline-tab":e===ur?"conversations-tab":e===cr?"prompts-tab":void 0,onClick:()=>ke(e),style:{flex:1,padding:"7px 8px",border:"none",background:"transparent",borderBottom:xe===e?"3px solid var(--gh-primary, #4285f4)":"3px solid transparent",color:xe===e?"var(--gh-primary, #4285f4)":"var(--gh-text-secondary, #6b7280)",fontWeight:xe===e?600:400,cursor:"pointer",fontSize:"13px",whiteSpace:"nowrap",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",transition:"all 0.2s"},children:[ Ie("span",{style:{display:"flex",alignItems:"center"},children:t&&Ie(t,{size:16})}), Ie("span",{children:se(`tab${e.charAt(0).toUpperCase()+e.slice(1)}`)})]},e)})}), Le("div",{className:"gh-panel-content",style:{flex:1,overflowY:"auto",padding:"0",scrollbarWidth:"none",msOverflowStyle:"none"},children:[xe===cr&&Ie(Ax,{manager:i,adapter:l,selectedPromptId:u,onPromptSelect:h}),xe===ur&&Ie(hx,{manager:a,onInteractionStateChange:b}),xe===dr&&Ie(vx,{manager:s,onJumpBefore:Ke,isCodexOpen:ee})]}), Le("div",{className:"gh-panel-footer",style:{display:"flex",justifyContent:"space-around",alignItems:"center",padding:"8px 16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)"},children:[ Ie(up,{content:se("scrollTop"),triggerStyle:{flex:1,maxWidth:"120px"},children:Le("button",{className:"gh-interactive scroll-nav-btn",onClick:je,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Ie(tt,{size:14}), Ie("span",{children:se("scrollTop")})]})}), Ie(up,{content:se(Ae?"jumpToAnchor":"noAnchor"),triggerStyle:{flex:"0 0 32px"},children:Ie("button",{className:"gh-interactive scroll-nav-btn anchor-btn",onClick:Ve,disabled:!Ae,style:{width:"32px",height:"32px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"50%",padding:0,cursor:Ae?"pointer":"default",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)",opacity:Ae?1:.4},onMouseEnter:e=>{if(Ae){e.currentTarget.style.transform="scale(1.1)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(360deg)");}},onMouseLeave:e=>{e.currentTarget.style.transform="scale(1)",e.currentTarget.style.boxShadow=Ae?"var(--gh-btn-shadow)":"none";const t=e.currentTarget.querySelector("div");t&&(t.style.transform="rotate(0deg)");},children:Ie("span",{className:"anchor-tap-wrapper"+(Ee>0?" is-tapping":""),onAnimationEnd:()=>Te(0),style:{display:"flex",alignItems:"center",justifyContent:"center"},children:Ie("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)"},children:Ie(Pe,{size:14})})},Ee)})}), Ie(up,{content:se("scrollBottom"),triggerStyle:{flex:1,maxWidth:"120px"},children:Le("button",{className:"gh-interactive scroll-nav-btn",onClick:Qe,style:{width:"100%",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",gap:"4px",background:"var(--gh-header-bg)",color:"var(--gh-footer-text, var(--gh-text-on-primary, white))",border:"none",borderRadius:"8px",cursor:"pointer",fontSize:"14px",transition:"transform 0.2s, box-shadow 0.2s",boxShadow:"var(--gh-btn-shadow)"},onMouseEnter:e=>{e.currentTarget.style.transform="translateY(-1px)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow-hover)";},onMouseLeave:e=>{e.currentTarget.style.transform="translateY(0)",e.currentTarget.style.boxShadow="var(--gh-btn-shadow)";},children:[ Ie(nt,{size:14}), Ie("span",{children:se("scrollBottom")})]})})]})]})]})};e('.gh-queue-capsule{position:fixed;z-index:99998;display:flex;align-items:center;gap:6px;padding:6px 14px;border-radius:20px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);color:var(--gh-text, #1f2937);font-size:13px;font-weight:500;cursor:pointer;-webkit-user-select:none;user-select:none;box-shadow:0 2px 12px #00000014;transition:all .2s ease;font-family:var( --gh-font-family, "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif )}.gh-queue-capsule:hover{transform:translateY(-1px);background:var(--gh-bg-secondary, #f9fafb);box-shadow:0 4px 16px #0000001f}.gh-queue-capsule-icon{font-size:14px;line-height:1}.gh-queue-capsule-badge{display:inline-flex;align-items:center;justify-content:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4);font-size:11px;font-weight:600}.gh-queue-panel{position:fixed;z-index:99999;width:420px;max-width:calc(100vw - 40px);max-height:400px;border-radius:16px;background:var(--gh-bg, #ffffff);border:1px solid var(--gh-border, #e5e7eb);box-shadow:0 8px 32px #0000001f,0 2px 8px #0000000f;display:flex;flex-direction:column;overflow:hidden;font-family:var( --gh-font-family, "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", "PingFang SC", "Hiragino Sans SC", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif )}.gh-queue-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-header-title{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-header-actions{display:flex;align-items:center;gap:4px}.gh-queue-header-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border:none;border-radius:6px;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-header-btn:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-list{flex:1;overflow-y:auto;padding:8px;max-height:180px}.gh-queue-empty{display:flex;align-items:center;justify-content:center;padding:16px;color:var(--gh-text-tertiary, #9ca3af);font-size:13px}.gh-queue-item{display:flex;align-items:flex-start;gap:8px;padding:8px 10px;border-radius:8px;margin-bottom:4px;background:var(--gh-bg-secondary, #f9fafb);transition:background .15s}.gh-queue-item:hover{background:var(--gh-bg-tertiary, #f3f4f6)}.gh-queue-item-index{flex-shrink:0;width:20px;height:20px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--gh-accent, #4285f4);color:#fff;font-size:11px;font-weight:600;margin-top:1px}.gh-queue-item-content{flex:1;min-width:0;font-size:13px;line-height:1.5;color:var(--gh-text, #1f2937);word-break:break-word;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.gh-queue-item-actions{flex-shrink:0;display:flex;align-items:center;gap:4px;opacity:0;transition:opacity .15s}.gh-queue-item:hover .gh-queue-item-actions{opacity:1}.gh-queue-item-remove,.gh-queue-item-force-send,.gh-queue-item-edit{display:flex;align-items:center;justify-content:center;width:22px;height:22px;border:none;border-radius:4px;background:transparent;color:var(--gh-text-tertiary, #9ca3af);cursor:pointer;transition:all .15s}.gh-queue-item-remove:hover{background:var(--gh-bg-danger, #fef2f2);color:var(--gh-text-danger, #dc2626)}.gh-queue-item-force-send:hover,.gh-queue-item-edit:hover{background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-area{flex:1;min-width:0;display:flex;flex-direction:column;gap:6px}.gh-queue-item-edit-input{width:100%;padding:6px 8px;border:1px solid var(--gh-accent, #4285f4);border-radius:6px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:vertical;min-height:48px;max-height:120px;outline:none;font-family:inherit}.gh-queue-item-edit-actions-row{display:flex;align-items:center;justify-content:flex-end;gap:4px}.gh-queue-item-edit-btn-save,.gh-queue-item-edit-btn-cancel{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border:none;border-radius:4px;background:transparent;cursor:pointer;transition:all .15s}.gh-queue-item-edit-btn-save{color:var(--gh-accent, #4285f4)}.gh-queue-item-edit-btn-save:hover{background:var(--gh-bg-accent, #eef2ff)}.gh-queue-item-edit-btn-cancel{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-item-edit-btn-cancel:hover{background:var(--gh-bg-tertiary, #f3f4f6);color:var(--gh-text, #1f2937)}.gh-queue-item[data-status=sending]{border-left:3px solid var(--gh-accent, #4285f4)}.gh-queue-item[data-status=sent]{opacity:.5}.gh-queue-item[data-status=failed]{border-left:3px solid var(--gh-text-danger, #dc2626)}.gh-queue-input-area{padding:12px;border-top:1px solid var(--gh-border-light, #f3f4f6)}.gh-queue-input-wrapper{display:flex;align-items:flex-end;gap:8px}.gh-queue-input{flex:1;min-height:36px;max-height:120px;padding:8px 12px;border:1.5px solid var(--gh-border, #e5e7eb);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;resize:none;outline:none;font-family:inherit;transition:border-color .15s}.gh-queue-input:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-input::placeholder{color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-send-btn{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:36px;height:36px;border:none;border-radius:10px;background:var(--gh-accent, #4285f4);color:#fff;cursor:pointer;font-size:16px;transition:all .15s}.gh-queue-send-btn:hover{background:var(--gh-accent-hover, #3b78e7)}.gh-queue-send-btn:disabled{opacity:.5;cursor:not-allowed}.gh-queue-status{display:flex;align-items:center;gap:6px;padding:6px 12px;font-size:11px;color:var(--gh-text-tertiary, #9ca3af)}.gh-queue-disable-hint{margin-left:4px;opacity:.6;font-size:10px;cursor:help}.gh-queue-status-dot{width:6px;height:6px;border-radius:50%;background:#22c55e}.gh-queue-status-dot[data-generating=true]{background:#f59e0b;animation:gh-queue-pulse 1.5s infinite}@keyframes gh-queue-pulse{0%,to{opacity:1}50%{opacity:.4}}.gh-queue-shortcut-hint{margin-left:auto;font-size:10px;color:var(--gh-text-tertiary, #9ca3af);opacity:.6}.gh-queue-batch-dialog{max-width:560px}.gh-queue-batch-section{margin-bottom:16px}.gh-queue-batch-tabs{display:flex;gap:6px;margin:12px 0 16px;padding:3px;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:8px;background:var(--gh-bg-secondary, #f9fafb)}.gh-queue-batch-tab{flex:1;height:30px;border:none;border-radius:6px;background:transparent;color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:13px;font-weight:600}.gh-queue-batch-tab[data-active=true]{background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);box-shadow:0 1px 3px #0f172a1f}.gh-queue-batch-label{margin-bottom:8px;font-size:13px;font-weight:600;color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-group{display:flex;gap:8px;flex-wrap:wrap}.gh-queue-batch-mode-btn{padding:8px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:8px;background:var(--gh-bg, #ffffff);color:var(--gh-text-secondary, #6b7280);cursor:pointer;font-size:13px;transition:all .15s ease}.gh-queue-batch-mode-btn:hover{border-color:var(--gh-accent, #4285f4);color:var(--gh-text, #1f2937)}.gh-queue-batch-mode-btn[data-active=true]{border-color:var(--gh-accent, #4285f4);background:var(--gh-bg-accent, #eef2ff);color:var(--gh-accent, #4285f4)}.gh-queue-batch-delimiter-input{margin-bottom:0}.gh-queue-batch-library-search{margin-bottom:10px}.gh-queue-batch-library-list{max-height:260px;overflow-y:auto;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:10px;background:var(--gh-bg, #ffffff)}.gh-queue-batch-library-item{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;padding:9px 10px;border-bottom:1px solid var(--gh-border-light, #e5e7eb);cursor:pointer}.gh-queue-batch-library-item:last-child{border-bottom:none}.gh-queue-batch-library-item:hover{background:var(--gh-hover, #f3f4f6)}.gh-queue-batch-library-item[data-disabled=true]{cursor:not-allowed;opacity:.62}.gh-queue-batch-library-item[data-disabled=true]:hover{background:var(--gh-bg, #ffffff)}.gh-queue-batch-library-main{min-width:0;display:flex;flex-direction:column;gap:3px}.gh-queue-batch-library-title{font-size:13px;font-weight:600;color:var(--gh-text, #1f2937);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-content{font-size:12px;color:var(--gh-text-secondary, #6b7280);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-category{max-width:90px;padding:2px 6px;border-radius:5px;background:var(--gh-hover, #f3f4f6);color:var(--gh-text-secondary, #6b7280);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.gh-queue-batch-library-empty{padding:24px 12px;color:var(--gh-text-tertiary, #9ca3af);font-size:13px;text-align:center}.gh-queue-batch-textarea{width:100%;min-height:160px;max-height:300px;padding:10px 12px;border:1px solid var(--gh-border, #d1d5db);border-radius:10px;background:var(--gh-bg, #ffffff);color:var(--gh-text, #1f2937);font-size:13px;line-height:1.55;resize:vertical;box-sizing:border-box;outline:none;font-family:inherit}.gh-queue-batch-textarea:focus{border-color:var(--gh-accent, #4285f4)}.gh-queue-batch-preview{margin-bottom:20px;padding:12px;border:1px solid var(--gh-border-light, #e5e7eb);border-radius:10px;background:var(--gh-bg-secondary, #f9fafb);display:flex;flex-direction:column}.gh-queue-batch-preview-header{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px;font-size:12px;color:var(--gh-text-secondary, #6b7280)}.gh-queue-batch-preview-body{max-height:220px;overflow-y:auto;min-height:0}.gh-queue-batch-preview-list{margin:0;padding-left:18px;display:flex;flex-direction:column;gap:6px}.gh-queue-batch-preview-item{color:var(--gh-text, #1f2937);font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word}.gh-queue-batch-preview-empty,.gh-queue-batch-preview-more{font-size:12px;color:var(--gh-text-tertiary, #9ca3af)}');const Tx=({adapter:e,dispatcher:t})=>{const[n,r]=z(false),[i,a]=z(false),[s,l]=z(""),[c,d]=z(false),[u,h]=z(""),[g,p]=z("library"),[m,f]=z("line"),[b,y]=z(""),[v,w]=z(""),[x,k]=z("single"),[S,C]=z([]),[E,T]=z(null),[M,I]=z(""),[L,N]=z(null),D=Pv(e=>e.items),q=Pv(),R=Tv(e=>e.prompts),B=P(null),O=P(null),F=P(null),$=D.filter(e=>"pending"===e.status).length,U=D.filter(e=>"pending"===e.status||"sending"===e.status).length,j=D.filter(e=>"pending"===e.status||"sending"===e.status).length,H=Ai(e=>e.settings.features?.prompts?.submitShortcut??"enter"),W=Ai(e=>e.settings?.shortcuts),G=W?.keybindings?.togglePromptQueue,Q=o.useMemo(()=>{if(null===G)return "";const e=navigator.userAgent.toLowerCase().includes("mac");if(G){const t=ir(G);return t?sr(t,e):""}return e?"⌥J":"Alt+J"},[G]),V=o.useMemo(()=>{const e=v.trim().toLowerCase();return [...e?R.filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e)||t.category?.toLowerCase().includes(e)):R].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:(t.lastUsedAt||0)-(e.lastUsedAt||0))},[v,R]),K=o.useMemo(()=>{const e=new Set(S);return R.filter(t=>e.has(t.id)&&0===kx(t.content).length)},[R,S]),Z=o.useMemo(()=>K.flatMap(e=>"line"===x?Cx(e.content):[e.content.trim()].filter(Boolean)),[x,K]),Y=o.useMemo(()=>((e,t,n)=>{const r=Sx(e),o=Sx((e=>e.replace(/\\(\\|n|r|t)/g,(e,t)=>{switch(t){case "n":return "\n";case "r":return "\r";case "t":return "\t";case "\\":return "\\";default:return t}}))(n));return ("line"===t?Cx(e):o?r.split(o):[]).map(e=>e.trim()).filter(Boolean)})(u,m,b),[b,u,m]),J="library"===g?Z:Y,X=A(e=>{let t=e,n=e.parentElement;for(let r=0;r<10&&n&&n!==document.body;r++){const e=window.getComputedStyle(n);if(e.borderRadius&&parseFloat(e.borderRadius)>0){t=n;break}n=n.parentElement;}return t},[]),ee=A(()=>{const t=e.getTextareaElement();if(!t)return void N(null);const n=X(t).getBoundingClientRect(),r=window.innerHeight-n.top+6,o=Math.min(420,window.innerWidth-40);let i=n.right-20-o;i<20&&(i=20);const a=window.innerWidth-(i+o);N({bottom:r,right:a,width:o});},[e,X]);_(()=>{ee();let t=null,n=null;const r=()=>{if(n=e.getTextareaElement(),n){const e=X(n);t=new ResizeObserver(()=>{ee();}),t.observe(n),t.observe(e),n.parentElement&&t.observe(n.parentElement);}};r();const o=setInterval(()=>{ee(),t||n||r();},2e3);return window.addEventListener("resize",ee),()=>{clearInterval(o),window.removeEventListener("resize",ee),t&&t.disconnect();}},[ee,e,X]),_(()=>{const t=setInterval(()=>{a(e.isGenerating());},1e3);return ()=>clearInterval(t)},[e]),_(()=>{const e=()=>{r(e=>!e);};return window.addEventListener("ophel:togglePromptQueue",e),()=>window.removeEventListener("ophel:togglePromptQueue",e)},[]),_(()=>{n&&B.current&&setTimeout(()=>B.current?.focus(),100);},[n]),_(()=>{if(!c||"text"!==g)return;const e=window.setTimeout(()=>O.current?.focus(),60);return ()=>window.clearTimeout(e)},[g,c]),_(()=>{const e=F.current;if(e)return es(e,{capture:false})},[n,L]),_(()=>{if(!n||c)return;const e=e=>{F.current&&!F.current.contains(e.target)&&r(false);},t=setTimeout(()=>{document.addEventListener("mousedown",e);},100);return ()=>{clearTimeout(t),document.removeEventListener("mousedown",e);}},[c,n]);const te=A(async()=>{const e=s.trim();e&&(l(""),i?(q.enqueue(e),t.isRunning()||t.start()):await t.sendImmediately(e,H));},[s,i,q,t,H]),ne=A(e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.stopPropagation(),te()),"Escape"===e.key&&(e.stopPropagation(),r(false));},[te]),re=A(e=>{q.remove(e);},[q]),oe=A(async(e,n)=>{q.remove(e);await t.sendImmediately(n,H)||(q.enqueue(n),t.isRunning()||t.start());},[q,t,H]),ie=A(()=>{q.clear();},[q]),ae=A(()=>{h(""),p("library"),f("line"),y(""),w(""),k("single"),C([]),d(false);},[]),le=A(e=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);},[]),ce=A(async()=>{if("text"===g&&"delimiter"===m&&!b.trim())return void Li(se("queueBatchDelimiterRequired"),2500);if(0===J.length)return void Li(se("queueBatchImportEmpty"),2500);const n=q.enqueueMany(J);0!==n.length?(t.isRunning()||t.start(),e.isGenerating()||await t.processNextNow(),Li(se("queueBatchImportSuccess",{count:String(n.length)}),2500),ae()):Li(se("queueBatchImportEmpty"),2500);},[e,b,J,g,m,t,ae,q]),de=A((e,t)=>{T(e),I(t);},[]),ue=A(e=>{M.trim()&&q.updateContent(e,M.trim()),T(null);},[M,q]),he=A(()=>{T(null);},[]),ge=A(()=>{B.current&&(B.current.style.height="0px",B.current.style.height=Math.min(B.current.scrollHeight,120)+"px");},[]);_(()=>{ge();},[s,ge]);const pe=A(e=>{l(e.target.value);},[]);if(!L)return null;const me=document.querySelector(".gh-root")||document.body,fe={bottom:L.bottom,right:L.right},be={bottom:L.bottom,right:L.right,width:L.width};return n?Le(_e,{children:[np( Le("div",{className:"gh-queue-panel",style:be,ref:F,children:[ Le("div",{className:"gh-queue-header",children:[ Le("div",{className:"gh-queue-header-title",children:[ Ie("span",{children:Ie(We,{size:18,color:"currentColor"})}), Ie("span",{children:se("queueTitle")}),$>0&&Ie("span",{className:"gh-queue-capsule-badge",children:$})]}), Le("div",{className:"gh-queue-header-actions",children:[ Ie(up,{content:se("queueBatchImport"),children:Ie("button",{className:"gh-queue-header-btn",onClick:()=>d(true),children:Ie(Qe,{size:16,color:"currentColor"})})}),j>0&&Ie(up,{content:se("queueClearAll"),children:Ie("button",{className:"gh-queue-header-btn",onClick:ie,children:Ie(Lt,{size:16,color:"currentColor"})})}), Ie(up,{content:se("collapse"),children:Ie("button",{className:"gh-queue-header-btn",onClick:()=>r(false),children:Le("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Ie("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]})]}), Ie("div",{className:"gh-queue-list",children:0===D.filter(e=>"pending"===e.status||"sending"===e.status).length?Ie("div",{className:"gh-queue-empty",children:se("queueEmpty")}):D.filter(e=>"pending"===e.status||"sending"===e.status).map((e,t)=>Le("div",{className:"gh-queue-item","data-status":e.status,children:[ Ie("span",{className:"gh-queue-item-index",children:t+1}),E===e.id?Le("div",{className:"gh-queue-item-edit-area",children:[ Ie("textarea",{className:"gh-queue-item-edit-input",value:M,onChange:e=>{I(e.target.value);const t=e.target;t.style.height="0px",t.style.height=Math.min(t.scrollHeight,120)+"px";},onKeyDown:t=>{"Enter"!==t.key||t.shiftKey||(t.preventDefault(),ue(e.id)),"Escape"===t.key&&he();},autoFocus:true}), Le("div",{className:"gh-queue-item-edit-actions-row",children:[ Ie("button",{className:"gh-queue-item-edit-btn-save",onClick:()=>ue(e.id),title:se("queueEditSave"),children:Ie("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:Ie("polyline",{points:"20 6 9 17 4 12"})})}), Ie("button",{className:"gh-queue-item-edit-btn-cancel",onClick:he,title:se("queueEditCancel"),children:Le("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Ie("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}):Le(_e,{children:[ Ie("span",{className:"gh-queue-item-content",children:e.content}), Le("div",{className:"gh-queue-item-actions",children:["pending"===e.status&&Ie("button",{className:"gh-queue-item-edit",onClick:()=>de(e.id,e.content),title:se("queueEdit"),children:Le("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}), Ie("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),"pending"===e.status&&Ie("button",{className:"gh-queue-item-force-send",onClick:()=>oe(e.id,e.content),title:se("queueForceSend"),children:Le("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Ie("polyline",{points:"5 12 12 5 19 12"})]})}), Ie("button",{className:"gh-queue-item-remove",onClick:()=>re(e.id),title:se("queueRemove"),children:Le("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("line",{x1:"18",y1:"6",x2:"6",y2:"18"}), Ie("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})]},e.id))}), Ie("div",{className:"gh-queue-input-area",children:Le("div",{className:"gh-queue-input-wrapper",children:[ Ie("textarea",{ref:B,className:"gh-queue-input",value:s,onChange:pe,onKeyDown:ne,placeholder:se(i?"queuePlaceholderBusy":"queuePlaceholderIdle"),rows:1}), Ie("button",{className:"gh-queue-send-btn",onClick:te,disabled:!s.trim(),title:"Enter",children:Le("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("line",{x1:"12",y1:"19",x2:"12",y2:"5"}), Ie("polyline",{points:"5 12 12 5 19 12"})]})})]})}), Le("div",{className:"gh-queue-status",children:[ Ie("span",{className:"gh-queue-status-dot","data-generating":i?"true":"false"}), Ie("span",{children:se(i?"queueStatusBusy":"queueStatusIdle")}), Le("span",{className:"gh-queue-disable-hint",title:se("queueSettingDesc"),children:["(",se("queueDisableHint"),")"]}),Q&&Ie("span",{className:"gh-queue-shortcut-hint",children:Q})]})]}),me),c&&Le(Iw,{onClose:ae,closeOnOverlayClick:false,closeOnEscape:false,dialogClassName:"gh-queue-batch-dialog",dialogStyle:{maxWidth:560,width:"min(560px, calc(100vw - 32px))"},children:[ Ie("div",{className:"gh-dialog-title",children:se("queueBatchImportTitle")}), Ie("div",{className:"gh-dialog-message",children:se("queueBatchImportDesc")}), Le("div",{className:"gh-queue-batch-tabs",children:[ Ie("button",{className:"gh-queue-batch-tab","data-active":"library"===g,onClick:()=>p("library"),children:se("queueBatchLibraryTab")}), Ie("button",{className:"gh-queue-batch-tab","data-active":"text"===g,onClick:()=>p("text"),children:se("queueBatchTextTab")})]}),"text"===g&&Le(_e,{children:[ Le("div",{className:"gh-queue-batch-section",children:[ Ie("div",{className:"gh-queue-batch-label",children:se("queueBatchSplitModeLabel")}), Le("div",{className:"gh-queue-batch-mode-group",children:[ Ie("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===m,onClick:()=>f("line"),children:se("queueBatchSplitModeLine")}), Ie("button",{className:"gh-queue-batch-mode-btn","data-active":"delimiter"===m,onClick:()=>f("delimiter"),children:se("queueBatchSplitModeDelimiter")})]})]}),"delimiter"===m&&Le("div",{className:"gh-queue-batch-section",children:[ Ie("div",{className:"gh-queue-batch-label",children:se("queueBatchDelimiterLabel")}), Ie("input",{className:"gh-dialog-input gh-queue-batch-delimiter-input",value:b,onChange:e=>y(e.target.value),placeholder:se("queueBatchDelimiterPlaceholder")})]}), Le("div",{className:"gh-queue-batch-section",children:[ Ie("div",{className:"gh-queue-batch-label",children:se("queueBatchInputLabel")}), Ie("textarea",{ref:O,className:"gh-queue-batch-textarea",value:u,onChange:e=>h(e.target.value),placeholder:se("queueBatchInputPlaceholder")})]})]}),"library"===g&&Le(_e,{children:[ Le("div",{className:"gh-queue-batch-section",children:[ Ie("div",{className:"gh-queue-batch-label",children:se("queueBatchLibraryModeLabel")}), Le("div",{className:"gh-queue-batch-mode-group",children:[ Ie("button",{className:"gh-queue-batch-mode-btn","data-active":"single"===x,onClick:()=>k("single"),children:se("queueBatchLibraryModeSingle")}), Ie("button",{className:"gh-queue-batch-mode-btn","data-active":"line"===x,onClick:()=>k("line"),children:se("queueBatchSplitModeLine")})]})]}), Le("div",{className:"gh-queue-batch-section",children:[ Ie("div",{className:"gh-queue-batch-label",children:se("queueBatchLibrarySearchLabel")}), Ie("input",{className:"gh-dialog-input gh-queue-batch-library-search",value:v,onChange:e=>w(e.target.value),placeholder:se("queueBatchLibrarySearchPlaceholder")}), Ie("div",{className:"gh-queue-batch-library-list",children:0===V.length?Ie("div",{className:"gh-queue-batch-library-empty",children:se("queueBatchLibraryEmpty")}):V.slice(0,80).map(e=>{const t=kx(e.content).length>0; return Le("label",{className:"gh-queue-batch-library-item","data-disabled":t?"true":"false",title:t?se("queueBatchLibraryVariablePrompt"):void 0,children:[ Ie("input",{type:"checkbox",disabled:t,checked:!t&&S.includes(e.id),onChange:()=>{t||le(e.id);}}), Le("span",{className:"gh-queue-batch-library-main",children:[ Ie("span",{className:"gh-queue-batch-library-title",children:e.title}), Ie("span",{className:"gh-queue-batch-library-content",children:t?se("queueBatchLibraryVariablePrompt"):e.content})]}), Ie("span",{className:"gh-queue-batch-library-category",children:e.category||se("uncategorized")})]},e.id)})})]})]}), Le("div",{className:"gh-queue-batch-preview",children:[ Le("div",{className:"gh-queue-batch-preview-header",children:[ Ie("span",{children:se("queueBatchPreviewTitle")}), Ie("span",{children:se("queueBatchPreviewCount",{count:String(J.length)})})]}), Ie("div",{className:"gh-queue-batch-preview-body",children:0===J.length?Ie("div",{className:"gh-queue-batch-preview-empty",children:se("queueBatchPreviewEmpty")}):Le(_e,{children:[ Ie("ol",{className:"gh-queue-batch-preview-list",children:J.slice(0,5).map((e,t)=>Ie("li",{className:"gh-queue-batch-preview-item",children:e},`${t}-${e.slice(0,20)}`))}),J.length>5&&Ie("div",{className:"gh-queue-batch-preview-more",children:se("queueBatchPreviewMore",{count:String(J.length-5)})})]})})]}), Le("div",{className:"gh-dialog-buttons",children:[ Ie("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:ae,children:se("cancel")}), Ie("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:()=>{ce();},disabled:0===J.length||"text"===g&&"delimiter"===m&&!b.trim(),children:se("queueBatchImportAction")})]})]})]}):np( Ie(up,{content:Q||se("queueQuickAsk"),children:Le("div",{className:"gh-queue-capsule",style:fe,onClick:()=>r(true),children:[ Ie("span",{className:"gh-queue-capsule-icon",children:Ie(We,{size:18,color:"currentColor"})}), Ie("span",{children:U>0?se("queueInQueue",{count:String(U)}):se("queueQuickAsk")})]})}),me)},Mx=()=>({width:window.innerWidth,height:window.innerHeight}),_x=(e,t)=>e&&t?e.xRatio===t.xRatio&&e.yRatio===t.yRatio:e===t,Ix=3e3,Lx=({isPanelExpanded:e,onPanelToggle:t,onPanelLogoHoverStart:n,onPanelLogoHoverEnd:r,onThemeToggle:i,themeMode:a,onExport:s,onMove:l,onSetTag:c,onScrollLock:d,onSettings:u,onCleanup:h,onGlobalSearch:g,scrollLocked:p,onCopyMarkdown:m,onModelLockToggle:f,isModelLocked:b,onOpenSettings:y,isScrolling:v})=>{const w=A(e=>{const t=e.getBoundingClientRect();return {clientX:t.left+t.width/2,clientY:t.top+t.height/2}},[]),{settings:x,updateNestedSetting:k}=Ai(),S=x||Jo,C=tv(),E=S.quickButtons||Jo.quickButtons,T=q(()=>E.collapsed||[],[E.collapsed]),M=S.panel?.defaultPosition??"right",I="left"===M?{left:"16px",right:"auto"}:{right:"16px",left:"auto"},L=Math.min(Math.max(E.opacity??1,.4),1),N=E.position??null,R=E.proximityRadius??150,O=C?.getSiteId()||"_default",F=Xo(S,O),$=a||("dark"===F.mode?"dark":"light");"light"===$?F.lightStyleId:F.darkStyleId;const U="dark"===$?"brand":"currentColor",j=P(null),[H,W]=z(false),[G,Q]=z(Mx),V=P(G),K=P(G),[Z,Y]=z({width:0,height:0}),J=A(e=>{V.current=e,Q(t=>t.width===e.width&&t.height===e.height?t:e);},[]);_(()=>{if(!H)return;const e=e=>{const t=e.target;j.current&&!j.current.contains(t)&&W(false);};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[H]);const[X,ee]=z(N),[te,ne]=z(false),[re,oe]=z(false),ie=P(N),ae=P(N),le=P({width:0,height:0}),[ce,de]=z(null),ue=P(null),he=P(null),ge=P(null),pe=P(null),me=P(false),fe=P(null),be=P(false),ye=P(null),ve=null!==B(tw,nw),[we,xe]=z(0);_(()=>{if(0===we)return;const e=setTimeout(()=>xe(0),400);return ()=>clearTimeout(e)},[we]);const[ke,Se]=z(false),[Ce,Ae]=z(true),Ee=P(null),Te=P(false),Me=A((e=3e3)=>{Ae(true),null!==Ee.current&&window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{Ae(false);},e);},[]),qe=A(e=>{null!==Ee.current&&(window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{Ae(false);},e));},[]);_(()=>{const t=te||re||e||H;Te.current=t,t?(Ae(true),null!==Ee.current&&(window.clearTimeout(Ee.current),Ee.current=null)):Me(4e3);},[te,re,e,H,Me]),_(()=>{let e=null;const t=t=>{null===e&&0!==R&&(e=requestAnimationFrame(()=>{if(e=null,!j.current||Te.current)return;const n=j.current.getBoundingClientRect(),r=Math.max(n.left-t.clientX,0,t.clientX-n.right),o=Math.max(n.top-t.clientY,0,t.clientY-n.bottom),i=Math.sqrt(r*r+o*o);R>0&&i<=R&&Me(Ix);}));},n=()=>{qe(1500);},r=()=>{document.hidden&&qe(1500);};return document.addEventListener("mousemove",t,{passive:true}),document.addEventListener("mouseleave",n,{passive:true}),document.addEventListener("visibilitychange",r),Me(Ix),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseleave",n),document.removeEventListener("visibilitychange",r),null!==e&&cancelAnimationFrame(e),null!==Ee.current&&window.clearTimeout(Ee.current);}},[Me,qe,R]);const Re=!(Ce||ke||H||e||te||re);P(Re).current=Re;const Pe=q(()=>{if(te||re||H)return false;if(Re)return false;if(E.hideWhenPanelOpen&&e)return true;const t=e&&"edge-snap"!==(S.panel?.panelMode??"edge-snap");for(const n of T){if("manualAnchor"===n.id)continue;const r=Hr[n.id];if(!r)continue;if((!r.canToggle||n.enabled)&&!(r.isPanelOnly&&e||r.hideWhenPanelOpen&&t))return false}return true},[te,re,H,Re,e,T,S.panel?.panelMode,E.hideWhenPanelOpen]),[ze,Be]=z(false),[Oe,Fe]=z(false),[$e,Ue]=z(""),je=P(false),He=A(()=>{null!==ye.current&&(window.clearTimeout(ye.current),ye.current=null);},[]),We=A(e=>{const t=e??null;He(),_x(ae.current,t)||(ae.current=t,k("quickButtons","position",t||void 0));},[He,k]);A(e=>{if(_x(ae.current,e))return;He();const t={...e};ye.current=window.setTimeout(()=>{ye.current=null,_x(ae.current,t)||(ae.current=t,k("quickButtons","position",t));},220);},[220,He,k]),_(()=>{const e=!_x(ae.current,N);e&&He(),ae.current=N,e&&!me.current&&(ie.current=N,ee(N));},[He,N]),_(()=>()=>{He();},[He]),_(()=>{N&&(ue.current=null,de(null));},[N]);const Ge=A((e,t=le.current)=>{const n=t.width,r=t.height;return {width:n,height:r,maxX:Math.max(8,e.width-n-8),maxY:Math.max(8,e.height-r-8)}},[8]),Qe=A((e,t,n,r=le.current)=>{const{width:o,height:i,maxX:a,maxY:s}=Ge(n,r);return {x:Math.min(Math.max(e,8),a),y:Math.min(Math.max(t,8),s),width:o,height:i,maxX:a,maxY:s}},[8,Ge]),Ve=A((e,t,n,r=le.current)=>{const o=Qe(e,t,n,r),i=Math.max(1,o.maxX-8),a=Math.max(1,o.maxY-8);return {xRatio:Math.min(1,Math.max(0,(o.x-8)/i)),yRatio:Math.min(1,Math.max(0,(o.y-8)/a))}},[8,Qe]),Ke=A((e,t,n=le.current)=>{if(!e)return null;const{maxX:r,maxY:o}=Ge(t,n),i=Math.max(1,r-8),a=Math.max(1,o-8),s=8+e.xRatio*i,l=8+e.yRatio*a;return {x:Math.min(Math.max(s,8),r),y:Math.min(Math.max(l,8),o)}},[8,Ge]);D(()=>{const e=j.current;if(!e)return;const t=()=>{const t=e.getBoundingClientRect(),n={width:t.width,height:t.height},r=le.current,o=0===r.width&&0===r.height;if(!(r.width!==n.width||r.height!==n.height))return;le.current=n,Y(n);const i=Mx(),a=K.current,s=a.width!==i.width||a.height!==i.height;if(K.current=i,V.current.width===i.width&&V.current.height===i.height||J(i),!ie.current){const e=ue.current??t.top,r=Qe(0,e,i,n).y;return void(ue.current!==r&&(ue.current=r,de(r)))}if(me.current||o||s)return;const l=Ve(t.left,t.top,i,n),c=ie.current;c.xRatio===l.xRatio&&c.yRatio===l.yRatio||(ie.current=l,ee(l));};t();const n=new ResizeObserver(()=>{t();});return n.observe(e),()=>{n.disconnect();}},[Qe,J,Ve]);const Ze=A(async()=>{je.current=false;const e=new AbortController,t=setInterval(()=>{je.current&&e.abort();},100);let n=setTimeout(()=>{je.current||(Fe(true),Ue(se("loadingHistory")));},1600);try{const t=await ww({adapter:C,loadAll:!0,signal:e.signal,allowShortCircuit:!0,onProgress:e=>{Ue(`${se("loadingHistory")} ${e}`);}});ew(t.previousScrollTop),Be(t.isFlutterMode),n&&(window.clearTimeout(n),n=null),Fe(!1),Ue(""),t.success&&!t.silent&&Li(se("historyLoaded"),2e3);}finally{clearInterval(t),n&&window.clearTimeout(n);}},[C]),Ye=A(()=>{je.current=true;},[]),Je=A(async()=>{const{previousScrollTop:e,container:t}=await cw(C);ew(e),Be(pw(t));},[C]),Xe=A(async()=>{const e=Xv();if(null===e)return;xe(e=>e+1);const t=(await hw(C)).scrollTop;await dw(C,e),ew(t);},[C]),et=A(async()=>{const e=await hw(C);ew(e.scrollTop),Be(e.isFlutterMode);},[C]),tt=Ke(X,G,Z),nt=Ge(G,Z),rt=tt&&nt.width>0?tt.x+nt.width/2<=G.width/2?"side-right":"side-left":"left"===M?"side-right":"side-left",ot={scrollTop:Ze,scrollBottom:Je,panel:t,anchor:Xe,theme:e=>{e?.stopPropagation();const t=e?.currentTarget;t?i?.(w(t)):i?.();},floatingToolbar:e=>{e?.stopPropagation(),W(e=>!e);},globalSearch:e=>{e?.stopPropagation(),W(false),g?.();},zenMode:e=>{e?.stopPropagation();const t=C?.getSiteId()||"_default",n=!(x?.layout?.zenMode?.[t]?.enabled||false);k("layout","zenMode",{[t]:{enabled:n}}),n&&k("layout","cleanMode",{[t]:{enabled:true}});},settings:e=>{e?.stopPropagation(),W(false),y?.();}},it=(t,o,i)=>{const s=o.isPanelOnly,l=!i,c="floatingToolbar"===t,d="zenMode"===t,u=d&&Boolean(x?.layout?.zenMode?.[O]?.enabled),h=c?H:u,g=e&&"edge-snap"!==(x?.panel?.panelMode??"edge-snap");if(l||s&&e||o.hideWhenPanelOpen&&g)return null;let p;if("theme"===t)p=Ie("dark"===a?Ne:De,{size:20});else if(u)p=Ie($t,{size:18,color:"currentColor"});else if(o.IconComponent){const e=o.IconComponent;p=Ie(e,{size:"panel"===t?21:18,color:"panel"===t?U:void 0});}else p=o.icon;const m="anchor"===t,f="panel"===t,b=m&&!ve,y=se(m?ve?"goToAnchor":"noAnchor":o.labelKey); return Ie(up,{content:y,children:Ie("button",{className:`quick-prompt-btn gh-interactive ${s?"panel-only":""} ${f?"panel-btn":""} ${h?"active":""} ${c?"tools-trigger-btn":""} ${d?"zen-mode-btn":""}`,onClick:e=>ot[t]?.(e),onMouseEnter:e=>{f&&n?.(e.currentTarget.getBoundingClientRect(),{waitForGroupDwell:Re&&0===R});},onMouseLeave:()=>{f&&r?.();},"data-tip-target":"globalSearch"===t?"search-btn":"floatingToolbar"===t?"toolbar-btn":"shortcuts"===t?"shortcuts-btn":"settings"===t?"settings-btn":void 0,style:{opacity:b?.4:1,cursor:b?"default":"pointer"},disabled:b,children:m?Ie("span",{className:"anchor-tap-wrapper"+(we>0?" is-tapping":""),onAnimationEnd:()=>xe(0),style:{display:"flex"},children:p},we):p})},t)},at=e=>{if(!e)return null;const t=Hr.manualAnchor,n=t?.IconComponent; return Ie(o.Fragment,{children:Ie(up,{content:se("setAnchor"),children:Ie("button",{className:"quick-prompt-btn manual-anchor-btn set-btn gh-interactive",onClick:et,children:n?Ie(n,{size:18}):"📍"})})},"manualAnchor")},st=(e,t)=>Ie("div",{className:"divider "},t),lt={[Eo]:()=>s?.(),[To]:()=>m?.(),[Mo]:()=>l?.(),[_o]:()=>c?.(),[Io]:()=>d?.(!p),[Lo]:()=>f?.(),[No]:()=>h?.(),[Do]:()=>u?.()},ct=e=>e===Io?p||false:e===Lo&&b||false;_(()=>{if(!j.current)return;let e=null,t=null;const n=()=>{e&&(clearTimeout(e),e=null),0===R?t=window.setTimeout(()=>{Se(true);},300):Se(true);},r=()=>{t&&(clearTimeout(t),t=null),e=window.setTimeout(()=>{Se(false);},300);},o=j.current;return o.addEventListener("mouseenter",n),o.addEventListener("mouseleave",r),()=>{o.removeEventListener("mouseenter",n),o.removeEventListener("mouseleave",r),e&&clearTimeout(e),t&&clearTimeout(t);}},[Qe,R]),_(()=>{let e=null,t=null,n=false;const r=()=>{const e=Mx();if(J(e),ie.current||null===ue.current)return;const t=Qe(0,ue.current,e,le.current).y;ue.current!==t&&(ue.current=t,de(t));},o=()=>{null===e?e=requestAnimationFrame(()=>{e=null,r(),n&&(n=false,o());}):n=true;},i=()=>{o(),null!==t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,r();},120);};return window.addEventListener("resize",i),window.visualViewport?.addEventListener("resize",i),()=>{window.removeEventListener("resize",i),window.visualViewport?.removeEventListener("resize",i),null!==e&&cancelAnimationFrame(e),null!==t&&window.clearTimeout(t);}},[Qe,J]);const dt=()=>{he.current&&(window.clearTimeout(he.current),he.current=null);},ut=()=>{(()=>{const e=me.current;oe(false),dt(),ge.current=null,pe.current=null,me.current&&(He(),me.current=false,ne(false)),j.current&&null!==fe.current&&j.current.hasPointerCapture(fe.current)&&j.current.releasePointerCapture(fe.current),fe.current=null,e&&We(ie.current);})();}; return Le(_e,{children:[ Ie(Zw,{isVisible:Oe,text:$e,onStop:Ye}), Le("div",{ref:j,className:`quick-btn-group gh-interactive ${e?"":"collapsed"} ${te?"dragging":""} ${re?"pressing":""} ${v?"scroll-hidden":""} ${Re?"liquid-collapsed":""} ${Pe?"group-hidden":""}`,"aria-hidden":Pe,onPointerDown:e=>{if(0!==e.button)return;if(!j.current)return;fe.current=e.pointerId,ge.current={x:e.clientX,y:e.clientY},be.current=false,oe(true);const t=j.current.getBoundingClientRect();pe.current={x:e.clientX-t.left,y:e.clientY-t.top},dt(),he.current=window.setTimeout(()=>{j.current&&null!==fe.current&&(He(),j.current.setPointerCapture(fe.current),oe(false),me.current=true,be.current=true,ne(true));},220);},onPointerMove:e=>{if(!ge.current)return;if(!me.current){const t=e.clientX-ge.current.x,n=e.clientY-ge.current.y;return void(Math.hypot(t,n)>6&&(dt(),oe(false)))}e.preventDefault();const t=Mx(),n=pe.current||{x:0,y:0},r=e.clientX-n.x,o=e.clientY-n.y,i=Ve(r,o,t);J(t),ie.current=i,ee(i);},onPointerUp:ut,onPointerCancel:ut,onPointerLeave:()=>{me.current||(dt(),oe(false),ge.current=null,pe.current=null,fe.current=null);},onClickCapture:e=>{be.current&&(e.preventDefault(),e.stopPropagation(),be.current=false);},style:{position:"fixed",top:tt?`${tt.y}px`:null!==ce?`${ce}px`:"50%",left:tt?`${tt.x}px`:I.left,right:tt?"auto":I.right,transform:tt||null!==ce?"none":"translateY(-50%)",opacity:Pe?0:L,pointerEvents:Pe?"none":void 0},children:[ Ie("div",{className:"quick-btn-drag-handle",style:{"--quick-btn-press-duration":"220ms"},"aria-hidden":"true"}),(()=>{if(Re)return [it("panel",Hr.panel,true)];const t=[],n=new Set(["scrollTop","scrollBottom","anchor","manualAnchor"]),r=T.map(t=>{if("manualAnchor"===t.id)return null;const r=Hr[t.id];if(!r)return null;const o=!r.canToggle||t.enabled;if(!o)return null;if(r.isPanelOnly&&e)return null;const i=e&&"edge-snap"!==(x?.panel?.panelMode??"edge-snap");return r.hideWhenPanelOpen&&i?null:{id:t.id,def:r,enabled:o,group:n.has(t.id)?"navigation":"tools"}}).filter(e=>null!==e);let o=0;for(;o=2&&ne.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(()=>{const e=[];let t=false,n=false;const r=E.toolsMenu??qo.map(e=>e.id),o=new Set(r);for(const i of qo){if(!(i.isSystem||o.has(i.id)))continue;i.isDanger&&!t&&(e.push(Ie("div",{className:"menu-divider"},`divider-before-${i.id}`)),t=true),i.isSystem&&!n&&(e.push(Ie("div",{className:"menu-divider"},`divider-before-${i.id}`)),n=true);const r=i.IconComponent,a=`quick-menu-btn ${!!i.isToggle&&ct(i.id)?"active":""} ${i.isDanger?"danger":""}`;e.push( Ie(up,{content:se(i.labelKey),children:Ie("button",{className:a,onClick:()=>{lt[i.id]?.(),W(false);},children:Ie(r,{size:18})})},i.id));}return e})()})]})]})},Nx="50%",Dx=({title:e,onClear:t,adapter:n})=>{const[r,o]=z(120),[i,a]=z(Nx),s=P(null),l=P(null),c=P(null),d=A(e=>{let t=e,n=e.parentElement;for(let r=0;r<10&&n&&n!==document.body;r++){const e=window.getComputedStyle(n);if(e.borderRadius&&parseFloat(e.borderRadius)>0){t=n;break}n=n.parentElement;}return t},[]),u=A(()=>{const e=n?.getTextareaElement();if(!e||!e.isConnected)return o(e=>120===e?e:120),a(e=>e===Nx?e:Nx),void(c.current=null);const t=l.current,r=t&&t.isConnected&&t.contains(e)?t:d(e),i=r.getBoundingClientRect(),u=window.innerHeight,h={left:Math.round(i.left),top:Math.round(i.top),width:Math.round(i.width),height:Math.round(i.height),viewportHeight:u};r!==l.current&&s.current&&(l.current&&s.current.unobserve(l.current),s.current.observe(r),l.current=r);const g=c.current;if(g&&g.left===h.left&&g.top===h.top&&g.width===h.width&&g.height===h.height&&g.viewportHeight===h.viewportHeight)return;c.current=h;const p=u-h.top+6,m=Math.max(50,Math.min(p,u-50));o(e=>e===m?e:m);const f=`${Math.round(h.left+h.width/2)}px`;a(e=>e===f?e:f);},[n,d]);return _(()=>{if(!e)return;const t=n?.getTextareaElement();if(s.current=new ResizeObserver(()=>{u();}),t){const e=d(t);s.current.observe(e),l.current=e;}u();const r=[50,200,400].map(e=>setTimeout(u,e));let o=null;const i=()=>{u(),o=window.requestAnimationFrame(i);};return o=window.requestAnimationFrame(i),window.addEventListener("resize",u),()=>{window.removeEventListener("resize",u),r.forEach(e=>clearTimeout(e)),null!==o&&window.cancelAnimationFrame(o),s.current&&(s.current.disconnect(),s.current=null),l.current=null,c.current=null;}},[e,n,d,u]),e?Le("div",{className:"selected-prompt-bar gh-interactive",style:{position:"fixed",bottom:`${r}px`,left:i,transform:"translateX(-50%)",zIndex:999998},children:[ Ie("span",{className:"selected-prompt-label",children:se("currentPrompt")}), Ie(up,{content:e,children:Ie("span",{className:"selected-prompt-text",children:e})}), Ie(up,{content:se("clear"),children:Ie("button",{className:"clear-prompt-btn",type:"button","aria-label":se("clear"),onClick:t,children:Ie(Re,{size:14})})})]}):null};function qx(){const e=q(()=>Vw(),[]); return Le("div",{className:"sidebar-community-links",children:[ Ie(up,{content:se("rateAndReview"),children:Ie("a",{href:e.url,target:"_blank",rel:"noopener noreferrer","aria-label":se("rateAndReview"),className:"sidebar-social-btn review-btn",children:o.cloneElement(e.icon,{size:18})})}), Ie(up,{content:se("giveStar"),children:Ie("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer","aria-label":se("giveStar"),className:"sidebar-social-btn github-btn",children:Ie(ct,{size:18})})}), Ie(up,{content:se("kofiSupport"),children:Ie("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer","aria-label":se("kofiSupport"),className:"sidebar-social-btn kofi-btn",children:Ie(Xt,{size:18})})}), Ie(up,{content:se("discordCommunity"),children:Ie("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer","aria-label":se("discordCommunity"),className:"sidebar-social-btn discord-btn",children:Ie(Jt,{size:18})})})]})}const Rx={"zh-CN":"简体中文","zh-TW":"繁體中文",en:"English",es:"Español",pt:"Português",ru:"Русский",ja:"日本語",de:"Deutsch",fr:"Français",ko:"한국어"},Px=({currentLang:e,themeMode:t="light",onSelect:n,onClose:r,triggerRef:o})=>{const i=P(null),[a,s]=z({top:0,left:0});_(()=>{if(!o.current)return;const e=o.current.getBoundingClientRect();s({top:e.top-10,left:e.right});},[o]);const l="dark"===t?{bg:"#1f2937",border:"#374151",text:"#e5e7eb",hover:"#374151",activeBg:"rgba(59, 130, 246, 0.2)"}:{bg:"#ffffff",border:"#e5e7eb",text:"#374151",hover:"#f3f4f6",activeBg:"rgba(59, 130, 246, 0.1)"};return np( Le("div",{className:"lang-menu-portal",style:{position:"relative",zIndex:2147483647},children:[ Ie("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:2e6,background:"transparent"},onClick:e=>{e.stopPropagation(),r();}}), Ie("div",{ref:i,style:{position:"fixed",bottom:window.innerHeight-a.top+5,left:a.left-150,width:"150px",background:l.bg,border:`1px solid ${l.border}`,borderRadius:"8px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)",padding:"4px",zIndex:2000001,animation:"ophel-lang-pop 0.1s ease-out",display:"flex",flexDirection:"column",maxHeight:"500px",overflowY:"auto"},children:Object.entries(Rx).map(([t,r])=>Le("button",{onClick:e=>{e.stopPropagation(),n(t);},style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",border:"none",background:e===t?l.activeBg:"transparent",color:e===t?"#3b82f6":l.text,fontSize:"13px",cursor:"pointer",borderRadius:"4px",textAlign:"left",width:"100%",fontWeight:e===t?500:400,transition:"background-color 0.1s"},onMouseEnter:n=>{e!==t&&(n.currentTarget.style.backgroundColor=l.hover);},onMouseLeave:n=>{e!==t&&(n.currentTarget.style.backgroundColor=e===t?l.activeBg:"transparent");},children:[ Ie("span",{children:r}),e===t&&Ie("span",{children:"✓"})]},t))}), Ie("style",{children:"\n @keyframes ophel-lang-pop {\n from { opacity: 0; transform: scale(0.95); }\n to { opacity: 1; transform: scale(1); }\n }\n "})]}),document.body)},zx=({siteId:e="_default"})=>{const{settings:t,setSettings:n}=Ai(),r=!window.__ophelThemeManager,i=window.__ophelThemeManager,a=B(i?.subscribe??(()=>()=>{}),i?.getSnapshot??(()=>"light")),s=t?.theme?.sites,l=s&&e in s?s[e]:s?._default,c=l?.mode||"light",d=async(r,o)=>{if(c===r)return;const i=window.__ophelThemeManager;if(i?.setMode)await i.setMode(r,o?.nativeEvent);else {const o=t?.theme?.sites||{},i=o[e]||o._default||{};n({theme:{...t?.theme,sites:{...o,[e]:{lightStyleId:"google-gradient",darkStyleId:"classic-dark",...i,mode:r}}}});}},u=e=>{n({language:e}),ie(e);},h=ae(t?.language||"auto"),[g,p]=o.useState(false),m=o.useRef(null),f=o.useRef(null),[b,y]=o.useState("normal"),v=o.useRef("normal"),w={en:"EN","zh-CN":"简","zh-TW":"繁",ja:"JP",ko:"KR",fr:"FR",de:"DE",ru:"RU",es:"ES",pt:"PT"},x=["zh-CN","en"],k=x.includes(h)?"es":h,S=Array.from(new Set([...x,k]));return o.useEffect(()=>{v.current=b;},[b]),o.useEffect(()=>{const e=f.current;if(!e)return;const t=t=>{e.classList.toggle("is-compact","compact"===t),e.classList.toggle("is-icon","icon"===t);},n=n=>(t(n),e.scrollWidth<=e.clientWidth+1),r=()=>{let e="normal";if(!n("normal")){e=n("compact")?"compact":"icon";}t(e),e!==v.current&&y(e);},o=()=>{"function"!=typeof requestAnimationFrame?r():requestAnimationFrame(r);};if(o(),"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(()=>o());return t.observe(e),()=>t.disconnect()}return window.addEventListener("resize",o),()=>window.removeEventListener("resize",o)},[h]),Le("div",{className:"settings-sidebar-footer",children:[!r&&Le("div",{ref:f,className:`settings-theme-segmented ${"compact"===b?"is-compact":""} ${"icon"===b?"is-icon":""}`,children:[ Ie(up,{content:se("themeLight"),triggerStyle:{flex:1},children:Le("button",{className:"settings-theme-segment "+("light"===c?"active":""),onClick:e=>d("light",e),children:[ Ie("span",{className:"segment-icon",children:Ie(Ne,{size:16})}), Ie("span",{className:"segment-label",children:se("themeLight")})]})}), Ie(up,{content:se("themeDark"),triggerStyle:{flex:1},children:Le("button",{className:"settings-theme-segment "+("dark"===c?"active":""),onClick:e=>d("dark",e),children:[ Ie("span",{className:"segment-icon",children:Ie(De,{size:16})}), Ie("span",{className:"segment-label",children:se("themeDark")})]})}), Ie(up,{content:se("themeSystem"),triggerStyle:{flex:1},children:Le("button",{className:"settings-theme-segment "+("system"===c?"active":""),onClick:e=>d("system",e),children:[ Ie("span",{className:"segment-icon",children:Ie(qe,{size:16})}), Ie("span",{className:"segment-label",children:se("themeSystem")})]})})]}), Le("div",{className:"settings-lang-inline",children:[ Ie("button",{className:"lang-icon",onClick:e=>{e.stopPropagation(),p(!g);},children:Ie(At,{size:16})}), Ie("div",{className:"lang-links-container",children:S.map((e,t)=>Le(o.Fragment,{children:[ Ie("button",{className:"lang-link "+(h===e?"active":""),onClick:()=>u(e),children:w[e]||e}),t{e.stopPropagation(),p(!g);},children:Ie(Ct,{size:18})})}),g&&Ie(Px,{currentLang:h,themeMode:a,onSelect:e=>{u(e),p(false);},onClose:()=>p(false),triggerRef:m})]}), Ie("style",{children:'\n .settings-lang-inline {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 3px 4px;\n background: var(--gh-bg-secondary, #f3f4f6);\n border-radius: 8px;\n margin-top: 4px; /* Reduced gap */\n height: 32px;\n }\n\n :host-context([data-gh-mode="dark"]) .settings-lang-inline {\n background: rgba(255, 255, 255, 0.08); /* 匹配深色模式下的 segmented */\n }\n\n .lang-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: var(--gh-text-secondary, #9ca3af);\n padding: 4px;\n margin-left: 2px;\n background: transparent;\n border: none;\n cursor: pointer;\n transition: color 0.2s;\n }\n\n .lang-icon:hover {\n color: var(--gh-text, #374151);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-icon:hover {\n color: #e5e7eb;\n }\n\n /* 中间语言链接容器 */\n .lang-links-container {\n flex: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 2px;\n }\n\n .lang-link {\n background: none;\n border: none;\n padding: 2px 4px;\n cursor: pointer;\n font-size: 13px;\n color: var(--gh-text-secondary, #6b7280);\n transition: all 0.2s;\n border-radius: 4px;\n font-weight: 500;\n }\n\n .lang-link:hover {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link:hover {\n color: #f3f4f6;\n background: rgba(255, 255, 255, 0.1);\n }\n\n .lang-link.active {\n color: var(--gh-primary, #4285f4);\n font-weight: 700;\n background: var(--gh-bg, #ffffff);\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.04);\n }\n\n :host-context([data-gh-mode="dark"]) .lang-link.active {\n color: var(--gh-primary, #7cb3ff);\n background: rgba(255, 255, 255, 0.12);\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);\n }\n\n .lang-divider {\n color: var(--gh-text-secondary, #d1d5db);\n font-size: 12px;\n margin: 0 1px;\n }\n\n .lang-more-btn {\n display: flex;\n align-items: center;\n justify-content: center;\n background: transparent;\n border: none;\n color: var(--gh-text-secondary, #9ca3af);\n cursor: pointer;\n padding: 2px;\n border-radius: 4px;\n transition: all 0.2s;\n margin-right: 2px;\n }\n .lang-more-btn:hover, .lang-more-btn.active {\n color: var(--gh-text, #374151);\n background: rgba(0, 0, 0, 0.05); /* Match hover styles */\n }\n :host-context([data-gh-mode="dark"]) .lang-more-btn:hover {\n color: #e5e7eb;\n background: rgba(255, 255, 255, 0.1);\n }\n '})]})},Bx={Gemini:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAABF1BMVEVHcExCiPvvTVP1Skoxhv/1WEP2uBhDivA8mdt4xWo8wGbkxSoxhv8xhv8KumEPumU+i/z6REL6vRI9wGeR0lztakvvvB7d0C72nh/ngEM2h/4yh/9wheMatH8+k/GscqotqazuWlOl1VSx1Esxhv8zh/83i/k6j/I0iP1LifY/iPs7lOc4h/6teaI7nc5Sto7uTlTkWGPUYHgcuG/Da42WfLxciexsid9Fq6eceLeBgtAuqaU8u3U3pLtlw3JEosFhuoG1ykWYxlf1SEkksYqIzWHvxB5QlOTcyiztpCWdnobLn0w6sZHkbVp8kMiSkLDBgoPTf2hvnL/JxjdcocBTqqjnkTXOtDdvrJKHsnTWbXSqsVi8lmybZV14AAAAJHRSTlMAt47pjhj6GPz7GBfqXl7qpV5ej66u9Y6P9Ojn5463jo63t+jInk8+AAABNklEQVQ4jZWSaVeCQABFJ1lMKpcsl/bFUIiEosUTiAsIAraZa/X/f0cz4EkKGE/v673nzTszA8A/k8utEAgCzyldorBCQpcSWEGXrm+wBZDfHmMWIH51l4wVCI8/HsTxU58/3K9F892nD59zXDaav70uOM+HO6hyGfKXZ8h5XhCEvT9LS5OJ++X88AsYckk3SrZtu67jDIeWxfEIV1BIv2W7QNN0YTr9nM9GI6vKsrUFh9nc8gTTNPvvne58Nm6tX1ahUPklwCOKfSSk2uNWPSiQgaHFDhLERn1ZERjptZx3e5rY8Cvgiv3wg5z1UIW3gq1FXvYOqmh6h0ReNTRQBTKOojkAKU0cKNCI44DR1IGiNOM/DMirqqGcxHMAVNkwcBzkZfkQKzCyzGAFkMngOUinVwihfANLZTmrCtehmQAAAABJRU5ErkJggg==",ChatGPT:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAD4UlEQVRYheXXaYjVVRgG8N+YOVlhiVhpWWSW0WZlYEjZRLTRAkaKpBJEESREChGt1pfMihZoIYIkCkXFaSEiworINYhS2yCTyG0qzYy2cbTbh+dM945zZ7P8Ui/8uff//s/ynOd93nPew//dGvrY/kCMwLDy3oJv0fZvgqpnDWjCQmzBH+XZUnxN/2TgnuwAzMAD6I8V+LL0PRXj8Duex24cg9/wKd7BV/sKrt2mlgFX4kI01nwbinmolKcVP5ffCr7BTAzc18mHYR2+wMk1/n64AK+XyTZhTgE4BhNwJ9bjT8zFgH0BME1ovbXGNxpPYacwMw9ndtH/NGFuF67ry8Sj8JBQ+BPGFv8kbJBVLcXlogvC1qwC9oiasc7DDizDYb2ZfILQXsEebMVJ5dsSSblZGFR8B4tOPlLVwipcq6qXRfhVBNutjcZnQu39eAvf40RR/auSekfXgH1NUrIFj+FJ/Ci0L8TZuLsAu6a7yfvh6dLwjvI+Hz/UAXAJnpDwVITi6TVjjVdlqwUfl/9XdwdgJDYKfYOLb8FeAJpFlN9JeN4TLbSK4mdiSOl7ECZjtWqKXtkdgEvL4A+W94YuAFSwFjeKqAbhhuLbgw8wUTXthmI2fsFy2crr2qQy+Kw6AE4ovlewTeK6t50lgq2IJubjnJrv7TqYU9upX83/HYWB4TW+Cg6XmB+qSuX2OgC2S5zX4k3Jgjdwffn+nGhhsi5YGIGvS6OhxTdN4t0mq18jOjmuTv9jZUdsxiESolYRY/tCHyljXVyPgY1YLLvazcX3sghnsWw6Z8iRPERnGyJ53yBp/HZhpUH10NssG9fgOv3/ZmG5CGZ2DRMDRFjLRGjrdBbhGglRc5nweNFEs5yoROC7cVlXAOAKEVFFUmiSpFT7KmdKyu3Cu+VpT822LgA0lFWvkjCN7A7AVWXwT2QT2SUhOLemzVQRbUU2o8clrptls6oFsKQwcHtp/4yOoe9kE+WwuUvSbYGIaRselaN1qxQhzTi/9BteB8CWwtB9EtbPdTzW69o4OTheKu+NqvFvP2w+xBTVQmOQhKatrFgBsLEspiIV0oSeJid5v0JiOrbGP0SyYwaOLL7+IqilIs4NohlSmGyXI32uHPG9tukS+/dxShdtxuAFSbmdUqTU0nuLMDK9c9eerREPC33rcY+UYGOk7Joj9LZKWdako7BGS7zXqpbwfbaBuE0orFdwVvCijtVPYwG4UnQ0padJelOWj8JFOF2qn00S+5sKyNVSxFQkBONlX7gXz4o29os1ScWzWceLyiJhoVe3rr5ezfa29qvaUeW9RbSx369q/x37C/dbHMwqTvecAAAAAElFTkSuQmCC","AI Studio":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAZlBMVEUBAQEFBQUCAgIAAAAKCgoEBAQHBwcJCQkICAgGBgYDAwP8/PwLCwvd3d1fX1++vr6fn58RERHs7OwkJCSSkpIhISFGRkZ+fn5vb2+vr69AQEAvLy9QUFBWVlYoKCg1NTXNzc0ZGRnSaSLwAAACAElEQVQ4jW1S4XobIQzDBhsbuLtck2Zdt7Xd+7/kZMja/ZgDXzgsZFmQJGdKOUnKGUuZy5TmOsdME5BiN/4DS/8F0ATEyHQqDsxMlpZMyIiorhnLco7iKmKCSZMhL156kPE445seJdIUOIsvnCf201bVBVjJvEQiyztXZQAnAMWUHsXJh6uP+9OJhce2UmohF0fPb5fjOO7MrFu/gSZGIgkB0c/16emCwCbfeu8vyi3WFBhRcdq+nwbaofejR1zetNSKyolzbslf+49UTk66b33FcfUxGhhawuCfHfIN9ZleIr3dCdpdCDlkUt57GABAa/KK/NVWYy7wrUlre8eHuhZVG7f+y4YZ1qq+SgRDSG4qJHYerqZekQ4fAOAUJdhbUxKqelV9M7WKCQaOWIDJAIDq+2ZWQWMabULnBBCH615dde8AmGnVYBCGSBy1EGkVBtW9l1JqzOhxMUBkmwymk6GOYoDiSjOqfALEQWu29woA8oYSDSXe+zvel1MIx3552UoZ+JWynExp+3hmabg1d4h7225gqED81ZCu23Z8xkc/ftd5HgwIzim35/3yFb/qbGEChBkyGp44bifstQFtZYx/GeZEF/E8VxdocPlQ1oOZb4JFmtNima0shkcXbfng0yhbgMkyucPuNm1U/zo8phXhJJoADQJSwRAPJ66qRtgfxqkYA+wij7QAAAAASUVORK5CYII=",Claude:"data:image/svg+xml;base64,PHN2ZyBmaWxsPSIjRDk3NzU3IiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+Q2xhdWRlPC90aXRsZT48cGF0aCBkPSJtNC43MTQ0IDE1Ljk1NTUgNC43MTc0LTIuNjQ3MS4wNzktLjIzMDctLjA3OS0uMTI3NWgtLjIzMDdsLS43ODkzLS4wNDg2LTIuNjk1Ni0uMDcyOS0yLjMzNzUtLjA5NzEtMi4yNjQ2LS4xMjE0LS41NzA3LS4xMjE1LS41MzQzLS43MDQyLjA1NDYtLjM1MjIuNDc5Ny0uMzIxOC42ODYuMDYwOCAxLjUxNzkuMTAzMiAyLjI3NjcuMTU3OCAxLjY1MTQuMDk3MiAyLjQ0NjguMjU1aC4zODg2bC4wNTQ2LS4xNTc5LS4xMzM2LS4wOTcxLS4xMDMyLS4wOTcyTDYuOTczIDkuODM1NmwtMi41NS0xLjY4NzktMS4zMzU2LS45NzE0LS43MjI1LS40OTE4LS4zNjQzLS40NjE0LS4xNTc4LTEuMDA3OC42NTU3LS43MjI1Ljg4MDMuMDYwNy4yMjQ2LjA2MDcuODkyNS42ODYgMS45MDY0IDEuNDc1NCAyLjQ4OTMgMS44MzM2LjM2NDMuMzAzNS4xNDU3LS4xMDMyLjAxODItLjA3MjgtLjE2NC0uMjczMy0xLjM1MzktMi40NDY3LTEuNDQ1LTIuNDg5My0uNjQzNS0xLjAzMi0uMTctLjYxOTRjLS4wNjA3LS4yNTUtLjEwMzItLjQ2NzQtLjEwMzItLjcyODVMNi4yODcuMTMzNSA2LjY5OTcgMGwuOTk1Ny4xMzM2LjQxOS4zNjQyLjYxOTIgMS40MTQ3IDEuMDAxOCAyLjIyODIgMS41NTQzIDMuMDI5Ni40NTUzLjg5ODUuMjQyOS44MzE4LjA5MS4yNTVoLjE1Nzl2LS4xNDU3bC4xMjc1LTEuNzA2LjIzNjgtMi4wOTQ3LjIzMDctMi42OTU3LjA3ODktLjc1ODkuMzc2NC0uOTEwNy43NDY4LS40OTE4LjU4MjguMjc5My40Nzk3LjY4Ni0uMDY2OC40NDMzLS4yODUzIDEuODUxNy0uNTU4NiAyLjkwMjEtLjM2NDMgMS45NDI5aC4yMTI1bC4yNDI5LS4yNDI5Ljk4MzUtMS4zMDUzIDEuNjUxNC0yLjA2NDMuNzI4Ni0uODE5Ni44NS0uOTA0Ni41NDY0LS40MzExaDEuMDMyMWwuNzU5IDEuMTI5My0uMzQgMS4xNjU3LTEuMDYyNSAxLjM0NzgtLjg4MDQgMS4xNDE0LTEuMjYyOCAxLjctLjc4OTMgMS4zNi4wNzI5LjEwOTMuMTg4Mi0uMDE4MyAyLjg1MzUtLjYwNyAxLjU0MjEtLjI3OTQgMS44Mzk2LS4zMTU3LjgzMTguMzg4Ni4wOTEuMzk0Ni0uMzI3OC44MDc1LTEuOTY3LjQ4NTctMi4zMDcyLjQ2MTQtMy40MzY0LjgxMzYtLjA0MjUuMDMwNC4wNDg2LjA2MDcgMS41NDgyLjE0NTcuNjYxOC4wMzY0aDEuNjIxbDMuMDE3NS4yMjQ3Ljc4OTIuNTIyLjQ3MzYuNjM3Ni0uMDc5LjQ4NTctMS4yMTQyLjYxOTMtMS42MzkzLS4zODg2LTMuODI1LS45MTA3LTEuMzExMy0uMzI3OWgtLjE4MjJ2LjEwOTNsMS4wOTI5IDEuMDY4NiAyLjAwMzUgMS44MDkyIDIuNTA3NSAyLjMzMTQuMTI3NS41NzY4LS4zMjE4LjQ1NTQtLjM0LS4wNDg2LTIuMjAzOS0xLjY1NzUtLjg1LS43NDY4LTEuOTI0Ni0xLjYyMWgtLjEyNzV2LjE3bC40NDMyLjY0OTYgMi4zNDM2IDMuNTIxNC4xMjE0IDEuMDgwNy0uMTcuMzUyMS0uNjA3MS4yMTI1LS42Njc5LS4xMjE0LTEuMzcyMS0xLjkyNDZMMTQuMzggMTcuOTU5bC0xLjE0MTQtMS45NDI4LS4xMzk3LjA3OS0uNjc0IDcuMjU1Mi0uMzE1Ni4zNzAzLS43Mjg2LjI3OTMtLjYwNzEtLjQ2MTQtLjMyMTgtLjc0NjguMzIxOC0xLjQ3NTMuMzg4Ni0xLjkyNDYuMzE1Ny0xLjUzLjI4NTMtMS45MDA0LjE3LS42MzE0LS4wMTIxLS4wNDI1LS4xMzk3LjAxODItMS40MzI4IDEuOTY3Mi0yLjE3OTYgMi45NDQ2LTEuNzI0MyAxLjg0NTYtLjQxMjguMTY0LS43MTY0LS4zNzA0LjA2NjctLjY2MTguNDAwOC0uNTg4OSAyLjM4Ni0zLjAzNTcgMS40Mzg5LTEuODgyLjkyOS0xLjA4NjgtLjAwNjItLjE1NzloLS4wNTQ2bC02LjMzODUgNC4xMTY0LTEuMTI5My4xNDU3LS40ODU3LS40NTU0LjA2MDgtLjc0NjcuMjMwNy0uMjQyOSAxLjkwNjQtMS4zMTE0WiIvPjwvc3ZnPg==",Grok:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAF00lEQVRYhbWXX0iUXxrHP+d1zsw7oyiDbLbq7NCEJk78XEkqIkmTvAiCWMTtJqho21qCvZKKiEb2LoL4tcyFFF1EgXS7WBdSLr/+YKvyM4yZpXK3sndWUZxJzfKdcZ69KGez5lV/bH3hXMyc53m+z7/znPMqlkMBLtM0y9PpdL1hGE1AvYiEALdSyg9oVoYtIiml1AyQAH7OZrN3tdZPQ6GQFYvF7C8JARARpZTSHo/nZDab/QNQBRSsQrZW2MAL4K9VVVXXYrFYBsjmHBAR5ff7S969excB/vyNSJ1w2efzRVKpVEopJS5AhcNh/Yn8xHcmxzTN4/Pz84TD4Q4gXbBlyxYdj8ePAn/h26U8HzGNjY28ePGiANiWSqXeNjY2/qMgmUwGReRH4FffixzgwIEDxONxpqenARCR3yQSib+5stnsD8DGtRry+XwEg0E2bdpEOBzG7XYzPT3N06dPefbsGYlEgsXFxZy82+3myJEjbNy4kRs3bnxuqiqbzdajtf5Ray1rWbt375a+vj4ZHx+XTCazbH348EGeP38uXV1dUllZmdM5evSovHr1StatW5fP5mW01j+tRlxYWCgnTpyQVCqVI1xYWJDx8XGxLEsmJyclk8nI/Py8DA8Py7Fjx8Q0Tdm3b5/Mzs7KuXPnnGz/5AJ+vVLK3W4358+f5+TJk7jdbhYXF+nt7SUajWJZFtlsFq011dXVzMzM8OTJE6ampti1axdXr14F4P79+3lti0gIl8s1sVL0LS0tuQgty5L29nYxTdNR3uPxSHNzc05ncnJS6uvr88q6XK4JtNb2Sg4MDQ1JJpOR8fFxaW1tXbVPmpubZWxsLFcqy7Jk8+bNTvK2wQqzvb29nbq6OgC6u7vp6+tzLJVhGOzcuZNbt25hmibJZBIAr9eL1+t1UtM4RWKapvT09OTS6NDFubV161Z5+fKlDA8PS2Njoxw8eFAWFhbEtm3Zu3evo57h5FpxcTEVFRUA3L17NxdRPtTV1XHz5k2GhoZobW2lv7+f/v5+LMvCMAy2b9/uqOty2igqKqKwsBCAwcFBRwOBQIBoNEo0GuXatWu8f/8egLdv3zIzMwNAeXn5L3dAKYVSH2/rqampvDLl5eVEIhFOnTrFw4cPl+2JCNlsFoCCAucrxtEB27ax7Y9vh1Ao9NV+WVkZbW1tdHZ2MjY29tW+aZqYpgmwYvkce2B6eprJyUkAWlpalkVRVFRETU0NV65c4fXr14jIV/qBQID169cjIsTj8V/ugG3b3Lt3D4CGhgb27NmzbP/Bgwe5eudDW1sbxcXFJJNJBgYGHOVWHEThcDg3UAYHB6WiomLVQbQ0CZf0ent7xe/3Ow8iEXEs0Ojo6OeO4na7nSP5hB07dnD9+vXc77NnzzI3N5dXVkSSuFyuMadoampqxLZtGRgYkGAwKFpr8fl8UltbK9XV1VJSUiI+n09KS0ultrZWOjo6ZHZ2VjKZjMzNzcnp06dXy9hzl1Lq30BlPg+PHz/Oo0ePOHz4MIlEgoaGBs6cOUN9fT2ZTIaJiQnS6TRer5eysjLKysowjI9tdfHiRaLR6GoJ+w9a68v5vNu2bZt0d3fnRrDf75cLFy7I6Oio2Lb91YNk6Y0wMjIibW1ta3rgaK0vK7fb/TsRucVnD1K/309HRweXLl3KHcUlBINBmpqa2L9/P6FQiJKSEizLYmRkhDt37vD48WMmJibyHs0vYCulfq9M09ywuLh4B9gEUFpaSlNTE7dv317xmH0DxA3D2GeEw+E3InJ16d/q6mp6enq+NzlANBAIvFEiojZs2OCxLOsC8Edg9bP2/8EGutLp9CkR+WAopeTQoUO2aZqdQNd3JgfoMk2zMxKJLCil/tcokUjEqKys9Gqt/6S1jmmtF9bYyWtZGa31Pz0eTwfgjUQiuStAfeGdArTH4wmIyA8ishv4LbBeRIrX+Hme/jRd00qpfwFPlFJ/Nwzj51Ao9CYWi6WBXOT/BWa+grSwiwH0AAAAAElFTkSuQmCC","Gemini Enterprise":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADACAYAAABS3GwHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAR4klEQVR4nO2de2wV153HTZ7dplK2SUq3jbSbJkSrjQTxvWd4BAgkvALYnutGdbrdpmmaSgRmjIFACiEP8zDvpwmBOIBnQptAUbv7x/61QpumadJtpUrbVt22eTeJqoo8zIyvHxgbvqu5NmDj+5jXndf9fqTzTyLE3Dnnw5zznd+ZU1VFCCGEEEIIIYQQQgghhBBCfKPuKMbJGo7LOj62WkbHMeu/8RaTxFPTjtuHBj2GN1nDKUpAEo+s4ceXD/5h7VjY10dI2Wg4gS/IGvoKCWD9v7lHcR27gCSS+hdRW+Rf/8HWjoVhXychZSGjo7WUALKOPbz9JJFkdPyp5BNAx/+FfZ2E+M79R3CrjcE/2DTcwi4giSKjYaVdAWQdK8K+XkJ8JaPjdQcCvMbbTxJD3SF8WdYw4ECAcws1/EPY102IL9TrWGJ7/n/pncBi3n6SCGQNv3QhwC/Cvm5CPFOv47aMhvNOBbD+jJUcsQtIrMloWOd48F9aCzwV9vUT4prmZlwh63jXrQAZDW9XAWPYBSSW1GmY73rwD7W6dswN+3cQ4gpZx394FSCj46e8/SR2fP2H+EqdhrOeBdDQX6Pj5rB/DyGOqGtHi6zlFrJenwBWa+HtJ7HB2tRSewSf1lkCaD4IoKHD2kwT9u8ixBa1R7Citj23gM0J4JMES3n7SeSZ2Yyrao7gL7VHBgXwSwJZx/szf4arwv59hBRl4SE8WHMEsATwW4LMi/gmbz+J9IuvhYfxh5rDwEUJ2v2TQNbxW+vvCPt3EpKX+S/g2wsPAQstAfJJoHmXoF7HA7z9JHI0nMCVC9rw5wWWAHYkcPsU0PAm1wIkcsxvwyPzXwAsAUpJ4Hk9oOE7Yf9eQi7ScALXzGvD+5YAIyQ4PFoCP9YDsoZ3FrXhanYBiQTz2rDyvjbAagUl8DkZkjU0hf27Cama34ovzTuI0/OeHxSgkAS+J0MaOmpfwk3sAhIqcw6ibe7zgCVAIQnKmAztZ/eT0Jh3EHfOPoCBuQeBixK0jZRggRMJnE+DBjLtGM8hQIIHGDPrAF6dcwCYYwmQR4KLTwEHEriYCp1k95PAuXc/Hpn9HDDbEiCPBAXXA+WIRxmLkiCZ2YabZu3HJ7OGBLggQU6Ag8XXA+WIR2UNn379KMZyFJBAuHc/jt+7H7AEmJXvKeBEAp/iUVnDD9n9pOzM2IcF9zwLWAJckKDYVMhVMuR2OtSOOg4BUjam7MINM/bhI0uACxLMsiNBQMmQrOPDjIa/5xAgZWFGK47P3AfMvCCACwnKnQzJOn7C7ie+M60Vj8xoBWZYAuwbFGDEVMiGBIElQ0yFiJ9M341b796LzrstAVoHBcgrwXOFJQgyGZI1ZHnmMPGFO5pxzbS9+PXdewGrzbArgZd41IdkSNbxBitGiWem7cHB6XuA6UMCXHgK2JXATTzqYzLUyiFAXDN1Fx6cthuYZgmQT4J9+SWwtSgOqnBOw8McAsQx03bhzqk70T3VEsCOBB6SoTLHo7217UhzCBDbTNyMG+/ahffu2gVMtZpNCYJKhpzGo9YOsoZDuIFDgNha9E7ZgVem7AQsAXIS7C4tQeSTIR2vzW/FtRwCpDDAmMnbcXTyDsASIK8Ee0ZLEJdkKKPjGA/cIAWZuB2bJm0HLAFsSXDhKbA3VsnQeg4BMopJW/H9idsBS4BJO+xJ4CYeDT0Zsg7sYzJEhiO2oV5sQ//EbcAoCXbml6Bs8WgAyZC1lZJfmCM5xFbMFVtwRtoKSJYARSS4KIATCSJaOCdr6JM11HAYVDBiE6alN6NLbAGEJUARCQpOhdwkQxEpnJM19GQ03BN2P5AQSLdgSmoTOtNbgPSQAIUksL0odpMMhRyPZnR01mmYwkFYQaQ2Ykb1JpipzYDVRkmw7ZIEuadARJMh3+JRDV3yi5gTdr+QAKhuwYLqjed6UpvOI7VpUIBCEoyYCm2PVjJUhnj0TN2LyHAQJpjUhn45teHcmVTLeeRaEQmKLop3xCgZcrow1vGNsPuJlIHqdQPfr14/MJDaeA6pjUMCFJDAzqL48ng0CclQZnA61C/r+B4HYVIAxqTW969Lrz+H1Iahlk+Cy58CDiRwE49GNRnKXGqtPI4p5oxbimtTzf0/Sq8bQHq91QpIUGo9EFQ8Gp1kCEPtRMMJ/F3Y/UhcMHENbkw197+Wbu5HToBCEthYD3hOhuJZOIehKdHPWUodM+5s7qtOPd3/bvqZfuQEaB7IL8FG5xJ4TobiVTiHIQk+qG3HxLD7ldgg/WTft1NP9XWnnz6LnAAFJCi6Hgg5GYpM4Zw+ovXK7XiEgzDCJ7Snn+zbmn7qLHLNEuDp/vwSrHcuQZSToSDOIshciEp1tFlnooXd32QYqTW941JPnPl1+sk+5Fo+CXIClFgPFJAgvTm6yVCgZxHoF6dEv6rXcRsHYQSoXtvzUHpNbza9tg+5lk+CZzxI4CIejUwyVM6jWnV01utYFHb/VyxiNa4Xa3pfEmvOIP3EUBshwfCngEMJ7C6Kgy6c85gM+XlUa+ZS+2n9i7gx7PFQUYjVZ2rSq3s/Eqt7YQlQUIIRU6Hii2IvyVAcCud8T4b0YesCDR9xb0EATFiZHZte1X1U/KAXuWYJMEqCIlOhMiRDcSicK2MyhMtE+E/5ML4axFioOMTjPQ1iVc8n4vEe5FoeCfJPhQosioNKhuJUOKf7IIGO07m1ATAm7DGTCFKrshPEyu5XxMpuiFU9gy2fBGs8SLDOuQRukqHEFc7pRZOiV+p0TAh7/MSWKSuMG8Tyrtb0imy/eKwbOQEKSZB3KmRTgggnQzEqnEOBp8E5WcdRHuDnALEIV6eXZZeL5V0dYkUXcs0SoJAEP3AigYdkyEPhXMK3VMLOtCijYTk/116MZlwhlmUbpKbs29KyLMRyqw0JUEiCIusBX5OhDdFPhiJROKeXnBZ9YK0PZv4MV3mdISQIjBGN2QbR2PlnqakTUlMWlgAlJVjlQgIXyVCohXNekqEIxKOZwiK8Z4nQcAJXVlVy7Y5QjG9JjcbvpcZOSEuH2igJui5J8FjXZU8BBxIUXQ+c9S0ZisOWyqDj0UzhqdHv63V8q6KeCBNW/u06STUWCcV4S1JN5Fqj1UpIsKKQBEWSodXBJkOphCZDcpkEGCbCXzI6Vje04fqqpDLl0e6bJcVsEYr52cWBP7yNkiB7UYLRUyEHEgSVDMWgcC4KyVCmuAifZXS01Oi4uSoRNOMKqdGYIynmCUk1zuYd+KUksLMe8CMZ8lI4V2gqFKfCucPBJkMlRDiX0XBS1tAQy3WCWGrcJilGs1DNd0sO+mISOFkUj0qGAopHXSRDcSicqw1ZgmEyvCtreOb+I7i1KspMbsp+WSjGEqEab0iqcd7xwB8hQbH1gM/J0NroJ0NJKpzLuG0azltHv9brWBKZF2sppeOfJNVcJhTzpFCMfk+DvuhUqEgytCLgZChKWypjXDiX8ThFknX8JqNhnXwY/xzYgBeL/vr5oTn9Vkk1f+P5X3q/JAgqGYrylsoYFs5l/Jwm6WjLrRnKkSRNbjJvF4p5XFKMvrINeCZDlbOlUi+jDIPnHhyvO4pxvgz+lGKMkxTj40AHvutkyMaTwE3hXEK3VM6NSTzqUoRTvuxbFqr549AGv1/JEAvnvCdDh8OPR120Y54FCPVf/wpJhuKwpXJhxOJRu0+BBAkQUDLELZWIYzJUNgFyi9+wB78bCVg4V9HJUGZQgJf9WQSrxqlYSeCqZohbKucmKBnybRF8QYJQYlDbEngsnIvjlsoKL5zLFB74fdbityxfrgv0RVilFc552VJZwYVzmSBehBUUoqnjH8tSClHuZIhbKmNdOCdb1aI6Xrf2ENS04/aqKDBhcXasUI3FkmK8HtiToeR6gFsqE1M4p+G8rOEXGR2PNhzBl6qizKTG018TivGUpJpvhy8BC+c81ww9H2rh3FuyhiczGm6pih8Y42hDTDkl4JbK2JxFIA9tiMm0oy4xX5hLqd1fLbolshyLYm6pDD0ZqnPwFLiwJTLR3xcdtin+zUAkYOFc9JMhDe/JOpbNPYrrqirpsyiSavyrpJq/K5sESdpSGbOzCGptSCDr+N96HQ/Ect+vf2CMtMSs81UEFs5FekulrOGPso6HeBD35Z9GbDQaRnwviMmQ5y2VUTqLoLYd79dV+hfh7HwcV1LN5ZJqdgQmAbdUopyFczWH8WlNOxqtaW/Y4ytWn0eXVKPV0xvmCi6cc1MzNNP/L8711xxG2/yov7iKMkLNjpcU87+ZDIW0pXK/y3j0BfzXwkP4l7DHT2Kw1geSanwSSjLELZW4PBkqFI/e9wI65h/i8anlOzVGMdsCTYZYOAe7ydC8NpzgdCcAxBKzRijmR2VbFHNLJRyeRfDBnAO4L4i+JxckWNRxvaSYLwWXDPEsgll5JJh9ECfmHcINHJhhrg0U83ToyVCFnUUw6zmYsw9wrh+dr1Grxq/cS5D8LZU+f3Hu9ZkHY1menPDaosGtmu4lSOiWSp/j0TbRhqvD7m9SAKEa/yapZndFF855+djWnvyFczNa0TtzHx7mwIsBkxo77pQU8x3v64EK31K5d1CAu1vx9oxnMT7sfiVO3xmoxquRiUdjehbB9L14ZfoBfJGDL4bc0YxrhGocZeGc62To+EwNnwu7H4knMEao5rqSX6rglkpclGAXzk/dja2J2Y9Lqqok1fxeycpSbqnEXbvRP203vssxk0CsnWdCNXorMhmyt6Wyb/IO3B92P5EyIpacvldSzWxZCufifRZB9107Wc9TEaQbO+8WimmGngxF5SyC7eiauBOzw+4XEiDpxeYUoZqdlX5K5cTt6Jy0C1M4+CoQ0dg5TVLMrkrdUiltRY/YgXvC7gcSIkI15kqKcaYCC+f6xDYs5OAj1pOgvmhEmrAtlektGBBb0MCuJyPeE1TElsrNOF+9BQ+x68koJNXcmPTCuerNaGbXkyJlE0Vqh2K+pbK6BcdY3kBKFtAV/Q5RTLdUVrec+/m4VlzL7ic2S6nNd5NSOFe98dzb47ewpJk4ILWkY0LRnWUx2VJZvX6gZ8IGpNj5xO32ylgXzlWvG2BlJ3GPUMz9cS2cS63v38u+J94XxarxP6EXzjlNhpoHfsmvNxBfkJYYt/pWPRpEMvTM2Wz1UxE5QJokg4mK+XBctlRWNw/wTS/xH6GYx6K/pfLsT9j3pCyMX2J8Uajmh2VNhjzEo6mnz344fg3zflJGpEZzQVEBQkyGUmvP1LHzSdkp+Vn2ELZUptae+RG7ngSCWNR5k6QYH/smgcfCudTaM59OaM6OZfeTwBBLzIdKT4WC2VKZeqLvQXY9CRyhmCedS+D7lsqT7HoSCpOWdt4hqcZZVxL4kAyl1/QOiNV9/GoziXCtUBm3VKZX9zzLvifhvxtQjE+9rwccxqOP93aIxzpvYveT0BGK2WTvKeBjPLqqd2nYv5uQHGIRrrZ1Io1vyVD3O9bfydtPIoNQze/aEsCHZEha2fOdsH8vISNoaMCVkmr80ZMENtYD6ZVdb1onYvL2k8ghNRrftC2Ay8K59MqeB8L+nYTkpxlXSKr5O2cSOEqGfmv9Hbz9JJlPgRLJUHp5lv/6kxisBewmQg4kSC/Pvse5P0nWewEnEjRlG8P+XYTYQiz66+dtvR22mQyJpuxndyinvsDbT2KDpJgtjgUolAw1ZVvC/j2EOEIs6vqKrUrREsmQWGr2T1nRfTNvP4kdQjH+3etTQCw1+ZUHEk/SqnGfKwGGS9CYnRP27yDE/Ysxp5HosCZU4y3r0A7efhJbJNV4xoMAT4Z9/YR4YvKjp2+RVOO8cwGM85MaT3+Nt5/EHqEabzgWQDFeC/u6CfEFoRqLXUx/FvP2k0QwYXF2rFCNAQeDf8D6M2FfNyG+YU1pHAjwKm89SRRCMVc4mAItC/t6CfEVK9GxK4CVHPH2k8QhKcafbEx//hD2dRJSFiTVaC0pgGLs4e0niSStmrWlBTAXhn2dhJQFa1OLpBh9RV5+9U1Y+bfrePtJYhGKebzIE+DlsK+PkLKSUoxx+U+XMU6JpcZtvP0k8VgDffDIVePUYDNf5uAnhBBCCCGEEEIIIYQQQgip8pX/BwILOckUNulSAAAAAElFTkSuQmCC",DeepSeek:"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzNSAyNiIgZmlsbD0ibm9uZSI+Cgk8ZyBjbGlwLXBhdGg9InVybCgjYSkiPgoJCTxwYXRoIGZpbGw9IiM0RDZCRkUiIGQ9Ik0zMy42MTUgMi41OThjLS4zNi0uMTc2LS41MTUuMTYtLjcyNi4zMy0uMDcyLjA1NS0uMTMyLjEyNy0uMTkzLjE5My0uNTI2LjU2Mi0xLjE0LjkzLTEuOTQzLjg4Ny0xLjE3NC0uMDY3LTIuMTc2LjMwMi0zLjA2MiAxLjItLjE4OC0xLjEwNy0uODE0LTEuNzY3LTEuNzY2LTIuMTkxLS40OTgtLjIyLTEuMDAyLS40NDEtMS4zNS0uOTItLjI0NC0uMzQxLS4zMS0uNzIxLS40MzMtMS4wOTYtLjA3Ny0uMjI2LS4xNTQtLjQ1Ny0uNDE1LS40OTYtLjI4Mi0uMDQ0LS4zOTMuMTkzLS41MDQuMzkxLS40NDMuODEtLjYxNCAxLjcwMi0uNTk4IDIuNjA1LjA0IDIuMDMzLjg5OCAzLjY1MiAyLjYwMyA0LjgwMy4xOTMuMTMyLjI0My4yNjQuMTgyLjQ1Ny0uMTE2LjM5Ny0uMjU0Ljc4Mi0uMzc2IDEuMTc5LS4wNzguMjUzLS4xOTQuMzA4LS40NjUuMTk4LS45MzYtLjM5MS0xLjc0NC0uOTctMi40NTgtMS42NjktMS4yMTMtMS4xNzMtMi4zMS0yLjQ2Ny0zLjY3Ni0zLjQ4YTE2LjI1NCAxNi4yNTQgMCAwIDAtLjk3NS0uNjY4Yy0xLjM5NS0xLjM1NC4xODMtMi40NjcuNTQ4LTIuNTk5LjM4Mi0uMTM4LjEzMy0uNjEyLTEuMTAyLS42MDYtMS4yMzQuMDA1LTIuMzY0LjQyLTMuODAzLjk3YTQuMzQgNC4zNCAwIDAgMS0uNjYuMTkzIDEzLjU3NyAxMy41NzcgMCAwIDAtNC4wOC0uMTQzYy0yLjY2Ny4yOTctNC43OTkgMS41NTgtNi4zNjUgMy43MTJDLjExNiA4LjQzNi0uMzI3IDExLjM3OC4yMTUgMTQuNDQ0Yy41NyAzLjIzMyAyLjIyIDUuOTEgNC43NTUgOC4wMDIgMi42MyAyLjE3IDUuNjU4IDMuMjMzIDkuMTEzIDMuMDMgMi4wOTgtLjEyMiA0LjQzNC0uNDAzIDcuMDctMi42MzMuNjY0LjMzIDEuMzYyLjQ2MyAyLjUxOC41NjIuODkyLjA4MyAxLjc1LS4wNDQgMi40MTQtLjE4MiAxLjA0LS4yMi45Ny0xLjE4NC41OTMtMS4zNi0zLjA1LTEuNDIxLTIuMzgtLjg0My0yLjk5LTEuMzExIDEuNTUtMS44MzQgMy45MTgtNS4wOTMgNC42NDgtOS41MzEuMDcyLS40OS4xNjQtMS4xOC4xNTMtMS41NzctLjAwNi0uMjQyLjA1LS4zMzYuMzI2LS4zNjRhNS45MDMgNS45MDMgMCAwIDAgMi4xODctLjY3MmMxLjk3Ny0xLjA4IDIuNzc0LTIuODUzIDIuOTYyLTQuOTc4LjAyOC0uMzI1LS4wMDYtLjY2MS0uMzUtLjgzMlpNMTYuMzkgMjEuNzNjLTIuOTU2LTIuMzI0LTQuMzktMy4wODktNC45ODItMy4wNTYtLjU1NC4wMzMtLjQ1NC42NjctLjMzMiAxLjA4LjEyNy40MDcuMjkzLjY4OC41MjYgMS4wNDYuMTYuMjM3LjI3MS41OS0uMTYxLjg1NC0uOTUyLjU4OS0yLjYwNy0uMTk4LTIuNjg1LS4yMzctMS45MjctMS4xMzQtMy41MzctMi42MzItNC42NzMtNC42OC0xLjA5Ni0xLjk3Mi0xLjczMy00LjA4Ny0xLjgzOC02LjM0NS0uMDI4LS41NDUuMTMzLS43MzguNjc2LS44MzdBNi42NDMgNi42NDMgMCAwIDEgNS4wODYgOS41YzMuMDE3LjQ0MSA1LjU4NiAxLjc5IDcuNzQgMy45MjcgMS4yMjkgMS4yMTcgMi4xNTkgMi42NzEgMy4xMTYgNC4wOTIgMS4wMiAxLjUwOSAyLjExNSAyLjk0NiAzLjUxIDQuMTI1LjQ5NC40MTMuODg3LjcyNyAxLjI2My45NTgtMS4xMzUuMTI3LTMuMDI4LjE1NC00LjMyNC0uODd2LS4wMDJabTEuNDE3LTkuMTE0YS40MzQuNDM0IDAgMCAxIC41ODctLjQwOGMuMDYuMDIyLjExNy4wNTUuMTYuMTA1YS40MjYuNDI2IDAgMCAxIC4xMjIuMzAzLjQzNC40MzQgMCAwIDEtLjQzNy40MzUuNDMuNDMgMCAwIDEtLjQzMi0uNDM1Wm00LjQwMiAyLjI1N2MtLjI4My4xMTYtLjU2NS4yMTUtLjgzNi4yMjYtLjQyMS4wMjItLjg4LS4xNDktMS4xMy0uMzU4LS4zODctLjMyNS0uNjY0LS41MDYtLjc4LTEuMDczLS4wNS0uMjQyLS4wMjItLjYxNy4wMjItLjgzMi4xLS40NjMtLjAxMS0uNzYtLjMzOC0xLjAzLS4yNjUtLjIyLS42MDMtLjI4LS45NzQtLjI4YS44LjggMCAwIDEtLjM2LS4xMWMtLjE1NS0uMDc4LS4yODMtLjI3LS4xNjEtLjUwOC4wMzktLjA3Ny4yMjctLjI2NC4yNzEtLjI5Ny41MDQtLjI4NiAxLjA4NS0uMTkzIDEuNjIzLjAyMi40OTguMjA0Ljg3NS41NzggMS40MTcgMS4xMDcuNTUzLjYzOS42NTMuODE1Ljk2OCAxLjI5NS4yNS4zNzQuNDc2Ljc2LjYzMiAxLjIuMDk0LjI3NS0uMDI4LjUtLjM1NC42MzhaIiAvPgoJPC9nPgoJPGRlZnM+CgkJPGNsaXBQYXRoIGlkPSJhIj4KCQkJPHJlY3Qgd2lkdGg9IjM0LjE1NCIgaGVpZ2h0PSIyNSIgeD0iMC4xMzUiIHk9IjAuNSIgZmlsbD0iI2ZmZiIgLz4KCQk8L2NsaXBQYXRoPgoJPC9kZWZzPgo8L3N2Zz4K",Doubao:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAsVBMVEVHcEzK5P/K5P/L5f/K5P+juM7K5P/K5f/K5P/K4/0eHyLK5P/K5P/K5P8PERIiJCYRFRpeaXQpKy1ZYGTK5f/O6P9GMy4+LSlMOjb/4Nbzy8D918w2JB/vw7f50cYJBQfQp5zruazfsqaee3PEgXFmYmWhr74dHiAvGxVZMixZQz7E3PW8loy4x9h5V0+Yn6iBaWSPj5FUVFesucrZl4jRt7R5f4jO3PAoDgO/1/DcztGl0EnsAAAAFHRSTlMAT5SN9QqhHeX9mojIyyFP24jI6xCzqC0AAAIcSURBVDiNbVOJlpswDIRkk0A2e7TFNodtjLmPEALk2P7/h1XYbJqk1XvAe55B0owlw7jFyly8WY5j7Rbmyvg3NmvbuYW93jzjr9M5Qk49vaZYPv5uqcMspdci3WuGdZdk8zKd1CklEJSkZ3vivGyecYxd18WEUkqyB4bOf3ABryoXU4LJVTEsjS8Vvu8JwBUkKPCURWl6VQW0sCPBbuWSooybFhiFSuFMRdZK4D4luHIpjn3P82JKioMirME/7U/mQou0bLg3RVPQXhHslWEq/HIGnJTJ9L8XBEFTkC8FmMZCtwgacVF2jT/h3Pfbq/ZrYexUC0MFjZWxaBrAWdt2zXVQhDdtAgITMKnaWHIecMZYJEqdwTJUBXQEAjQRVpIHvmzdTna1vti/BKjQh+kJKsR9fhTxZSZon6cMZRK3JxDBTyE+McFsXeLtVqJMIsa9gHMuRykjTdhpmarJMmF+4PHI5yyKZPTb0TLNGwEn0uc+i3x4xDC3YGqrETjt0k4COCYjYwJ/zcO50peFMkxAZCfY5CJrCJ1Frr+vuz6kxD2n6Sh9v2nDsJgJm7uBRvBcEoj9kGWZfT/a1vc6oP0oxsRGSI++bT0MLeCOkFEkTs5MeBpr5GTgFLQo4/NhqNEdrhYHDX0YBxyGgYswDPPaety+ZQ+HoVDzFId5Hv54Xs73bQ7RiZOI4bt9/89+rz62Pz9z8utz+3G3/n8AizBVNlqUq8sAAAAASUVORK5CYII=",Kimi:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAbFBMVEVHcExvcHB0dXUAAAEFBQYdHR0CAgKFhYVaWloDAwQxPk8TExQsLixCQ0NSUlF7fHw/QEBNTk0BAQIJCQn///8wMDEjJScQEBFaW1oaGxs8PDxLS0v09PSam5pvcG+7u7vd3d0Xhf0QWq8LOGx10D/DAAAAEnRSTlMA5beDuDfZ/ibp/YXLuoKC1oV4m0C2AAABk0lEQVQ4jXWTjZajIAyFaauiZ2Z2Z4mEAC3azvu/496g9tROGz2C3o/8CcaotaemG8jdjYauObVms75xL63pF70dXuvODdVJ/1YnN6iPN/7XKAjwRmKuQ2tOr/Wf6/VHx493EW7X6w1JhMZ065eQ8uLU+ZwzgBteKXRmq8GfR1snch7Hi5agq2gw9ASs+lonBeP2wKbTRjwBm3+YpvgLeNAVCTHsARnX/FYgxn0OM9bP9/VEIdAeqDanBVGRyfEemOZxPFslgl4hctoBk+NJsYgWwX9g7/0jMOl40TCWaxT2yT83amkFpkGJ5NOvVlMNYylWQw7D2lWe5rL8HziZCsMSbm86etjutUnVX4peUkzyaZqgxA5CizP7nLKX/GU+OKKi+l/qatxaXkzsOYv8MW1g1Bxr4UsQrR71eTgRwb7/jCiXGU91RREakgeCnSdHPTiSBPOckvalSE4xguUkIod6+PpDKXgBVSwu8awNyHcdxLFYKaXYC6xIyRENAP/V3893+/d4gDwBsLZ4Iv99/Lcc//+vBkqfTIfVbAAAAABJRU5ErkJggg==","Z.ai":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAYFBMVEUtLS3///8AAAD9/f0eHh77+/ssLCyenp6bm5snJycjIyNPT0/a2tpOTk5kZGShoaEJCQlfX1+SkpLR0dF3d3dCQkKIiIi5ubk4ODjw8PDm5uYRERGpqanExMR9fX0WFhYW+xctAAAA+UlEQVQ4jY2T7RaCIAxA18IhSKF9l5bv/5YFbIkdyu4fd9hVZBuwWgDSY11gElyDRRqXBIcGihh0UWi+5F/GJgr4LQ+AQVgHwSjBEAc2CBULZuvrhO8ohXpnM0HVcuwK9xwdZoIW4Xji4NzmW5CxifbC+StSLgAxeGNhE88+CUw/cF6PUBJsx3nHax8C9ZW0kIoC3jn/UFAS1IPz9+mVXCCQWo1UFEJvI52FkjBKtYceSkJofeSGUrR5JfHKwqXlqhvKhfbM+dNR2qZVJtgDr+7fX1rVM2HndcBDN+iE35p8C8tzRtnsyU8uDu2vsW/+uziLV2/58v7kCT8OC8uRxXhyAAAAAElFTkSuQmCC",ChatGLM:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEhUlEQVRYhb2XTWhUVxTHf+/Om8kHozGMtZOFg8UYV8HEbQa7aYkYrIssNEGMLUGUUppaMFZatdCFgWJXflACmk1skCw0REi1UG3SZZIiLmKsqWNhFNJqcDoZ5+t0cTPvzZt5mYzG9g+P997Mfef/P+eec+69kAcRWScip0RkTt48pkTkkohswg0i0iUiz/4D4kI8E5GeQvJPV2PxUTQjj6KZV/2sC8AQHZIpYJ1raFwwPp3hxkSa0YkMkSdZx3+hoCK8TbGrxaQtbJYy8xx4xxCRS8DBlUgXYsLF4RQXhlMsxKQsoaGgYuRsJaGgWm7I14aITAFNpQxdHE5xZiBZNnE+avwGI2eraKx3FfGHISLLWl2ICftPJhifzhQZ7Wg1adzsIdykLA8XYsLdB1kGx1JcGUs7xt/5vso1EssKiDzJsvtowjHHNX6Dw+1ejrR7qfEbJT2/+yDL7qOLVtTCTR5GzlaVJ8CN/HC7l+NdPpQyiMXhfgRii/o/fxWsqYYtIX3PYXw6w+6ji9b7b4PVRVEoSlM38hMfVlC71ssX52FypqTj1K2Hho2woxnaWjyEmzzWFI5OZDjSvoKAvoGkgzz4ViXDP5csJwei8/q6PQX91yHyVAEZy7lCOCwPjqUZzEueDYEKavzF5HXroS6g7zlSgNnH8CLuFBNP2LniVkUO630DSeu5xm9Su9ZrvW/fCm0tOrT581yIyRm4PQl3pm1hts3ixLUEDI6lrRB5TUWg1mcRd+/R93Kwfau+PuuA0Qn4/Du7hENBRXTejhyAlRFXxlLWj9WVCq+p6N4D54+VT16Ixs1Znv5tCwhv89B/3RkZBXpu8ptNoNZH9x7o/uD1iHPIb0ahoKKxXjE5Az/cLBBw94GdnUoZhIJq1eSRJ1nO5OVU7wEfoxPa+xu/2smqI/CPnZ2VFYq9762OHGD/yYT1HAoqOneaDC15/iJuT0NRc85khIbQ6shPnHvpiGrvAZ3Q/rzqmX2cJyD0tq0jlZai8nkVfNyX4MKwndC9XT46d7r3EktAY72yajSbFUZ+SRd9sBJ0C190NLKOVpPjXdr76LyzjdcF8gTkBudw9dZL7j0sbptuWIgJfQNJdhxadFRSR6vJ+d5K673/uv1Nw8aCCAAc7/I5otD5ZcLhjZvHfQNJtnXGizYrh9u9TvJruinlsPd9+9mxHI+Opx3ZC7p9NtYrQkFjyWNdtm4LSyioOHesgnCTB9DZ3n8Nhm7ZY9pa4KuPlhEAMPRjmk++TZJKlzcFOZH5G5UXcRi6qYnzF6ctG3VnzV9LXDck9x5m6f4mye9/ZksK2RDwsKPZpLPVJJ4wuB/R5eW2Z2hrgZ59xQuZISJzwKbCD6LzOnGu/pQhlRbSS0JMU+E1DSp9CqVKb8tAE/bs0wJcMG2IyGng1HIGckImZ4qX11LYvhXebYZdLSWX78uGiKwD5ijjYDI5A7MRuP/YFhP9S9f0mmoIBqAhtPKeYQnPgWYAROTgao5mr4mi82GP/H+H04OuMRGRTSJyWfRR+k1jTkROi55yC/8C7thSyJF3OSAAAAAASUVORK5CYII=","Qwen Studio":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAaVBMVEVHcExeTe1cUe1fVO1cNOlhV+9wcfJVQvBQR/NeSu5WO+phRupVEeSFkff///9gRulhT+tiOediVu308/64sfWon/NfLOVua/BqYO7W0/qLeO1WPenm5PyRhvCDbe3Au/Z3fPNTEeRRLuid/6vZAAAADnRSTlMAg+XYqru9MxBfz/W/ga+H9kIAAAGTSURBVDiNdZPrYoMgDIV1VattB8hNEZTJ+z/kkqCt3er5ZZvPQ3KCRfFSVTdN0xWnKqMcx2FoT4GBRQFEc1avAmMjelw/168zY8xxIOCY4Qc0f78BNwWA4VIekGM7nYG6SkI8CUD2dq6gewCHJXnOudgoQHI7X0ZrPcfAFD5sijrGqMmiE+Q+O2ziXZocpPRY0mDxR6qm/KQUE/78bzHTFBdoyDvMQCzTUwb1lUcAQEh8YbHW9iAYZHAokxdXA+A1HrluZZ6CQrGBgBYA4dHCkEHPvdmacGVeMwAcN8HoCN5n+tVmgUDCISMdkiI8hkSn3vIeAOALvsHRQlDHnNIxOewLAIlGBYuVHjycGkAXahMd+h5fnKyl1HBl3HvPqc0aAW6xrbCulLvfl5qjItpiSU35XuStC9HlpCAH3LRjytG4M8UF9T1skWdgKmgacQXgjtdou3O1SHnVm8GIcR0/oJZv2Qbj9rhubze6XKYFNfbPwM8+DrAyKwDV53pRPJRa8Vqc1Yt2mqFuy1Og6B4V6PDHL81hMVCAJrPEAAAAAElFTkSuQmCC",Qianwen:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAaVBMVEVHcExeTe1cUe1fVO1cNOlhV+9wcfJVQvBQR/NeSu5WO+phRupVEeSFkff///9gRulhT+tiOediVu308/64sfWon/NfLOVua/BqYO7W0/qLeO1WPenm5PyRhvCDbe3Au/Z3fPNTEeRRLuid/6vZAAAADnRSTlMAg+XYqru9MxBfz/W/ga+H9kIAAAGTSURBVDiNdZPrYoMgDIV1VattB8hNEZTJ+z/kkqCt3er5ZZvPQ3KCRfFSVTdN0xWnKqMcx2FoT4GBRQFEc1avAmMjelw/168zY8xxIOCY4Qc0f78BNwWA4VIekGM7nYG6SkI8CUD2dq6gewCHJXnOudgoQHI7X0ZrPcfAFD5sijrGqMmiE+Q+O2ziXZocpPRY0mDxR6qm/KQUE/78bzHTFBdoyDvMQCzTUwb1lUcAQEh8YbHW9iAYZHAokxdXA+A1HrluZZ6CQrGBgBYA4dHCkEHPvdmacGVeMwAcN8HoCN5n+tVmgUDCISMdkiI8hkSn3vIeAOALvsHRQlDHnNIxOewLAIlGBYuVHjycGkAXahMd+h5fnKyl1HBl3HvPqc0aAW6xrbCulLvfl5qjItpiSU35XuStC9HlpCAH3LRjytG4M8UF9T1skWdgKmgacQXgjtdou3O1SHnVm8GIcR0/oJZv2Qbj9rhubze6XKYFNfbPwM8+DrAyKwDV53pRPJRa8Vqc1Yt2mqFuy1Og6B4V6PDHL81hMVCAJrPEAAAAAElFTkSuQmCC",ima:"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Kzc3Nzc3Kzc3Nys3Ny01Nzc1LTcuKzI3NzctNys3Liw3Kys3NzctKysrLis3NCsrN//AABEIACAAIAMBIgACEQEDEQH/xAAYAAEBAQEBAAAAAAAAAAAAAAAGBQgHA//EACYQAAEDBAICAgIDAAAAAAAAAAECAwQFBhEhADEHExJBYYEUIlH/xAAXAQEBAQEAAAAAAAAAAAAAAAAEAAUB/8QAHREAAgEEAwAAAAAAAAAAAAAAAAECAwQRIQUSE//aAAwDAQACEQMRAD8Ag+SPINy1G9ZFJoM2XEYiSv4rDERRQt51KviSSNqyrQHWMaznmhYXvTEYEtSVSA2n2lPRXj+2P3nkqfEt+jOS7kmQ4UZ5psrfnekezGMdgZJPWtnQ5CsvyXSLwqsmn0+PLZcZaLqVPpSA4gEAnRODsa5HGNZnvVCfENSUyS2r1FXQXjWf3jmePG3kG5aderFIr0yXLZlyv4r7EtRWtl1SviCCdpwrRHWM6zjnU7y8m0iz6rGp1Qjy3nHmw6pTCUkNoJIHZGTo64gp8W3q05EuSHDhSXnWwtid6R7MYx2RkEdb2NjkSeSb5Et926bVlUmNKRHecUhaVrz8SUnOFY3jhC0rCk2ZSJ7tNnRHbhkthCJDzZ9LScglI+znHf4TrW39RW9HWUqSr4/Svo8mlxazk55nXV55aCTrtvqkELtsKVeNJgO1KbFauCM2ULkMtn0upySEn7GM9/lWt6YeOaE7a1rRaTJkpkOtqWtSkZ+IKjnCc7xz1bURylBC3VAAH4/Z/wA4KhyUqs1BCKaljZ//2Q==",Yuanbao:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAMAAABHPGVmAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAA51BMVEUAAAAAz3AAzHAAy3AAzXAAzHAAzHAAzXAAzHAAzHAAy3AAz3AAzXAAzXAAynAAzXAAzHEAzHAAy3AAzHAAy3AAzHAAzHAw1ooQz3kg04Ig0oJQ3J2A5bfP9uR/5bef7Mkw1ov////f+e2/8ttg36ZA2ZOw79Jw4q5g36XP9eSQ6MDv/PZA2ZQg04EQ0Hmv79Jv4q6P6cDf+O2P6MDf39+QkJBgYGCAgICfn5+vr68QEBAAAABwcHAgICDv7++/v7+goKBAQEB/f38w1YtQUFAwMDCQ6cDPz8+Pj49fX1+A5rig7Mlw4q+cA9JGAAAAFnRSTlMAEFBwj6/P3++/QCCfYDB/b5CA37CgSCmUoAAAAAFiS0dEIcRsDRYAAATWSURBVGjetZp9f5pIEMeXoICiXkiaSTSX6GqpJtjYtMbmShKbXu7ay+X9v577gCC77CwssPf7S5eHLzOzj7NLiKKMA7PVtmwHAMCxO52W2TVUn1WSa/ZsQGS3+wM9hG4LBexBvW5TgvGbBaWy+24DxKDllCNi9epi3I4ioT7GaFVB1MMcqjqKi01FT52eVYcAdCoYc+gMR3UYAI6pHo3heT0GALTUXGXB8PfaDABbwWWuDXBR01mqlIEDcDluwgBwBuWMCW1kSCklYsB01pBRTHEjxiV93xgCjjQuUcxhSBt7C4qiH48bY3qhgQFg4eNm3CP6lH7QAsFb5WF8aUZpk5bICulh4qBHEaFzTRAk+LsRakwpXWiCQCfP6ENqiD5I3mHubkayiCC6YgLg8DWstyu9iiDX2iB8DXMh8xZt3qtkckVDYm/RQCOkIxgSNZJIS42UQd4QCHaQakH5eOr7vn8juerlDfF3DBooz1RO57MgfWi1GCJ37CtYPymYJ/crVuKb+YzyGiOYI7b3BYBrWsWUTwEVJWKsHaOb/s8+7LYUMbmgqKZCf9Hlwg6fs3vL5l2fqFSXaOj3axzmzmBSyPhCqTLlOJ48pP/OOLOHcsTNjBYqN1a4TN2CEXdnIPWYP6Ul4t0Q9cVtHCI6NzHjSxmC0ilXO3tsSEbCveLIcnMZlDNyDe2YEAOkkAjDhca/VULkG5qRtRIMQim9Gs99/+Opv7hdKRKE2B8Qc//7TP0dpeLGJJN42Z8KX1oq1l8eYdbRn6WPrO82m69rofgeK9yJbQDvWMhKxvjjWxjpLlf8EIbho4TC1i+LMImTaxnkMWaE3554O+LCDf4Iu446Jsx6fSFhbMNE3zkX7tDP+DPshNohzJ+RBPI1hXBfvQmLLOGqFwuRRX6TQtivvk/K1lUhkqA8p5BHwVnhD4n1H6SQpTpkI5Tw4mY8hEvUBKqQbbGz+H7FIXa5vxDIfVhUtSilf3JV2Cr3V4ElWwljyr61k41ZsWaKEPqSlDzhkDEP8aDUlJcU8ldW9pTUrhccwk2nPaarl5rygLWT1GHfMQbnLTDJAZSacpdCHhA0agqf0+gyw+9Of4uPrEMszE/yvos3BAxCcvnrM2TC84y2vJ/xAPALgfB5E5sQcpIzBXHYOg79c77l3T+G4T8I45V/4TtC8pFHHUbX2y3SuJ+wQiE302eWQCWNRVnTfJJpwE24i8JSn2HHs3pPMGVUnyLmSHv8IkgDZSWu0ZLtFUsb5VV8k52sGY8AodSI/hRLAKSbBAa6w/CqwVVs4sPDrsJ5JZdN8UVTL0sHo9dh9K8yIniVrMqZDI5sY0kxMlIEYwjW6lMtyzFyBJ+KkkQlcVrhkmJ2XpC+YA2RVbB9FZBwgtVbYYIkn+Y2oViTt9UV9/6r8duk5BkQNtJUNhWHy+X7SMvJUOFuMWWbJJ91Ctt5KHNYZaEbdZ6GFzPyMAYxFDas1WUTXK6t4eUpQ74VpC34TsE24EATRWF77n9m6KGUMXREX3Xzt4kstT35Rq3SUz0yY9YOjPKmf+WDHpmqHF+IErk1IlPFjMSYk6oM5WjUx1T0VA2M4zU5HeWqxMY6anzSq3tSfPTKa3z0aqdBv40fIuuZTQ5diTK6ptfppMfhrLZnHig76T8EnUECfKwPQAAAAABJRU5ErkJggg=="},Ox=({title:e,description:t,children:n,className:r="",style:o,settingId:i})=>Le("div",{className:`settings-card ${r}`,style:o,"data-setting-id":i,children:[e&&Ie("div",{className:"settings-card-title",children:e}),t&&Ie("div",{className:"settings-card-desc",children:t}),n]}),Fx=({label:e,description:t,children:n,disabled:r=false,onDisabledClick:o,style:i,settingId:a})=>{const s=r&&!!o; return Le("div",{className:`settings-row ${r?"disabled":""} ${s?"disabled-clickable":""}`,"data-setting-id":a,style:i,onClick:()=>{s&&o?.();},children:[ Le("div",{className:"settings-row-info",children:[ Ie("div",{className:"settings-row-label",children:e}),t&&Ie("div",{className:"settings-row-desc",children:t})]}),n&&Ie("div",{className:"settings-row-control",children:n})]})},$x=({label:e,description:t,checked:n,onChange:r,disabled:o=false,onDisabledClick:i,settingId:a})=>Ie(Fx,{label:e,description:t,disabled:o,onDisabledClick:i,settingId:a,children:Ie(Mw,{checked:n,onChange:r,disabled:o})}),Ux=({tabs:e,activeTab:t,onTabChange:n})=>Ie("div",{className:"settings-tab-group",children:e.map(e=>Ie("button",{className:"settings-tab-item "+(t===e.id?"active":""),onClick:()=>n(e.id),children:e.label},e.id))}),jx=({title:e,Icon:t})=>Le("h1",{className:"settings-page-title",style:{display:"flex",alignItems:"center"},children:[t&&Ie(t,{size:28,className:"settings-page-title-icon",style:{marginRight:8,color:"var(--gh-primary, #4285f4)"}}),e]}),Hx=()=>{const e=String(So.length); return Le("div",{children:[ Ie(jx,{title:se("navAbout"),Icon:lt}), Ie("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",marginBottom:32},children:Le("div",{className:"about-slogan-badge",children:[ Ie("span",{style:{marginRight:6},children:"✨"}),se("aboutPageDesc"), Ie("span",{style:{marginLeft:6},children:"✨"})]})}), Le("div",{className:"about-hero-card",children:[ Ie("img",{src:Tw,alt:Aw,className:"about-hero-logo",onError:e=>{e.target.style.display="none";}}), Le("div",{className:"about-hero-content",children:[ Le("div",{className:"about-hero-title",children:[Aw, Le("span",{className:"about-hero-version",children:["v",Ew]})]}), Ie("div",{className:"about-hero-desc",children:se("aboutDescription",{appName:Aw})})]})]}), Ie("div",{className:"about-section-title",children:se("rateAndReview")}), Le("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:[ Le("a",{href:"https://chromewebstore.google.com/detail/ophel-ai-%E5%AF%B9%E8%AF%9D%E5%A2%9E%E5%BC%BA%E5%B7%A5%E5%85%B7/lpcohdfbomkgepfladogodgeoppclakd",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4285F4"},children:[ Le("div",{className:"about-link-header",children:[ Ie(Dt,{size:24,color:"var(--card-color)"}), Ie("span",{style:{fontWeight:600},children:se("chromeStore")})]}), Ie("button",{className:"about-link-btn",children:se("reviewBtn")})]}), Le("a",{href:"https://microsoftedge.microsoft.com/addons/detail/ophel-atlas-ai-chat-navi/ffpenkdeifijngifjmbbpijfpdhlolga",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#0078D7"},children:[ Le("div",{className:"about-link-header",children:[ Ie(Pt,{size:24}), Ie("span",{style:{fontWeight:600},children:se("edgeAddons")})]}), Ie("button",{className:"about-link-btn",children:se("reviewBtn")})]}), Le("a",{href:"https://addons.mozilla.org/zh-CN/firefox/addon/ophel-ai-chat-enhancer/",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#FF7139"},children:[ Le("div",{className:"about-link-header",children:[ Ie(qt,{size:24,color:"var(--card-color)"}), Ie("span",{style:{fontWeight:600},children:se("firefoxAddons")})]}), Ie("button",{className:"about-link-btn",children:se("reviewBtn")})]}), Le("a",{href:"https://greasyfork.org/zh-CN/scripts/563646-ophel-ai-chat-page-enhancer",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#4b5563"},children:[ Le("div",{className:"about-link-header",children:[ Ie(Rt,{size:24,color:"currentColor"}), Ie("span",{style:{fontWeight:600,color:"var(--gh-text)"},children:se("greasyFork")})]}), Ie("button",{className:"about-link-btn",children:se("reviewBtn")})]})]}), Ie("div",{className:"about-section-title",children:se("communityAndSupport")}), Le("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",marginBottom:16,fontStyle:"italic",textAlign:"center"},children:['"',se("communityMotto"),'"']}), Le("div",{className:"about-links-grid",style:{gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))"},children:[ Le("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#111827"},children:[ Le("div",{className:"about-link-header",children:[ Ie(ct,{size:22}), Ie("span",{style:{fontWeight:600},children:se("githubRepository")})]}), Ie("div",{className:"about-link-desc",children:se("githubDesc")}), Ie("button",{className:"about-link-btn about-star-btn",children:Le("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Ie(gt,{size:15,color:"currentColor",filled:true}),se("giveStar")]})})]}), Le("a",{href:"https://ko-fi.com/urzeye",target:"_blank",rel:"noopener noreferrer",className:"about-link-card kofi-card",style:{"--card-color":"#FF5E5B"},children:[ Le("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ Ie(Xt,{size:22,color:"var(--card-color)"}), Ie("span",{style:{fontWeight:600},children:se("kofiSupport")})]}), Ie("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:se("kofiDesc")}), Ie("button",{className:"about-link-btn",children:Le("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Ie(Xt,{size:14,color:"currentColor"}),se("kofiBtn")]})})]}), Le("a",{href:"https://github.com/urzeye/ophel",target:"_blank",rel:"noopener noreferrer",className:"about-link-card",style:{"--card-color":"#3B82F6"},children:[ Le("div",{className:"about-link-header",children:[ Ie(dt,{size:22,color:"var(--card-color)"}), Ie("span",{style:{fontWeight:600,color:"var(--card-color)"},children:se("projectWebsite")})]}), Ie("div",{className:"about-link-desc",children:se("websiteDesc")}), Ie("button",{className:"about-link-btn",children:Le("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Ie(dt,{size:14,color:"currentColor"}),se("visitWebsite")]})})]}), Le("a",{href:"https://discord.gg/rmPzb6Cx9u",target:"_blank",rel:"noopener noreferrer",className:"about-link-card discord-card",style:{"--card-color":"#5865F2"},children:[ Le("div",{className:"about-link-header",style:{color:"var(--card-color)"},children:[ Ie(Jt,{size:22,color:"var(--card-color)"}), Ie("span",{style:{fontWeight:600},children:se("discordCommunity")})]}), Ie("div",{className:"about-link-desc",style:{color:"var(--gh-text-secondary)"},children:se("discordDesc")}), Ie("button",{className:"about-link-btn",children:Le("span",{style:{display:"flex",alignItems:"center",gap:6},children:[ Ie(Jt,{size:14,color:"currentColor"}),se("joinDiscord")]})})]})]}), Ie("div",{className:"about-section-title",children:se("aboutSupportedPlatforms")}), Le("div",{className:"about-platforms-card",children:[ Le("div",{className:"about-platforms-header",children:[ Ie("div",{className:"about-platforms-desc",children:se("aboutSupportedPlatformsDesc",{count:e})}), Ie("span",{className:"about-platforms-count",children:e})]}), Ie("div",{className:"about-platforms-grid",children:So.map(e=>Le("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"about-platform-chip",title:e.url,children:[Bx[e.name]?Ie("img",{src:Bx[e.name],alt:e.name,className:"about-platform-chip-icon"}):Ie("span",{className:"about-platform-chip-emoji","aria-hidden":"true",children:e.icon}), Ie("span",{children:e.name})]},e.id))})]}), Ie("div",{className:"about-section-title",children:se("techStack")}), Le("div",{className:"about-tech-grid",children:[ Ie(Wx,{name:"Plasmo",version:"v0.89.0",desc:se("tsPlasmoDesc")}), Ie(Wx,{name:"React",version:"v18.2.0",desc:se("tsReactDesc")}), Ie(Wx,{name:"TypeScript",version:"v5.3.3",desc:se("tsTypescriptDesc")}), Ie(Wx,{name:"Zustand",version:"v5.0.3",desc:se("tsZustandDesc")}), Ie(Wx,{name:"Vite",version:"v5.0.0",desc:se("tsViteDesc")})]}), Ie("div",{className:"about-section-title",children:se("credits")}), Le("div",{className:"about-simple-card",children:[ Le("div",{className:"about-simple-header",children:[ Ie(ut,{size:18,style:{color:"#ef4444"}}),se("devAndMaintain")]}), Ie("p",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:1.6,marginBottom:16},children:se("creditsDesc")}), Le("div",{style:{display:"flex",gap:8},children:[ Ie(Gx,{text:"Made with ❤️"}), Ie(Gx,{text:"Open Source"}), Ie(Gx,{text:"Privacy First"})]}), Le("div",{style:{marginTop:16,fontSize:"12px",color:"var(--gh-text-secondary)"},children:["GNU GPLv3 © ", (new Date).getFullYear()," ",Aw]})]}), Le("div",{className:"about-privacy-banner",children:[ Ie(ht,{size:24,className:"about-privacy-icon"}), Le("div",{children:[ Ie("div",{className:"about-privacy-title",children:se("privacyTitle")}), Ie("div",{className:"about-privacy-desc",children:se("privacyText")})]})]})]})},Wx=({name:e,version:t,desc:n})=>Le("div",{className:"about-tech-card",children:[ Le("div",{className:"about-tech-header",children:[ Ie("div",{className:"about-tech-name",children:e}), Ie("div",{className:"about-tech-version",children:t})]}), Ie("div",{className:"about-tech-desc",children:n})]}),Gx=({text:e})=>Ie("span",{style:{display:"inline-flex",alignItems:"center",padding:"2px 8px",background:"var(--gh-bg-secondary)",border:"1px solid var(--gh-border)",borderRadius:"12px",fontSize:"12px",color:"var(--gh-text-secondary)"},children:e});var Qx={};const Vx=Cl($);var Kx;const Zx=Sl(function(){if(Kx)return Qx;Kx=1;var e=Qx&&Qx.__extends||function(){var e=function(t,n){return (e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);})(t,n)};return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r);}}(),t=Qx&&Qx.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n-1){e._history.stack=l.slice(0,c+1);var d=e._history.stack.length;if(d>100){var u=d-100;e._history.stack=l.slice(u,d),e._history.offset=Math.max(e._history.offset-u,0);}}var h=Date.now();if(r){var g=e._history.stack[e._history.offset];if(g&&h-g.timestamp<3e3){var p=/[^a-z0-9]([a-z0-9]+)$/i,m=null===(o=e._getLines(g.value,g.selectionStart).pop())||void 0===o?void 0:o.match(p),f=null===(i=e._getLines(n.value,n.selectionStart).pop())||void 0===i?void 0:i.match(p);if((null==m?void 0:m[1])&&(null===(a=null==f?void 0:f[1])||void 0===a?void 0:a.startsWith(m[1])))return void(e._history.stack[e._history.offset]=t(t({},n),{timestamp:h}))}}e._history.stack.push(t(t({},n),{timestamp:h})),e._history.offset++;},e._updateInput=function(t){var n=e._input;n&&(n.value=t.value,n.selectionStart=t.selectionStart,n.selectionEnd=t.selectionEnd,e.props.onValueChange(t.value));},e._applyEdits=function(n){var r=e._input,o=e._history.stack[e._history.offset];o&&r&&(e._history.stack[e._history.offset]=t(t({},o),{selectionStart:r.selectionStart,selectionEnd:r.selectionEnd})),e._recordChange(n),e._updateInput(n);},e._undoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r-1];o&&(e._updateInput(o),e._history.offset=Math.max(r-1,0));},e._redoEdit=function(){var t=e._history,n=t.stack,r=t.offset,o=n[r+1];o&&(e._updateInput(o),e._history.offset=Math.min(r+1,n.length-1));},e._handleKeyDown=function(t){var n=e.props,r=n.tabSize,o=n.insertSpaces,i=n.ignoreTabKey,a=n.onKeyDown;if(!a||(a(t),!t.defaultPrevented)){27===t.keyCode&&t.currentTarget.blur();var c=t.currentTarget,d=c.value,u=c.selectionStart,h=c.selectionEnd,g=(o?" ":"\t").repeat(r);if(9===t.keyCode&&!i&&e.state.capture)if(t.preventDefault(),t.shiftKey){var p=(y=e._getLines(d,u)).length-1,m=e._getLines(d,h).length-1,f=d.split("\n").map(function(e,t){return t>=p&&t<=m&&e.startsWith(g)?e.substring(g.length):e}).join("\n");if(d!==f){var b=y[p];e._applyEdits({value:f,selectionStart:(null==b?void 0:b.startsWith(g))?u-g.length:u,selectionEnd:h-(d.length-f.length)});}}else if(u!==h){var y,v=(y=e._getLines(d,u)).length-1,w=e._getLines(d,h).length-1;b=y[v];e._applyEdits({value:d.split("\n").map(function(e,t){return t>=v&&t<=w?g+e:e}).join("\n"),selectionStart:b&&/\S/.test(b)?u+g.length:u,selectionEnd:h+g.length*(w-v+1)});}else {var x=u+g.length;e._applyEdits({value:d.substring(0,u)+g+d.substring(h),selectionStart:x,selectionEnd:x});}else if(8===t.keyCode){var k=u!==h;if(d.substring(0,u).endsWith(g)&&!k){t.preventDefault();x=u-g.length;e._applyEdits({value:d.substring(0,u-g.length)+d.substring(h),selectionStart:x,selectionEnd:x});}}else if(13===t.keyCode){if(u===h){var S=e._getLines(d,u).pop(),C=null==S?void 0:S.match(/^\s+/);if(null==C?void 0:C[0]){t.preventDefault();var A="\n"+C[0];x=u+A.length;e._applyEdits({value:d.substring(0,u)+A+d.substring(h),selectionStart:x,selectionEnd:x});}}}else if(57===t.keyCode||219===t.keyCode||222===t.keyCode||192===t.keyCode){var E=void 0;57===t.keyCode&&t.shiftKey?E=["(",")"]:219===t.keyCode?E=t.shiftKey?["{","}"]:["[","]"]:222===t.keyCode?E=t.shiftKey?['"','"']:["'","'"]:192!==t.keyCode||t.shiftKey||(E=["`","`"]),u!==h&&E&&(t.preventDefault(),e._applyEdits({value:d.substring(0,u)+E[0]+d.substring(u,h)+E[1]+d.substring(h),selectionStart:u,selectionEnd:h+2}));}else !(l?t.metaKey&&90===t.keyCode:t.ctrlKey&&90===t.keyCode)||t.shiftKey||t.altKey?(l?t.metaKey&&90===t.keyCode&&t.shiftKey:s?t.ctrlKey&&89===t.keyCode:t.ctrlKey&&90===t.keyCode&&t.shiftKey)&&!t.altKey?(t.preventDefault(),e._redoEdit()):77!==t.keyCode||!t.ctrlKey||l&&!t.shiftKey||(t.preventDefault(),e.setState(function(e){return {capture:!e.capture}})):(t.preventDefault(),e._undoEdit());}},e._handleChange=function(t){var n=t.currentTarget,r=n.value,o=n.selectionStart,i=n.selectionEnd;e._recordChange({value:r,selectionStart:o,selectionEnd:i},true),e.props.onValueChange(r);},e._history={stack:[],offset:-1},e._input=null,e}return e(r,n),r.prototype.componentDidMount=function(){this._recordCurrentState();},Object.defineProperty(r.prototype,"session",{get:function(){return {history:this._history}},set:function(e){this._history=e.history;},enumerable:false,configurable:true}),r.prototype.render=function(){var e=this,n=this.props,r=n.value,o=n.style,s=n.padding,l=n.highlight,u=n.textareaId,g=n.textareaClassName,p=n.autoFocus,m=n.disabled,f=n.form,b=n.maxLength,y=n.minLength,v=n.name,w=n.placeholder,x=n.readOnly,k=n.required,S=n.onClick,C=n.onFocus,A=n.onBlur,E=n.onKeyUp;n.onKeyDown,n.onValueChange,n.tabSize,n.insertSpaces,n.ignoreTabKey;var T=n.preClassName,M=i(n,["value","style","padding","highlight","textareaId","textareaClassName","autoFocus","disabled","form","maxLength","minLength","name","placeholder","readOnly","required","onClick","onFocus","onBlur","onKeyUp","onKeyDown","onValueChange","tabSize","insertSpaces","ignoreTabKey","preClassName"]),_={paddingTop:"object"==typeof s?s.top:s,paddingRight:"object"==typeof s?s.right:s,paddingBottom:"object"==typeof s?s.bottom:s,paddingLeft:"object"==typeof s?s.left:s},I=l(r);return a.createElement("div",t({},M,{style:t(t({},h.container),o)}),a.createElement("pre",t({className:T,"aria-hidden":"true",style:t(t(t({},h.editor),h.highlight),_)},"string"==typeof I?{dangerouslySetInnerHTML:{__html:I+"
"}}:{children:I})),a.createElement("textarea",{ref:function(t){return e._input=t},style:t(t(t({},h.editor),h.textarea),_),className:c+(g?" ".concat(g):""),id:u,value:r,onChange:this._handleChange,onKeyDown:this._handleKeyDown,onClick:S,onKeyUp:E,onFocus:C,onBlur:A,disabled:m,form:f,maxLength:b,minLength:y,name:v,placeholder:w,readOnly:x,required:k,autoFocus:p,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:false,"data-gramm":false}),a.createElement("style",{dangerouslySetInnerHTML:{__html:d}}))},r.defaultProps={tabSize:2,insertSpaces:true,ignoreTabKey:false,padding:0},r}(a.Component);Qx.default=u;var h={container:{position:"relative",textAlign:"left",boxSizing:"border-box",padding:0,overflow:"hidden"},textarea:{position:"absolute",top:0,left:0,height:"100%",width:"100%",resize:"none",color:"inherit",overflow:"hidden",MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",WebkitTextFillColor:"transparent"},highlight:{position:"relative",pointerEvents:"none"},editor:{margin:0,border:0,background:"none",boxSizing:"inherit",display:"inherit",fontFamily:"inherit",fontSize:"inherit",fontStyle:"inherit",fontVariantLigatures:"inherit",fontWeight:"inherit",letterSpacing:"inherit",lineHeight:"inherit",tabSize:"inherit",textIndent:"inherit",textRendering:"inherit",textTransform:"inherit",whiteSpace:"pre-wrap",wordBreak:"keep-all",overflowWrap:"break-word"}};return Qx}());class Yx extends a{constructor(e){super(e);let t=false;try{document.createElement("div").innerHTML="";}catch{t=true;}this.state={hasError:t};}static getDerivedStateFromError(e){return {hasError:true}}componentDidCatch(e,t){}render(){if(this.state.hasError){const{value:e,onValueChange:t,style:n,placeholder:r,className:o,fallbackPlaceholder:i}=this.props; return Ie("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:Ie("textarea",{className:`settings-textarea ${o||""}`,value:e,onChange:e=>t(e.target.value),placeholder:i||r,style:{...n,fontFamily:'"Menlo", "Monaco", "Consolas", monospace',resize:"none",flex:1,width:"100%",height:"100%",border:"none",outline:"none",padding:"12px"}})})} return Ie(Zx,{...this.props})}}const Jx=({preset:e})=>{const t=e.variables,n=t["--gh-bg"]||"#ffffff",r=t["--gh-header-bg"]||t["--gh-primary"]||"#4285f4",o=t["--gh-border"]||"#e5e7eb",i=t["--gh-primary"]||"#4285f4",a=t["--gh-text"]||"#374151",s=t["--gh-text-secondary"]||"#9ca3af",l=t["--gh-bg-secondary"]||"#f3f4f6"; return Le("div",{className:"theme-preview-layout",style:{backgroundColor:n,borderColor:o},children:[ Le("div",{className:"theme-preview-header",style:{backgroundColor:r},children:[ Ie("div",{className:"theme-preview-dot"}), Ie("div",{className:"theme-preview-dot delay-1"}), Ie("div",{className:"theme-preview-dot delay-2"})]}), Le("div",{className:"theme-preview-body",children:[ Le("div",{className:"theme-preview-sidebar",style:{backgroundColor:l,borderColor:o},children:[ Ie("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.3}}), Ie("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), Ie("div",{className:"theme-preview-line",style:{backgroundColor:s,opacity:.3}}), Ie("div",{className:"theme-preview-active-item",style:{backgroundColor:i,opacity:.15}})]}), Le("div",{className:"theme-preview-content",children:[ Ie("div",{className:"theme-preview-hero",style:{backgroundColor:i,opacity:.1}}), Le("div",{className:"theme-preview-row",children:[ Ie("div",{className:"theme-preview-avatar",style:{backgroundColor:s,opacity:.2}}), Le("div",{style:{flex:1},children:[ Ie("div",{className:"theme-preview-line",style:{backgroundColor:a,opacity:.6,marginBottom:4}}), Ie("div",{className:"theme-preview-line short",style:{backgroundColor:s,opacity:.4}})]})]}), Ie("div",{className:"theme-preview-button",style:{backgroundColor:i}})]})]})]})};Ml.registerLanguage("css",Rl);const Xx=({preset:e,isActive:t,onClick:n})=>{const r=`themePreset_${e.id}`,o=se(r),i=o&&o!==r?o:e.name; return Le("div",{className:"settings-theme-card "+(t?"active":""),onClick:n,children:[ Ie(Jx,{preset:e}), Ie("div",{className:"settings-theme-name",children:i})]})},ek=({siteId:e,initialTab:t})=>{const[n,r]=z(t||Ir),{settings:o,setSettings:i}=Ai();_(()=>{t&&r(t);},[t]);const[a,s]=z(false),[l,c]=z(null),d=o?.theme?.sites?.[e]||o?.theme?.sites?._default;if(!o)return null;const u=[{id:Ir,label:se("themePresetsTab")},{id:Lr,label:se("customStylesTab")}],h=o?.theme?.customStyles||[],g=e=>{const t=(e=>{const t={},n=/(--[\w-]+)\s*:\s*([^;]+);/g;let r;for(;null!==(r=n.exec(e));){const e=r[1],n=r[2].trim();t[e]=n;}return t})(e.css),n={"--gh-bg":"light"===e.mode?"#f3f4f6":"#1f2937","--gh-header-bg":"light"===e.mode?"#e5e7eb":"#374151","--gh-border":"light"===e.mode?"#d1d5db":"#4b5563","--gh-primary":"#4285f4","--gh-text":"light"===e.mode?"#374151":"#f9fafb","--gh-text-secondary":"light"===e.mode?"#6b7280":"#9ca3af","--gh-bg-secondary":"light"===e.mode?"#ffffff":"#1f2937"};return {id:e.id,name:e.name,variables:{...n,...t}}},p=[...Bv,...h.filter(e=>"light"===e.mode).map(g)],m=[...Ov,...h.filter(e=>"dark"===e.mode).map(g)]; return Le("div",{children:[ Ie(jx,{title:se("navAppearance"),Icon:ot}), Ie("p",{className:"settings-page-desc",children:se("appearancePageDesc")}), Ie(Ox,{settingId:"appearance-theme-sync",children:Ie($x,{label:se("syncNativePageThemeLabel"),description:se("syncNativePageThemeDesc"),checked:o?.theme?.syncNativePageTheme??true,onChange:()=>i({theme:{...o?.theme,syncNativePageTheme:!(o?.theme?.syncNativePageTheme??1)}}),settingId:"appearance-sync-native-page-theme"})}), Ie(Ux,{tabs:u,activeTab:n,onTabChange:r}),n===Ir&&Le(_e,{children:[ Ie(Ox,{title:se("lightModePreset"),description:se("lightModePresetDesc"),settingId:"appearance-preset-light",children:Ie("div",{className:"settings-theme-grid",children:p.map(t=>Ie(Xx,{preset:t,isActive:(d?.lightStyleId||"google-gradient")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("light");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"light"},lightStyleId:t}}}});})(t.id)},t.id))})}), Ie(Ox,{title:se("darkModePreset"),description:se("darkModePresetDesc"),settingId:"appearance-preset-dark",children:Ie("div",{className:"settings-theme-grid",children:m.map(t=>Ie(Xx,{preset:t,isActive:(d?.darkStyleId||"classic-dark")===t.id,onClick:()=>(async t=>{const n=window.__ophelThemeManager,r="system"===d?.mode;!r&&n?.setMode&&await n.setMode("dark");const a=o?.theme?.sites||{},s=a[e]||a._default||{};i({theme:{...o?.theme,sites:{...o?.theme?.sites,[e]:{...s,...r?{}:{mode:"dark"},darkStyleId:t}}}});})(t.id)},t.id))})})]}),n===Lr&&Ie(_e,{children:Le(Ox,{title:se("customCSS"),description:se("customCSSDesc"),settingId:"appearance-custom-styles",children:[ Le("button",{className:"settings-btn settings-btn-primary",onClick:()=>{c({id:"",name:"",css:"/* 🎨 Custom CSS Cheat Sheet\n * 以下是本扩展使用的主要 CSS 类名,您可以自由覆盖。\n */\n\n/* === 主题变量 === */\n/*\n:host {\n --gh-bg: #ffffff;\n --gh-text: #1f2937;\n --gh-primary: #4285f4;\n}\n*/\n\n/* === 面板样式 === */\n/*\n.gh-main-panel { }\n.gh-panel-header { }\n.gh-panel-content { }\n*/\n",mode:"light"}),s(true);},style:{marginBottom:"16px"},children:["➕ ",se("addCustomStyle")]}),0===(o?.theme?.customStyles||[]).length?Ie("div",{style:{padding:"20px",textAlign:"center",color:"var(--gh-text-secondary, #9ca3af)",fontSize:"13px",border:"1px dashed var(--gh-border, #e5e7eb)",borderRadius:"8px"},children:se("noCustomStyles")}):Ie("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:(o?.theme?.customStyles||[]).map(e=>Le("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px",background:"var(--gh-bg-secondary, #f9fafb)",borderRadius:"8px"},children:[ Le("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Ie("span",{style:{fontSize:"11px",padding:"2px 8px",borderRadius:"4px",backgroundColor:"light"===e.mode?"rgba(251, 191, 36, 0.2)":"rgba(99, 102, 241, 0.2)",color:"light"===e.mode?"#b45309":"#4338ca"},children:"light"===e.mode?"☀️":"🌙"}), Ie("span",{style:{fontSize:"14px",fontWeight:500},children:e.name||se("unnamedStyle")})]}), Le("div",{style:{display:"flex",gap:"8px"},children:[ Le("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{c(e),s(true);},style:{padding:"6px 12px",fontSize:"12px"},children:["✏️ ",se("edit")]}), Ie("button",{className:"settings-btn settings-btn-danger",onClick:()=>(e=>{if(confirm(se("confirmDeleteStyle"))){const t=(o?.theme?.customStyles||[]).filter(t=>t.id!==e);i({theme:{...o?.theme,customStyles:t}});}})(e.id,e.name),style:{padding:"6px 12px",fontSize:"12px"},children:"🗑️"})]})]},e.id))})]})}),a&&l&&Ie("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},children:Le("div",{style:{background:"var(--gh-bg, white)",borderRadius:"12px",width:"800px",maxWidth:"95%",height:"85vh",display:"flex",flexDirection:"column",boxShadow:"0 4px 20px rgba(0,0,0,0.2)"},children:[ Le("div",{style:{padding:"16px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("h3",{style:{margin:0,fontSize:"16px",fontWeight:600},children:l.id?se("editStyle"):se("newStyle")}), Ie("button",{onClick:()=>s(false),style:{background:"none",border:"none",cursor:"pointer",fontSize:"18px",color:"var(--gh-text-secondary, #9ca3af)"},children:"✕"})]}), Le("div",{style:{padding:"16px",overflowY:"auto",flex:1,display:"flex",flexDirection:"column"},children:[ Le("div",{style:{marginBottom:"16px"},children:[ Ie("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:se("styleNameLabel")}), Ie("input",{type:"text",className:"settings-input",value:l.name,onChange:e=>c({...l,name:e.target.value}),placeholder:se("enterStyleName"),style:{width:"100%"}})]}), Le("div",{style:{marginBottom:"16px"},children:[ Ie("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:se("styleModeLabel")}), Le("div",{style:{display:"flex",gap:"12px"},children:[ Le("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ Ie("input",{type:"radio",checked:"light"===l.mode,onChange:()=>c({...l,mode:"light"})}), Le("span",{children:["☀️ ",se("lightMode")]})]}), Le("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[ Ie("input",{type:"radio",checked:"dark"===l.mode,onChange:()=>c({...l,mode:"dark"})}), Le("span",{children:["🌙 ",se("darkMode")]})]})]})]}), Le("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[ Le("label",{style:{fontSize:"13px",fontWeight:500,marginBottom:"6px",display:"block"},children:["CSS ",se("code")]}), Ie("div",{className:"settings-textarea",style:{flex:1,padding:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:Ie(Yx,{value:l.css,onValueChange:e=>c({...l,css:e}),highlight:e=>qp(Ml.highlight(e,{language:"css"}).value),padding:12,style:{fontFamily:'"Menlo", "Monaco", "Consolas", monospace',fontSize:13,minHeight:"100%"},textareaClassName:"focus-outline-none"})})]})]}), Le("div",{style:{padding:"16px",borderTop:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"flex-end",gap:"8px"},children:[ Ie("button",{className:"settings-btn settings-btn-secondary",onClick:()=>s(false),children:se("cancel")}), Ie("button",{className:"settings-btn settings-btn-primary",onClick:()=>{if(!l)return;if(!l.name.trim())return void Li(se("pleaseEnterStyleName"));const e=o?.theme?.customStyles||[];let t;if(l.id)t=e.map(e=>e.id===l.id?l:e);else {const n={...l,id:crypto.randomUUID()};t=[...e,n];}i({theme:{...o?.theme,customStyles:t}}),s(false),Li(l.id?se("styleUpdated"):se("styleCreated"));},children:l.id?se("save"):se("create")})]})]})})]})};function tk(e){const t=[];if(!e||"object"!=typeof e)return {valid:false,errorKeys:["backupValidationInvalidFormat"]};if(e.version||t.push("backupValidationMissingVersion"),!e.data||"object"!=typeof e.data)return t.push("backupValidationMissingData"),{valid:false,errorKeys:t};const n=e.data;return void 0!==n.settings&&("object"!=typeof n.settings||Array.isArray(n.settings))&&t.push("backupValidationSettingsType"),void 0!==n.prompts&&(Array.isArray(n.prompts)||t.push("backupValidationPromptsType")),void 0!==n.folders&&(Array.isArray(n.folders)||t.push("backupValidationFoldersType")),void 0!==n.conversations&&("object"!=typeof n.conversations||Array.isArray(n.conversations))&&t.push("backupValidationConversationsType"),void 0!==n.readingHistory&&("object"!=typeof n.readingHistory||Array.isArray(n.readingHistory))&&t.push("backupValidationHistoryType"),{valid:0===t.length,errorKeys:t}}function nk(e,t){const n=e.getElementsByTagNameNS("*",t)[0];return n?.textContent?.trim()||null}function rk(e,t,n){if(!e)return null;const r=function(e){try{return decodeURIComponent(e)}catch{return e}}(e.trim());if(!r.endsWith(".json")||!r.includes(`${Cw}_backup_`))return null;const o=t?parseInt(t.trim(),10):0,i=Number.isFinite(o)?o:0,a=n?new Date(n.trim()):new Date(0),s=Number.isNaN(a.getTime())?new Date(0):a;return {name:r.split("/").pop()||r,path:r,size:i,lastModified:s}}function ok(e){return function(e){if("undefined"==typeof DOMParser)return null;try{const t=(new DOMParser).parseFromString(e,"application/xml");return function(e){return e.getElementsByTagName("parsererror").length>0}(t)?null:Array.from(t.getElementsByTagNameNS("*","response")).map(e=>rk(nk(e,"href"),nk(e,"getcontentlength"),nk(e,"getlastmodified"))).filter(e=>Boolean(e))}catch{return null}}(e)??function(e){const t="(?:[a-zA-Z0-9_-]+:)?",n=new RegExp(`<${t}response[^>]*>([\\s\\S]*?)<\\/${t}response>`,"gi");return Array.from(e.matchAll(n)).map(e=>{const n=e[1],r=n.match(new RegExp(`<${t}href[^>]*>([^<]+)<\\/${t}href>`,"i")),o=n.match(new RegExp(`<${t}getcontentlength[^>]*>([^<]+)<\\/${t}getcontentlength>`,"i")),i=n.match(new RegExp(`<${t}getlastmodified[^>]*>([^<]+)<\\/${t}getlastmodified>`,"i"));return rk(r?.[1]??null,o?.[1]??null,i?.[1]??null)}).filter(e=>Boolean(e))}(e)}const ik=[{id:"jianguoyun",labelKey:"providerJianguoyun",urlTemplate:"https://dav.jianguoyun.com/dav/",hintKey:"providerJianguoyunHint",helpUrl:"https://help.jianguoyun.com/?p=2064",passwordPlaceholderKey:"providerJianguoyunPasswordPlaceholder"},{id:"infinicloud",labelKey:"providerInfinicloud",urlTemplate:"https://connect.infini.cloud/dav",hintKey:"providerInfinicloudHint"},{id:"pcloud",labelKey:"providerPcloud",urlTemplate:"https://webdav.pcloud.com",hintKey:"providerPcloudHint",helpUrl:"https://docs.pcloud.com/protocols/webdav_protocol/"},{id:"nextcloud",labelKey:"providerNextcloud",urlTemplate:"",urlPlaceholder:"https://your-domain.com/remote.php/dav/files/username/",hintKey:"providerNextcloudHint"},{id:"synology",labelKey:"providerSynology",urlTemplate:"",urlPlaceholder:"https://your-nas.example.com/webdav/",hintKey:"providerSynologyHint",helpUrl:"https://kb.synology.com/en-global/DSM/help/DSM/AdminCenter/file_webdav"},{id:"seafile",labelKey:"providerSeafile",urlTemplate:"",urlPlaceholder:"https://your-seafile-domain.com/seafdav",hintKey:"providerSeafileHint"},{id:"custom",labelKey:"providerCustom",urlTemplate:"",urlPlaceholder:"https://dav.example.com/dav/"}];function ak(e){return ik.some(t=>t.id===e)}function sk(e){if(!e)return "custom";const t=e.toLowerCase();return t.includes("jianguoyun.com")||t.includes("nutscloud.com")?"jianguoyun":t.includes("infini.cloud")?"infinicloud":t.includes("pcloud.com")?"pcloud":t.includes("/remote.php/")?"nextcloud":t.includes("/seafdav")||t.includes("/seafile-webdav")?"seafile":t.includes(".quickconnect.to")||t.includes(".synology.me")||/\/webdav\//.test(t)?"synology":"custom"}const lk={enabled:false,url:"",username:"",password:"",syncMode:"manual",syncInterval:30,remoteDir:Cw};class ck{config=lk;autoSyncTimer=null;constructor(){this.loadConfig();}async loadConfig(){const{getSettingsState:e}=await r(async()=>{const{getSettingsState:e}=await Promise.resolve().then(()=>_i);return {getSettingsState:e}},void 0),t=e();if(t?.webdav){const e={...lk,...t.webdav,provider:ak(t.webdav.provider)?t.webdav.provider:void 0};!e.provider&&e.url&&(e.provider=sk(e.url)),this.config=e;}return this.config} /** * 设置配置 * @param config 配置对象 * @param persist 是否持久化到 storage (默认 true) */async setConfig(e,t=true){if(this.config={...this.config,...e},t){const{useSettingsStore:e}=await r(async()=>{const{useSettingsStore:e}=await Promise.resolve().then(()=>_i);return {useSettingsStore:e}},void 0);e.getState().setSettings({webdav:this.config});}}async saveConfig(e){return this.setConfig(e,true)}getConfig(){return {...this.config}}async testConnection(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const e=await this.request("PROPFIND",this.config.remoteDir,null,{Depth:"0"});return e.ok||404===e.status?{success:!0,messageKey:"webdavConnectionSuccess"}:401===e.status?{success:!1,messageKey:"webdavAuthFailed"}:{success:!1,messageKey:"webdavConnectionFailed",messageArgs:{status:e.status}}}catch(e){return {success:false,messageKey:"webdavConnectionFailed",messageArgs:{error:String(e)}}}}async upload(){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});const e=await new Promise(e=>chrome.storage.local.get(null,e)),t=Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return eo.includes(e)&&n?.state&&(n=to.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}})),n={version:3,timestamp:(new Date).toISOString(),data:t},r=function(){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return `${Cw}_backup_${t}-${n}-${r}_${o}-${i}-${a}.json`}(),o=this.buildRemotePath(r);if(this.config.remoteDir)try{await this.request("MKCOL",this.config.remoteDir);}catch{}const i=await this.request("PUT",o,JSON.stringify(n,null,2),{"Content-Type":"application/json"});if(i.ok||201===i.status||204===i.status){const e=Date.now();return await this.saveConfig({lastSyncTime:e,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavUploadSuccess",timestamp:e}}return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavUploadFailed",messageArgs:{status:i.status}}}catch(e){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavUploadFailed",messageArgs:{error:String(e)}}}}async getBackupList(e=10){if(!this.config.url||!this.config.username||!this.config.password)return [];try{const t='\n\n \n \n \n \n \n',n=await this.request("PROPFIND",this.config.remoteDir,t,{Depth:"1","Content-Type":"application/xml"});if(!n.ok)return [];const r=ok(await n.text());return r.sort((e,t)=>t.lastModified.getTime()-e.lastModified.getTime()),r.slice(0,e)}catch(t){return console.error("Failed to get backup list:",t),[]}}async deleteFile(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{const t=this.buildRemotePath(e),n=await this.request("DELETE",t);return n.ok||204===n.status||404===n.status?{success:!0,messageKey:"webdavDeleteSuccess"}:{success:!1,messageKey:"webdavDeleteFailed",messageArgs:{status:n.status}}}catch(t){return {success:false,messageKey:"webdavDeleteFailed",messageArgs:{error:String(t)}}}} /** * 从 WebDAV 下载并恢复数据 * @param targetFileName 可选,指定下载的文件名。若不指定则下载最新。 */async download(e){if(!this.config.url||!this.config.username||!this.config.password)return {success:false,messageKey:"webdavConfigIncomplete"};try{await this.saveConfig({lastSyncStatus:"syncing"});let t=e;if(!t){const e=await this.getBackupList(1);if(0===e.length)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavFileNotFound"};t=e[0].name;}const n=this.buildRemotePath(t),r=await this.request("GET",n);if(!r.ok)return await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavDownloadFailed",messageArgs:{status:r.status}};const o=await r.text(),i=JSON.parse(o),a=tk(i);if(!a.valid)return console.error("Backup validation failed:",a.errorKeys),await this.saveConfig({lastSyncStatus:"failed"}),{success:!1,messageKey:"webdavInvalidFormat"};const s=this.config,l=Object.fromEntries(Object.entries(i.data).map(([e,t])=>{if(null==t)return [e,t];if(eo.includes(e)){let n;if(to.includes(e))if("object"!=typeof t||Array.isArray(t))n="readingHistory"===e?{history:t}:{[e]:t};else {const r=t;n="conversations"===e&&void 0!==r.conversations?t:"readingHistory"!==e||void 0===r.history&&void 0===r.lastCleanupRun?"readingHistory"===e?{history:t}:{[e]:t}:t;}else n={[e]:t};return [e,JSON.stringify({state:n,version:0})]}return "object"==typeof t?[e,JSON.stringify(t)]:[e,t]}));await new Promise((e,t)=>chrome.storage.local.set(l,()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await new Promise((e,t)=>{chrome.storage.local.get("settings",n=>{if(chrome.runtime.lastError)return void t(chrome.runtime.lastError);let r=n.settings;if("string"==typeof r)try{r=JSON.parse(r);}catch{return void e()}r?.state?.settings&&(r.state.settings.webdav=s),chrome.storage.local.set({settings:JSON.stringify(r)},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e());});});const c=Date.now();return await this.saveConfig({lastSyncTime:c,lastSyncStatus:"success"}),{success:!0,messageKey:"webdavDownloadSuccess",timestamp:c}}catch(t){return await this.saveConfig({lastSyncStatus:"failed"}),{success:false,messageKey:"webdavDownloadFailed",messageArgs:{error:String(t)}}}}startAutoSync(){this.stopAutoSync(),this.config.enabled&&"auto"===this.config.syncMode&&this.config.syncInterval>0&&(this.autoSyncTimer=setInterval(()=>{this.upload();},60*this.config.syncInterval*1e3));}stopAutoSync(){this.autoSyncTimer&&(clearInterval(this.autoSyncTimer),this.autoSyncTimer=null);}buildRemotePath(e){let t=this.config.remoteDir.trim();return t=t.replace(/^\/+|\/+$/g,""),t?`${t}/${e}`:e}async request(e,t,n,r){const o=this.buildUrl(t);return this.requestViaGM(e,o,n,r)}requestViaGM(e,t,n,r){return new Promise((o,i)=>{const a={...r};if(this.config.username&&this.config.password){const e=btoa(`${this.config.username}:${this.config.password}`);a.Authorization=`Basic ${e}`;}GM_xmlhttpRequest({method:e,url:t,headers:a,data:n||void 0,onload:e=>{o({ok:e.status>=200&&e.status<300,status:e.status,statusText:e.statusText,text:async()=>e.responseText,headers:{get:t=>{const n=e.responseHeaders?.split("\r\n")||[];for(const e of n){const[n,...r]=e.split(":");if(n?.toLowerCase()===t.toLowerCase())return r.join(":").trim()}return null}}});},onerror:e=>{i(new Error(e.statusText||"GM_xmlhttpRequest failed"));},ontimeout:()=>{i(new Error("Request timeout"));}});})}async requestViaBackground(e,t,n,r){const o=await chrome.runtime.sendMessage({type:"WEBDAV_REQUEST",method:e,url:t,body:n,headers:r,auth:{username:this.config.username,password:this.config.password}});if(!o.success)throw new Error(o.error||"WebDAV request failed");return {ok:o.status>=200&&o.status<300,status:o.status,statusText:o.statusText,text:async()=>o.body,headers:{get:e=>o.headers?.[e.toLowerCase()]||null}}}buildUrl(e){let t=this.config.url.trim();t.endsWith("/")||(t+="/");return t+e.replace(/^\/+/,"")}}let dk=null;function uk(){return dk||(dk=new ck),dk}let hk=null;const gk=Bo()($o((e,t)=>(hk=()=>e({_hasHydrated:true}),{history:{},lastCleanupRun:0,_hasHydrated:false,savePosition:(t,n)=>e(e=>({history:{...e.history,[t]:n}})),getPosition:e=>t().history[e],cleanup:n=>{if(-1===n)return;const r=Date.now(),o=t();if(r-o.lastCleanupRun<864e5)return;const i=24*n*60*60*1e3,a={};let s=false;for(const[e,t]of Object.entries(o.history))r-t.ts<=i?a[e]=t:s=true;e(s?{history:a,lastCleanupRun:r}:{lastCleanupRun:r});},setHasHydrated:t=>e({_hasHydrated:t})}),{name:"readingHistory",storage:Oo(()=>di),partialize:e=>({history:e.history,lastCleanupRun:e.lastCleanupRun}),onRehydrateStorage:()=>()=>{hk?.();}})),pk=()=>gk.getState(),mk=Object.freeze(Object.defineProperty({__proto__:null,getReadingHistoryStore:pk,useReadingHistoryStore:gk},Symbol.toStringTag,{value:"Module"})),fk=e=>{if(0===e)return "0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["B","KB","MB","GB","TB"][t]},bk=e=>e instanceof Error?e.message:String(e),yk=({onClose:e,onRestore:t})=>{const[n,r]=z([]),[i,a]=z(true),[s,l]=z({show:false,title:"",message:"",onConfirm:()=>{}}),c=async()=>{a(true);try{const e=uk(),t=await e.getBackupList();r(t);}catch(e){Li(se("loadFailed")+": "+String(e));}finally{a(false);}};o.useEffect(()=>{c();},[]); return Le("div",{className:"settings-modal-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0,0,0,0.5)",zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center"},children:[s.show&&Ie(Lw,{title:s.title,message:s.message,danger:s.danger,onConfirm:s.onConfirm,onCancel:()=>l(e=>({...e,show:false}))}), Le("div",{className:"settings-modal",style:{width:"500px",height:"600px",background:"var(--gh-card-bg, #ffffff)",borderRadius:"12px",display:"flex",flexDirection:"column",overflow:"hidden"},children:[ Le("div",{style:{padding:"16px 20px",borderBottom:"1px solid var(--gh-border, #e5e7eb)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("div",{style:{fontWeight:600,fontSize:"16px"},children:se("webdavBackupList")}), Le("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Ie(up,{content:se("refresh"),children:Ie("button",{onClick:c,className:"settings-btn settings-btn-secondary","aria-label":se("refresh"),style:{padding:"6px",display:"flex",alignItems:"center"},children:Ie(Fe,{size:16})})}), Ie("button",{onClick:e,className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px"},children:"✕"})]})]}), Ie("div",{style:{overflowY:"auto",padding:"16px",flex:1},children:i?Ie("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:se("loading")}):0===n.length?Ie("div",{style:{textAlign:"center",padding:"20px",color:"var(--gh-text-secondary)"},children:se("noBackupsFound")}):Ie("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:n.map(e=>Le("div",{style:{padding:"12px 14px",background:"var(--gh-bg, #ffffff)",border:"1px solid var(--gh-border, #e5e7eb)",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"space-between",transition:"border-color 0.15s"},children:[ Le("div",{style:{minWidth:0,flex:1,marginRight:"12px"},children:[ Ie("div",{style:{fontSize:"13px",fontWeight:500,color:"var(--gh-text, #1f2937)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}), Le("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginTop:"2px"},children:[fk(e.size)," • ",e.lastModified.toLocaleString()]})]}), Le("div",{style:{display:"flex",gap:"6px",flexShrink:0},children:[ Ie(up,{content:se("restore"),children:Ie("button",{onClick:()=>(e=>{l({show:true,title:se("restore"),message:se("backupRestoreConfirmMsg",{name:e.name}),danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const n=uk();if((await n.download(e.name)).success){try{"extension"===qi.type&&"undefined"!=typeof chrome&&(await new Promise((e,t)=>chrome.storage.local.set({[ai]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),await chrome.runtime.sendMessage({type:xp}));}catch{}Li(se("restoreSuccess")),setTimeout(()=>{t();},1500);}else Li(se("restoreError")),a(!1);}catch(n){Li(se("restoreError")+": "+String(n)),a(false);}}});})(e),"aria-label":se("restore"),style:{padding:"7px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"7px",border:"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 25%, transparent)",background:"color-mix(in srgb, var(--gh-primary, #4285f4) 8%, transparent)",color:"var(--gh-primary, #4285f4)",cursor:"pointer",transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-primary, #4285f4) 16%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-primary, #4285f4) 40%, transparent)";},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-primary, #4285f4) 8%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-primary, #4285f4) 25%, transparent)";},children:Ie(nn,{size:16,color:"currentColor"})})}), Ie(up,{content:se("delete"),children:Ie("button",{onClick:()=>(e=>{l({show:true,title:se("delete"),message:se("backupDeleteCloudConfirmMsg",{name:e.name}),danger:true,onConfirm:async()=>{l(e=>({...e,show:false}));try{a(!0);const t=uk();(await t.deleteFile(e.name)).success?(Li(se("deleteSuccess")),c()):(Li(se("deleteError")),a(!1));}catch(t){Li(se("deleteError")+": "+String(t)),a(false);}}});})(e),"aria-label":se("delete"),style:{padding:"7px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"7px",border:"1px solid color-mix(in srgb, var(--gh-danger, #ef4444) 20%, transparent)",background:"color-mix(in srgb, var(--gh-danger, #ef4444) 7%, transparent)",color:"var(--gh-danger, #ef4444)",cursor:"pointer",transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-danger, #ef4444) 14%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-danger, #ef4444) 35%, transparent)";},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--gh-danger, #ef4444) 7%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--gh-danger, #ef4444) 20%, transparent)";},children:Ie(Bt,{size:16,color:"currentColor"})})})]})]},e.name))})})]})]})},vk=({onNavigate:e})=>{const{settings:t,setSettings:n,resetSettings:r}=Ai(),[o,i]=z(false),a=P(null),[s,l]=z(""),[c,d]=z({url:"",username:"",password:"",remoteDir:"ophel",provider:"custom"});_(()=>{if(t?.webdav){const e=t.webdav,n=ak(e.provider)?e.provider:e.url?sk(e.url):"custom";d(t=>({...t,...e,provider:n}));}},[t?.webdav]);const[u,h]=z({show:false,title:"",message:"",onConfirm:()=>{}}),[g,p]=z({show:false,onConfirm:()=>{}});if(!t)return null;const m=async e=>{await new Promise((t,n)=>chrome.storage.local.set(e,()=>chrome.runtime.lastError?n(chrome.runtime.lastError):t()));},f=async e=>{try{let n={};const r=(new Date).toISOString();let o=`ophel-backup-${r.slice(0,10)}.json`;if("full"===e){const e=await new Promise(e=>chrome.storage.local.get(null,e));n={version:3,timestamp:r,type:"full",data:Object.fromEntries(Object.entries(e).map(([e,t])=>{try{let n="string"==typeof t?JSON.parse(t):t;return eo.includes(e)&&n?.state&&(n=to.includes(e)?n.state:void 0!==n.state[e]?n.state[e]:n.state),[e,n]}catch{return [e,t]}}))};}else if("prompts"===e){const e=await new Promise(e=>chrome.storage.local.get("prompts",e));let i=[];try{const t="string"==typeof e.prompts?JSON.parse(e.prompts):e.prompts;t?.state?.prompts&&(i=t.state.prompts);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"prompts",data:{prompts:i}},o=`ophel-prompts-${r.slice(0,10)}.json`;}else if("settings"===e){const e=await new Promise(e=>chrome.storage.local.get("settings",e));let i={};try{const t="string"==typeof e.settings?JSON.parse(e.settings):e.settings;t?.state?.settings?i=t.state.settings:t?.state&&(i=t.state);}catch(t){console.error(t);}n={version:3,timestamp:r,type:"settings",data:{settings:i}},o=`ophel-settings-${r.slice(0,10)}.json`;}const i=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),a=URL.createObjectURL(i),s=document.createElement("a");s.href=a,s.download=o,s.click(),URL.revokeObjectURL(a),Li(se("exportSuccess"));}catch(n){Li(se("exportError"));}},b=async e=>{try{const n=JSON.parse(e),r=tk(n);if(!r.valid){r.errorKeys.map(e=>se(e)).join(", ");return console.error("Backup validation failed:",r.errorKeys),void Li(se("invalidBackupFile"))}h({show:!0,title:se("importData"),message:Le("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Ie("div",{children:se("importConfirm")}), Ie("div",{style:{border:"1px solid color-mix(in srgb, var(--gh-primary, #4285f4) 15%, transparent)",background:"var(--gh-hover, #f8fafc)",borderRadius:"8px",padding:"10px 12px"},children:Le("div",{style:{display:"grid",gridTemplateColumns:"72px 1fr",rowGap:"6px",columnGap:"10px",alignItems:"start"},children:[ Ie("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:se("backupTime")}), Ie("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:String(n.timestamp||"-")}), Ie("div",{style:{color:"var(--gh-text-secondary, #6b7280)"},children:se("backupType")}), Ie("div",{style:{color:"var(--gh-text, #111827)",fontWeight:500},children:(t=n.type,"full"===t?se("fullBackup"):"prompts"===t?se("promptsBackup"):"settings"===t?se("settingsBackup"):String(t||se("unknown")))})]})}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:se("openAiPagesWillRefresh")})]}),danger:!0,onConfirm:async()=>{h(e=>({...e,show:!1}));try{const e={};Object.entries(n.data).forEach(([t,n])=>{if(null!=n)if(eo.includes(t)){let r=n;if(to.includes(t))if("object"!=typeof n||Array.isArray(n))r="readingHistory"===t?{history:n}:{[t]:n};else {const e=n;r="conversations"===t&&void 0!==e.conversations?n:"readingHistory"!==t||void 0===e.history&&void 0===e.lastCleanupRun?"readingHistory"===t?{history:n}:{[t]:n}:n;}else r="prompts"===t&&Array.isArray(n)?{prompts:n}:"settings"!==t||n.settings?{[t]:n}:{settings:n};e[t]=JSON.stringify({state:r,version:0});}else e[t]="object"==typeof n?JSON.stringify(n):n;}),await m(e),await(async()=>{try{"extension"===qi.type&&"undefined"!=typeof chrome&&(await m({[ai]:Date.now()}),await chrome.runtime.sendMessage({type:xp}));}catch{}})(),Li(se("importSuccess")),setTimeout(()=>window.location.reload(),1e3);}catch(e){console.error("[Backup] import storage write failed:",e),Li(`${se("importError")}${bk(e)}`);}}});}catch(n){console.error("[Backup] import parse failed:",n),Li(`${se("importError")}${bk(n)}`);}var t;},y=async e=>{const t=c.url;if(!t)return Li(se("webdavConfigIncomplete")),false;if(!qi.hasCapability("permissions"))return await e(),true;try{const n=new URL(t).origin+"/*";return (await chrome.runtime.sendMessage({type:bp,origin:n})).hasPermission?(await e(),!0):(p({show:!0,onConfirm:async()=>{p(e=>({...e,show:!1}));try{const t=await chrome.runtime.sendMessage({type:vp,permType:"allUrls"});if(!t.success)return void Li(t.error||se("permissionRequired"));const n=await(async e=>{const t=Date.now()+6e4;for(;Date.now()setTimeout(e,1e3));}return !1})("");if(!n)return void Li(se("permissionRequired"));await e();}catch(t){console.warn("WebDAV permission request failed:",t),Li(se("permissionRequired"));}}}),!1)}catch(n){return console.warn("Perm check logic skipped:",n),await e(),true}},v=(()=>{const e=t.webdav??Jo.webdav,n=e.provider??(e.url?sk(e.url):"custom");return c.url!==e.url||c.username!==e.username||c.password!==e.password||c.remoteDir!==e.remoteDir||c.provider!==n})(); return Le("div",{className:"settings-content",children:[ Ie(jx,{title:se("navBackup"),Icon:pt}),u.show&&Ie(Lw,{title:u.title,message:u.message,danger:u.danger,onConfirm:u.onConfirm,onCancel:()=>h(e=>({...e,show:false}))}),g.show&&Ie(Lw,{title:se("permissionRequired"),message:se("webdavPermissionDesc"),onConfirm:g.onConfirm,onCancel:()=>p(e=>({...e,show:false}))}),o&&Ie(yk,{onClose:()=>i(false),onRestore:()=>window.location.reload()}), Le("div",{className:"backup-grid",style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(400px, 1fr))",gap:"20px",marginBottom:"24px"},children:[ Ie(Ox,{title:se("exportData"),description:se("exportDataDesc"),children:Le("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Le("div",{children:[ Ie("div",{style:{fontWeight:500,fontSize:"14px"},children:se("fullBackup")}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:se("fullBackupDesc")})]}), Ie("button",{onClick:()=>f("full"),className:"settings-btn settings-btn-success",style:{padding:"6px 16px"},children:se("export")})]}), Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Le("div",{children:[ Ie("div",{style:{fontWeight:500,fontSize:"14px"},children:se("promptsBackup")}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:se("promptsBackupDesc")})]}), Ie("button",{onClick:()=>f("prompts"),className:"settings-btn settings-btn-primary",style:{padding:"6px 16px"},children:se("export")})]}), Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px",background:"var(--gh-bg-secondary)",borderRadius:"8px"},children:[ Le("div",{children:[ Ie("div",{style:{fontWeight:500,fontSize:"14px"},children:se("settingsBackup")}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:se("settingsBackupDesc")})]}), Ie("button",{onClick:()=>f("settings"),className:"settings-btn settings-btn-secondary",style:{padding:"6px 16px"},children:se("export")})]})]})}), Ie(Ox,{title:se("importData"),description:se("importDataDesc"),children:Le("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Ie("div",{style:{fontSize:"14px",fontWeight:500},children:se("selectFile")}), Le("button",{className:"settings-btn settings-btn-secondary",onClick:()=>a.current?.click(),style:{padding:"6px 12px"},children:[se("browse"), Ie("input",{ref:a,type:"file",accept:".json",style:{display:"none"},onChange:async e=>{const t=e.target.files?.[0];if(!t)return;const n=await t.text();l(n),a.current&&(a.current.value="");}})]})]}), Le("div",{style:{flex:1},children:[ Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)",marginBottom:"4px"},children:se("dataPreview")}), Ie("textarea",{className:"settings-input",value:s,onChange:e=>l(e.target.value),placeholder:se("pastePlaceholder"),style:{width:"100%",height:"120px",fontFamily:"monospace",fontSize:"12px",resize:"vertical"}})]}), Ie("button",{onClick:()=>{s.trim()?b(s):Li(se("selectFileOrPasteFirst"));},className:"settings-btn settings-btn-primary",style:{width:"100%",justifyContent:"center",padding:"8px"},disabled:!s.trim(),children:se("importBtn")})]})})]}), Le(Ox,{title:se("webdavConfig"),description:se("webdavConfigDesc"),children:[ Le("div",{style:{background:"var(--gh-bg-secondary, #f8f9fa)",border:"1px solid var(--gh-border, #e0e0e0)",borderRadius:"8px",padding:"12px",marginBottom:"20px",fontSize:"13px",color:"var(--gh-text-secondary)"},children:[ Le("div",{style:{fontWeight:600,marginBottom:"4px",display:"flex",alignItems:"center",gap:"6px",color:"var(--gh-text)"},children:[ Ie(ft,{size:14,color:"var(--gh-primary, #4285f4)"})," ",se("restoreTip")]}), Ie("div",{style:{lineHeight:1.5},children:se("restoreTipContent")})]}), Ie(Fx,{label:se("webdavProvider"),children:Ie("select",{className:"settings-input settings-select",value:c.provider||"custom",onChange:e=>{const t=e.target.value,n=ik.find(e=>e.id===t);d(e=>({...e,provider:t,...n?.urlTemplate?{url:n.urlTemplate}:{}}));},style:{width:"280px"},children:ik.map(e=>Ie("option",{value:e.id,children:se(e.labelKey)},e.id))})}),(()=>{const e=ik.find(e=>e.id===(c.provider||"custom"));return e?.hintKey?Le("div",{style:{background:"var(--gh-primary-light-bg, rgba(66, 133, 244, 0.05))",border:"1px solid var(--gh-primary-border, rgba(66, 133, 244, 0.2))",borderRadius:"8px",padding:"10px 12px",marginBottom:"4px",fontSize:"12px",color:"var(--gh-text-secondary)",display:"flex",alignItems:"flex-start",gap:"8px"},children:[ Ie(ft,{size:14,color:"var(--gh-primary, #4285f4)",style:{flexShrink:0,marginTop:"1px"}}), Le("div",{children:[se(e.hintKey),e.helpUrl&&Ie("a",{href:e.helpUrl,target:"_blank",rel:"noreferrer noopener",style:{marginLeft:"6px",color:"var(--gh-primary, #4285f4)",textDecoration:"underline"},children:se("learnMore")})]})]}):null})(), Ie(Fx,{label:se("webdavAddress"),children:(()=>{const e=ik.find(e=>e.id===(c.provider||"custom")); return Ie("input",{type:"text",className:"settings-input",placeholder:e?.urlPlaceholder||"https://dav.example.com/dav/",value:c.url,onChange:e=>d({...c,url:e.target.value}),style:{width:"280px"}})})()}), Ie(Fx,{label:se("username"),children:Ie("input",{type:"text",className:"settings-input",value:c.username,onChange:e=>d({...c,username:e.target.value}),style:{width:"280px"}})}), Ie(Fx,{label:se("password"),children:(()=>{const e=ik.find(e=>e.id===(c.provider||"custom")),t=se(e?.passwordPlaceholderKey?e.passwordPlaceholderKey:"webdavPasswordPlaceholder"); return Ie("input",{type:"password",className:"settings-input",placeholder:t,value:c.password,onChange:e=>d({...c,password:e.target.value}),style:{width:"280px"}})})()}), Ie(Fx,{label:se("defaultDir"),description:se("defaultDirHint"),children:Ie("input",{type:"text",className:"settings-input",placeholder:"ophel",value:c.remoteDir,onChange:e=>d({...c,remoteDir:e.target.value}),style:{width:"280px"}})}), Le("div",{style:{marginTop:"16px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:"8px"},children:[ Le("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Le("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{await y(async()=>{const e=uk();await e.setConfig(c,!1);(await e.testConnection()).success?Li(se("webdavConnectionSuccess")):Li(se("webdavConnectionFailed"));});},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ Ie(tn,{size:16})," ",se("webdavTestBtn")]}), Le("div",{style:{position:"relative"},children:[ Le("button",{className:"settings-btn "+(v?"settings-btn-primary":"settings-btn-secondary"),onClick:()=>{const e=t.webdav??Jo.webdav;n({webdav:{...e,...c}}),Li(se("saveSuccess"));},style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},children:[ Ie(en,{size:16})," ",se("saveConfig")]}),v&&Ie("span",{style:{position:"absolute",top:"-4px",right:"-4px",width:"8px",height:"8px",backgroundColor:"var(--gh-warning, #f59e0b)",borderRadius:"50%",boxShadow:"0 0 0 2px var(--gh-bg, #ffffff)"}})]})]}), Le("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[ Le("button",{className:"settings-btn settings-btn-secondary",style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await y(async()=>{const e=uk();await e.setConfig(c,!1),i(!0);});},children:[ Ie(nn,{size:16,color:"currentColor"})," ",se("restore")]}), Le("button",{className:"settings-btn "+(v?"settings-btn-secondary":"settings-btn-primary"),style:{display:"flex",alignItems:"center",gap:"6px",padding:"6px 16px"},onClick:async()=>{await y(async()=>{const e=uk();await e.setConfig(c,!1);(await e.upload()).success?Li(se("webdavUploadSuccess")):Li(se("webdavUploadFailed"));});},children:[ Ie(mt,{size:16,color:"currentColor"})," ",se("backupNow")]})]})]})]}), Ie(Ox,{title:se("dangerZone"),description:se("dangerZoneDesc"),className:"danger-zone-card",children:Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[ Le("div",{children:[ Ie("div",{style:{fontSize:"14px",fontWeight:500,color:"var(--gh-danger, #ef4444)"},children:se("clearAllData")}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:se("clearAllDataDesc")})]}), Ie("button",{className:"settings-btn settings-btn-danger",onClick:()=>{h({show:true,title:se("clearAllData"),message:se("clearAllDataConfirm"),danger:true,onConfirm:async()=>{h(e=>({...e,show:false}));try{if("extension"===qi.type&&"undefined"!=typeof chrome)try{await chrome.runtime.sendMessage({type:wp});}catch{}await Promise.all([new Promise((e,t)=>chrome.storage.local.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),new Promise((e,t)=>chrome.storage.sync.clear(()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e()))]),await new Promise((e,t)=>chrome.storage.local.set({[jo]:Date.now()},()=>chrome.runtime.lastError?t(chrome.runtime.lastError):e())),r(),Tv.getState().setPrompts(no()),dv.setState({folders:ro}),pv.setState({tags:[]}),ov.setState({conversations:{},lastUsedFolderId:"inbox"}),gk.setState({history:{},lastCleanupRun:0}),Li(se("clearSuccess")),setTimeout(()=>window.location.reload(),1500);}catch(e){Li(se("error")+": "+String(e));}}});},style:{padding:"8px 16px",fontSize:"13px"},children:se("clearAllData")})]})})]})},wk="ophel:usageMonitor",xk={version:2,records:{},events:[]},kk=(e,t=0)=>Number.isFinite(e)?Math.max(0,Math.floor(e)):t,Sk=e=>{const t=Date.now();return e?{count:kk(e.count),updatedAt:kk(e.updatedAt,t),resetAt:kk(e.resetAt,t)}:{count:0,updatedAt:t,resetAt:t}},Ck=e=>{if(!e||"object"!=typeof e)return null;const t=kk(e.ts,Date.now());return {id:"string"==typeof e.id&&e.id?e.id:`${t}-${Math.random().toString(36).slice(2,8)}`,ts:t,siteId:"string"==typeof e.siteId&&e.siteId?e.siteId:"_default",cid:"string"==typeof e.cid&&e.cid?e.cid:"default",sessionId:"string"==typeof e.sessionId?e.sessionId:"",countDelta:kk(e.countDelta,1)||1,requestTokens:kk(e.requestTokens),roundTripTokens:kk(e.roundTripTokens),loadedConversationTokens:kk(e.loadedConversationTokens),loadedOutputTokens:kk(e.loadedOutputTokens)}},Ak=e=>{const t=Date.now();return e.filter(e=>t-e.ts<=3456e7).sort((e,t)=>e.ts-t.ts).slice(-4e3)},Ek=e=>{if(!e||"object"!=typeof e)return {...xk};const t=Array.isArray(e.events)?e.events:[];return {version:2,records:e.records&&"object"==typeof e.records?e.records:{},events:Ak(t.map(e=>Ck(e)).filter(Boolean))}};async function Tk(){const e=await qi.storage.get(wk);return Ek(e)}async function Mk(e){await qi.storage.set(wk,Ek(e));}const _k=e=>{const t=new Date(e);return t.setMinutes(0,0,0),t},Ik=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t},Lk=e=>{const t=new Date(e);return t.setDate(1),t.setHours(0,0,0,0),t},Nk=e=>`${`${e.getHours()}`.padStart(2,"0")}:00`,Dk=e=>`${e.getMonth()+1}/${e.getDate()}`,qk=e=>`${e.getFullYear()}/${`${e.getMonth()+1}`.padStart(2,"0")}`,Rk=(e,t)=>{switch(t){case "requestTokens":return e.requestTokens;case "roundTripTokens":return e.roundTripTokens;case "loadedConversationTokens":return e.loadedConversationTokens;case "loadedOutputTokens":return e.loadedOutputTokens;default:return e.count}};function Pk(e){return qi.storage.watch(wk,(t,n)=>{e(Ek(t),Ek(n));})}const zk=({value:e,onChange:t,placeholder:n,className:r,style:i})=>{const[a,s]=z(e);o.useEffect(()=>{s(e);},[e]);const l=()=>{a!==e&&t(a);}; return Ie("input",{type:"text",className:r,value:a,onChange:e=>s(e.target.value),onBlur:l,onKeyDown:e=>{"Enter"===e.key&&(l(),e.target.blur());},placeholder:n,style:i})},Bk=({siteId:e})=>{const[t,n]=z("day"),[r,i]=z("requestTokens"),[a,s]=z("_default"===e?"all":e),[l,c]=z([]),[d,u]=z(true),[h,g]=z(null),p=o.useRef(null),m=o.useMemo(()=>[{id:"all",label:se("usageMonitorChartSiteAll")},{id:lo,label:"Gemini"},{id:ho,label:"Gemini Enterprise"},{id:co,label:"ChatGPT"},{id:so,label:"Claude"},{id:go,label:"Grok"},{id:po,label:"AI Studio"},{id:bo,label:"DeepSeek"},{id:mo,label:"Doubao"},{id:fo,label:"ima"},{id:uo,label:"ChatGLM"},{id:yo,label:"Kimi"},{id:vo,label:"Qianwen"},{id:wo,label:"Qwen Studio"},{id:ko,label:"Z.ai"}],[]),f=m.find(e=>e.id===a)?.label||se("usageMonitorChartSiteAll"),b=o.useCallback(async()=>{u(true);try{const e=await async function(e){return (await Tk()).events.filter(t=>!(e?.siteId&&"_default"!==e.siteId&&t.siteId!==e.siteId||e?.cid&&t.cid!==e.cid))}({siteId:"all"===a?void 0:a});c(function(e,t,n=new Date){const r="hour"===t?24:"day"===t?30:12,o=[],i=new Map;for(let a=r-1;a>=0;a--){const e=new Date(n);let r,s,l;"hour"===t?(e.setHours(e.getHours()-a),r=_k(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}-${r.getHours()}`,l=Nk(r)):"day"===t?(e.setDate(e.getDate()-a),r=Ik(e),s=`${r.getFullYear()}-${r.getMonth()}-${r.getDate()}`,l=Dk(r)):(e.setMonth(e.getMonth()-a),r=Lk(e),s=`${r.getFullYear()}-${r.getMonth()}`,l=qk(r));const c={key:s,label:l,startAt:r.getTime(),endAt:"hour"===t?r.getTime()+36e5:"day"===t?r.getTime()+864e5:new Date(r.getFullYear(),r.getMonth()+1,1).getTime(),count:0,requestTokens:0,roundTripTokens:0,loadedConversationTokens:0,loadedOutputTokens:0,maxLoadedConversationTokens:0,maxRequestTokens:0,maxRoundTripTokens:0,maxLoadedOutputTokens:0};o.push(c),i.set(s,c);}return e.forEach(e=>{const n=new Date(e.ts),r="hour"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}-${n.getHours()}`:"day"===t?`${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`:`${n.getFullYear()}-${n.getMonth()}`,o=i.get(r);o&&(o.count+=e.countDelta,o.requestTokens+=e.requestTokens,o.roundTripTokens+=e.roundTripTokens,o.loadedConversationTokens+=e.loadedConversationTokens,o.loadedOutputTokens+=e.loadedOutputTokens,o.maxLoadedConversationTokens=Math.max(o.maxLoadedConversationTokens,e.loadedConversationTokens),o.maxRequestTokens=Math.max(o.maxRequestTokens,e.requestTokens),o.maxRoundTripTokens=Math.max(o.maxRoundTripTokens,e.roundTripTokens),o.maxLoadedOutputTokens=Math.max(o.maxLoadedOutputTokens,e.loadedOutputTokens));}),o}(e,t));}finally{u(false);}},[t,a]);_(()=>{b();},[b]),_(()=>{const e=Pk(()=>{b();});return ()=>e()},[b]),_(()=>{if(!p.current)return;const e=p.current,t=()=>{e.scrollLeft=e.scrollWidth;};t();const n=window.requestAnimationFrame(t);return ()=>window.cancelAnimationFrame(n)},[t,l.length]);const y=l.map(e=>Rk(e,r)),v=Math.max(1,...y),w=y[y.length-1]??0,x=se("requestTokens"===r?"usageMonitorChartMetricRequest":"roundTripTokens"===r?"usageMonitorChartMetricRoundTrip":"loadedConversationTokens"===r?"usageMonitorChartMetricConversation":"loadedOutputTokens"===r?"usageMonitorChartMetricOutput":"usageMonitorChartMetricCount"),k="month"===t?72:"hour"===t?48:44,S=l.length>1?Math.max(640,40+(l.length-1)*k+48):640,C=16,A=12,E=18,T=S-E-A,M=220-C-32,I=l.length>1?T/(l.length-1):T,L="month"===t?1:"hour"===t?2:Math.max(2,Math.ceil(l.length/10)),N=l.map((e,t)=>{const n=E+I*t,o=Rk(e,r);return {x:n,y:C+M-o/v*M,value:o,label:e.label}}),D=N.length>0?N.map((e,t)=>`${0===t?"M":"L"} ${e.x.toFixed(2)} ${e.y.toFixed(2)}`).join(" "):"",q=N.length>0?`${D} L ${N[N.length-1].x.toFixed(2)} ${(C+M).toFixed(2)} L ${N[0].x.toFixed(2)} ${(C+M).toFixed(2)} Z`:"",R=null!==h&&h>=0&&h=0&&h0&&h-1U?Math.min(j-U-8,Math.max(8,P.x-H-110)):8,G=P&&P.y>110?Math.max(8,P.y-94):8,Q="var(--gh-border, #e5e7eb)",V="var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",K="var(--gh-primary, #4285f4)",Z="var(--gh-border-active, #6366f1)",Y="var(--gh-text-secondary, #6b7280)",J="var(--gh-text, #374151)",X="var(--gh-card-bg, #ffffff)",ee="var(--gh-border, #e5e7eb)",te="var(--gh-border-active, #6366f1)",ne="var(--gh-shadow-sm, 0 1px 3px rgba(0,0,0,0.1))"; return Le("div",{style:{marginTop:"14px",padding:"14px",borderRadius:"12px",border:`1px solid ${ee}`,background:"var(--gh-bg-secondary, #f9fafb)"},children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",gap:"12px",flexWrap:"wrap"},children:[ Le("div",{children:[ Ie("div",{style:{fontSize:"14px",fontWeight:600,color:"var(--gh-text, #374151)"},children:se("usageMonitorChartTitle")}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)",marginTop:"4px"},children:se("usageMonitorChartDesc")}), Le("div",{style:{marginTop:"8px",display:"inline-flex",alignItems:"center",gap:"8px",flexWrap:"wrap"},children:[ Ie("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:se("usageMonitorChartSiteLabel")}), Ie("select",{className:"settings-select",value:a,onChange:e=>s(e.target.value),style:{minWidth:"170px"},children:m.map(e=>Ie("option",{value:e.id,children:e.label},e.id))})]})]}), Le("div",{style:{display:"flex",gap:"8px",flexWrap:"wrap",alignItems:"flex-start"},children:[ Ie("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["hour",se("usageMonitorChartHour")],["day",se("usageMonitorChartDay")],["month",se("usageMonitorChartMonth")]].map(([e,r])=>Ie(Dw,{size:"sm",variant:t===e?"primary":"secondary",onClick:()=>n(e),children:r},e))}), Ie("div",{style:{display:"flex",gap:"6px",flexWrap:"wrap"},children:[["count",se("usageMonitorChartMetricCount")],["requestTokens",se("usageMonitorChartMetricRequest")],["roundTripTokens",se("usageMonitorChartMetricRoundTrip")],["loadedConversationTokens",se("usageMonitorChartMetricConversation")],["loadedOutputTokens",se("usageMonitorChartMetricOutput")]].map(([e,t])=>Ie(Dw,{size:"sm",variant:r===e?"primary":"secondary",onClick:()=>i(e),children:t},e))})]})]}), Le("div",{style:{display:"flex",gap:"18px",marginTop:"12px",marginBottom:"8px",flexWrap:"wrap"},children:[ Le("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Le("span",{children:[x,": "]}), Ie("strong",{style:{color:"var(--gh-text, #374151)"},children:w})]}), Le("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Le("span",{children:[se("usageMonitorChartCurrentSite"),": "]}), Ie("strong",{style:{color:"var(--gh-text, #374151)"},children:f})]}), Le("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:[ Ie("span",{children:"MAX: "}), Ie("strong",{style:{color:"var(--gh-text, #374151)"},children:v})]}), Ie("div",{style:{fontSize:"12px",color:"var(--gh-text-secondary, #6b7280)"},children:Ie("span",{children:se("usageMonitorChartScrollHint")})})]}), Le("div",{style:{position:"relative",marginTop:"4px"},onMouseLeave:()=>g(null),children:[ Le("div",{ref:p,style:{position:"relative",borderRadius:"10px",overflowX:"auto",overflowY:"hidden",background:X,border:`1px solid ${ee}`,minHeight:"220px"},children:[ Ie("div",{style:{width:`${S}px`,minWidth:"100%",position:"relative"},children:Le("svg",{viewBox:`0 0 ${S} 220`,style:{width:"100%",height:"220px",display:"block"},children:[[0,.25,.5,.75,1].map(e=>{const t=C+M-M*e; return Ie("line",{x1:E,x2:S-A,y1:t,y2:t,stroke:Q,strokeWidth:"1",opacity:.6},e)}),q&&Ie("path",{d:q,fill:V}),D&&Ie("path",{d:D,fill:"none",stroke:K,strokeWidth:"2.5",strokeLinejoin:"round",strokeLinecap:"round"}),N.map(e=>Ie("circle",{cx:e.x,cy:e.y,r:"3",fill:K},`${e.label}-${e.x}`)),P&&Ie("line",{x1:P.x,x2:P.x,y1:C,y2:C+M,stroke:Z,strokeDasharray:"4 4",strokeWidth:"1",opacity:.65}),l.map((e,t)=>{const n=N[t],r=N[t-1],o=N[t+1],i=r?(r.x+n.x)/2:E,a=o?(n.x+o.x)/2:S-A; return Ie("rect",{x:i,y:C,width:Math.max(12,a-i),height:M,fill:"transparent",pointerEvents:"all",onMouseEnter:()=>g(t),onMouseMove:()=>g(t)},`${e.key}-hover`)}),l.map((e,t)=>{if(!(0===t||t===l.length-1||t%L===0))return null; return Ie("text",{x:E+I*t,y:210,textAnchor:"middle",fill:Y,fontSize:"11",children:e.label},e.key)})]})}),!d&&l.every(e=>0===Rk(e,r))&&Ie("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:Y,fontSize:"13px"},children:se("usageMonitorChartEmpty")})]}),R&&P&&Le("div",{style:{position:"absolute",left:`${W}px`,top:`${G}px`,width:"220px",borderRadius:"10px",padding:"10px 12px",background:X,color:J,border:`1px solid ${te}`,boxShadow:ne,pointerEvents:"none",zIndex:5},children:[ Ie("div",{style:{fontSize:"12px",fontWeight:700,marginBottom:"8px"},children:(e=>{const n=new Date(e.startAt),r=new Date(e.endAt-1);if("hour"===t){return `${`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`} ${`${n.getHours()}`.padStart(2,"0")}:00 - ${`${r.getHours()}`.padStart(2,"0")}:59`}return "day"===t?`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}/${`${n.getDate()}`.padStart(2,"0")}`:`${n.getFullYear()}/${`${n.getMonth()+1}`.padStart(2,"0")}`})(R)}),null!==$&&Le("div",{style:{fontSize:"11px",marginBottom:"8px",color:"var(--gh-text-secondary, #6b7280)"},children:[x,": ",O," · ",$>=0?"+":"",$," ",se("usageMonitorChartDelta")]}), Le("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"6px 10px",fontSize:"12px"},children:[ Ie("span",{style:{color:Y},children:se("usageMonitorChartMetricCount")}), Ie("strong",{children:R.count}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMetricRequest")}), Ie("strong",{children:R.requestTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMetricRoundTrip")}), Ie("strong",{children:R.roundTripTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMetricConversation")}), Ie("strong",{children:R.loadedConversationTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMetricOutput")}), Ie("strong",{children:R.loadedOutputTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMaxConversation")}), Ie("strong",{children:R.maxLoadedConversationTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMaxRequest")}), Ie("strong",{children:R.maxRequestTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMaxRoundTrip")}), Ie("strong",{children:R.maxRoundTripTokens}), Ie("span",{style:{color:Y},children:se("usageMonitorChartMaxOutput")}), Ie("strong",{children:R.maxLoadedOutputTokens})]})]})]})]})},Ok=({siteId:e,initialTab:t})=>{const n=[{id:kr,label:se("tabOutline")},{id:Sr,label:se("tabConversations")},{id:Cr,label:se("tabPrompts")},{id:Ar,label:se("tabSettingsTab")},{id:Er,label:se("reminderTab")},{id:Tr,label:se("navContent")},{id:Mr,label:se("readingHistoryTitle")}],[r,i]=z(t||n[0].id),[a,s]=z(false),l=o.useRef(null),{settings:c,updateDeepSetting:d,updateNestedSetting:u}=Ai(),h=A(()=>{l.current&&(l.current.onended=null,l.current.onerror=null);},[]),g=A(()=>{const e=l.current;e?(h(),e.pause(),e.currentTime=0,s(false)):s(false);},[h]);if(_(()=>{t&&i(t);},[t]),_(()=>()=>{g();},[g]),_(()=>{r!==Er&&g();},[r,g]),_(()=>{c?.tab?.showNotification&&c.tab.notificationSound||g();},[c?.tab?.notificationSound,c?.tab?.showNotification,g]),_(()=>{const e=l.current;if(!e||!a)return;const t=c?.tab?.notificationVolume??.5;e.volume=Math.max(.1,Math.min(1,t));},[a,c?.tab?.notificationVolume]),!c)return null;const p=se("enablePrerequisiteToast"),m=e=>Ni(p.replace("{setting}",e),2e3,{},1500,e),f=se("autoRenameTabLabel"),b=se("showNotificationLabel"),y=se("showStatusLabel"),v=se("privacyModeLabel"),w=se("readingHistoryPersistenceLabel"),x=se("formulaCopyLabel"),k="zip"===c.export?.packaging||"markdown"===c.export?.packaging?c.export.packaging:"markdown",S=[{value:"markdown",label:se("exportPackagingMarkdown")},{value:"zip",label:se("exportPackagingZip")}],C="mathml"===c.content?.formulaCopyFormat?"mathml":"latex",E=[{value:"latex",label:se("formulaCopyFormatLatex")},{value:"mathml",label:se("formulaCopyFormatMathml")}],T=Xr.length>1,M=e=>se("secondsValueLabel",{val:String(e)}),I=e=>`${e}x`,L=se("notificationSoundPreviewButtonLabel"),N=e=>{const t=e||c.tab?.notificationSoundPreset||Xr[0].id,n=qi.getNotificationSoundUrl(t);if(!n)return void Li(se("notificationSoundPreviewFailed"),2e3);g();let r=l.current;r||(r=new Audio,l.current=r);const o=c.tab?.notificationVolume??.5;r.volume=Math.max(.1,Math.min(1,o)),r.src=n,r.currentTime=0,r.onended=()=>{h(),s(false);},r.onerror=()=>{h(),s(false),Li(se("notificationSoundPreviewFailed"),2e3);},s(true),r.play().catch(()=>{h(),s(false),Li(se("notificationSoundPreviewFailed"),2e3);});},D=Le(Ox,{title:se("notificationSettings"),children:[ Ie($x,{label:se("showNotificationLabel"),description:se("showNotificationDesc"),settingId:"tab-show-notification",checked:c.tab?.showNotification??false,onChange:async()=>{const e=c.tab?.showNotification;if(e)u("tab","showNotification",false);else {if(!qi.hasCapability("permissions"))return void u("tab","showNotification",true);if(void 0!==chrome.permissions){await chrome.permissions.request({permissions:["notifications"]})&&u("tab","showNotification",true);}else {const e=await kp({type:yp,permissions:["notifications"]});e.success&&e.hasPermission?u("tab","showNotification",true):(await kp({type:vp,permType:"notifications"}),Li(se("permissionRequestToast"),3e3));}}}}), Ie($x,{label:se("notificationSoundLabel"),description:se("notificationSoundDesc"),settingId:"tab-notification-sound",checked:c.tab?.notificationSound??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notificationSound",!c.tab?.notificationSound)}),T&&Ie(Fx,{label:se("notificationSoundPresetLabel"),settingId:"tab-notification-sound-preset",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("select",{className:"settings-select",value:c.tab?.notificationSoundPreset||Xr[0].id,onChange:e=>{const t=e.target.value;u("tab","notificationSoundPreset",t),N(t);},disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{flex:1},children:Xr.map(e=>Ie("option",{value:e.id,children:se(e.labelKey)},e.id))}), Ie(Dw,{type:"button",variant:a?"primary":"secondary",size:"sm",onClick:()=>N(),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{minWidth:"56px",flexShrink:0},children:L})]})}), Ie(Fx,{label:se("notificationVolumeLabel"),settingId:"tab-notification-volume",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("input",{type:"range",min:"0.1",max:"1.0",step:"0.1",value:c.tab?.notificationVolume||.5,onChange:e=>u("tab","notificationVolume",parseFloat(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,style:{width:"100px"}}), Le("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(c.tab?.notificationVolume||.5)),"%"]})]})}), Ie(Fx,{label:se("notificationRepeatCountLabel"),settingId:"tab-notification-repeat-count",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Ie("select",{className:"settings-select",value:c.tab?.notificationRepeatCount??1,onChange:e=>u("tab","notificationRepeatCount",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5].map(e=>Ie("option",{value:e,children:I(e)},e))})}), Ie(Fx,{label:se("notificationRepeatIntervalLabel"),settingId:"tab-notification-repeat-interval",disabled:!c.tab?.showNotification||!c.tab?.notificationSound,onDisabledClick:()=>m(b),children:Ie("select",{className:"settings-select",value:c.tab?.notificationRepeatInterval??3,onChange:e=>u("tab","notificationRepeatInterval",parseInt(e.target.value)),disabled:!c.tab?.showNotification||!c.tab?.notificationSound,children:[1,2,3,5,10].map(e=>Ie("option",{value:e,children:M(e)},e))})}), Ie($x,{label:se("notifyWhenFocusedLabel"),description:se("notifyWhenFocusedDesc"),settingId:"tab-notify-when-focused",checked:c.tab?.notifyWhenFocused??false,disabled:!c.tab?.showNotification,onDisabledClick:()=>m(b),onChange:()=>u("tab","notifyWhenFocused",!c.tab?.notifyWhenFocused)}), Ie($x,{label:se("autoFocusLabel"),description:se("autoFocusDesc"),settingId:"tab-auto-focus",checked:c.tab?.autoFocus??false,onChange:()=>u("tab","autoFocus",!c.tab?.autoFocus)})]}),q=Le(Ox,{title:se("usageMonitorSettingsTitle"),description:se("usageMonitorSettingsDesc"),children:[ Le("div",{style:{marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border, #e5e7eb)",background:"var(--gh-bg-secondary, #f9fafb)",color:"var(--gh-text-secondary, #6b7280)",fontSize:"12px",lineHeight:1.6},children:[ Ie("div",{children:se("usageMonitorExplainLocalOnly")}), Ie("div",{children:se("usageMonitorExplainNoBackend")}), Ie("div",{children:se("usageMonitorExplainReset")})]}), Ie($x,{label:se("usageMonitorEnabledLabel"),description:se("usageMonitorEnabledDesc"),settingId:"usage-monitor-enabled",checked:c.usageMonitor?.enabled??false,onChange:()=>u("usageMonitor","enabled",!c.usageMonitor?.enabled)}), Ie("div",{style:{marginTop:"-2px",marginBottom:"12px",padding:"10px 12px",borderRadius:"10px",border:"1px solid var(--gh-border-active, #6366f1)",background:"var(--gh-user-query-bg, rgba(66, 133, 244, 0.08))",color:"var(--gh-text, #374151)",fontSize:"12px",lineHeight:1.55},children:se("usageMonitorExplainRender")}), Ie(Fx,{label:se("usageMonitorDailyLimitLabel"),description:se("usageMonitorDailyLimitDesc"),settingId:"usage-monitor-daily-limit",disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(se("usageMonitorEnabledLabel")),children:Ie(qw,{value:c.usageMonitor?.dailyLimit??100,onChange:e=>u("usageMonitor","dailyLimit",e),min:1,max:9999,defaultValue:100,disabled:!c.usageMonitor?.enabled,style:{width:"96px"}})}), Ie($x,{label:se("usageMonitorAutoResetLabel"),description:se("usageMonitorAutoResetDesc"),settingId:"usage-monitor-auto-reset",checked:c.usageMonitor?.autoResetEnabled??false,disabled:!c.usageMonitor?.enabled,onDisabledClick:()=>m(se("usageMonitorEnabledLabel")),onChange:()=>u("usageMonitor","autoResetEnabled",!c.usageMonitor?.autoResetEnabled)}), Ie(Bk,{siteId:e})]}); return Le("div",{children:[ Ie(jx,{title:se("navFeatures"),Icon:at}), Ie("p",{className:"settings-page-desc",children:se("featuresPageDesc")}), Ie(Ux,{tabs:n,activeTab:r,onTabChange:i}),r===Ar&&Le(_e,{children:[ Le(Ox,{title:se("tabBehaviorTitle"),children:[ Ie($x,{label:se("openNewTabLabel"),description:se("openNewTabDesc"),settingId:"tab-open-new",checked:c.tab?.openInNewTab??true,onChange:()=>u("tab","openInNewTab",!c.tab?.openInNewTab)}), Ie($x,{label:se("autoRenameTabLabel"),description:se("autoRenameTabDesc"),settingId:"tab-auto-rename",checked:c.tab?.autoRename??false,onChange:()=>u("tab","autoRename",!c.tab?.autoRename)}), Ie(Fx,{label:se("renameIntervalLabel"),settingId:"tab-rename-interval",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:Ie("select",{className:"settings-select",value:c.tab?.renameInterval||3,onChange:e=>u("tab","renameInterval",parseInt(e.target.value)),disabled:!c.tab?.autoRename,children:[1,3,5,10,30,60].map(e=>Ie("option",{value:e,children:M(e)},e))})}), Ie(Fx,{label:se("titleFormatLabel"),description:se("titleFormatDesc"),settingId:"tab-title-format",disabled:!c.tab?.autoRename,onDisabledClick:()=>m(f),children:Ie(Ow,{value:c.tab?.titleFormat??"{status}{title}",onChange:e=>u("tab","titleFormat",e),placeholders:["{status}","{title}","{model}"],placeholder:"{status}{title}",disabled:!c.tab?.autoRename,style:{width:"260px"}})}), Ie($x,{label:se("showStatusLabel"),description:se("showStatusDesc"),settingId:"tab-show-status",checked:c.tab?.showStatus??true,onChange:()=>u("tab","showStatus",!c.tab?.showStatus)}), Ie($x,{label:se("hideStatusWhenReadLabel"),description:se("hideStatusWhenReadDesc"),settingId:"tab-hide-status-when-read",disabled:!c.tab?.showStatus,onDisabledClick:()=>m(y),checked:c.tab?.hideStatusWhenRead??false,onChange:()=>u("tab","hideStatusWhenRead",!c.tab?.hideStatusWhenRead)})]}), Le(Ox,{title:se("privacyModeTitle"),children:[ Ie($x,{label:se("privacyModeLabel"),description:se("privacyModeDesc"),settingId:"tab-privacy-mode",checked:c.tab?.privacyMode??false,onChange:()=>u("tab","privacyMode",!c.tab?.privacyMode)}), Ie(Fx,{label:se("privacyTitleLabel"),settingId:"tab-privacy-title",disabled:!c.tab?.privacyMode,onDisabledClick:()=>m(v),children:Ie("input",{type:"text",className:"settings-input",value:c.tab?.privacyTitle||"Google",onChange:e=>u("tab","privacyTitle",e.target.value),placeholder:"Google",disabled:!c.tab?.privacyMode,style:{width:"180px"}})})]})]}),r===Er&&Le(_e,{children:[D,q]}),r===kr&&Le(_e,{children:[ Le(Ox,{title:se("outlineSettings"),description:se("outlineSettingsDesc"),children:[ Ie($x,{label:se("outlineAutoUpdateLabel"),description:se("outlineAutoUpdateDesc"),settingId:"outline-auto-update",checked:c.features?.outline?.autoUpdate??true,onChange:()=>d("features","outline","autoUpdate",!c.features?.outline?.autoUpdate)}), Ie(Fx,{label:se("outlineUpdateIntervalLabel"),description:se("outlineUpdateIntervalDesc"),settingId:"outline-update-interval",children:Ie(qw,{value:c.features?.outline?.updateInterval??2,onChange:e=>d("features","outline","updateInterval",e),min:1,max:60,defaultValue:2,style:{width:"80px"}})}), Ie(Fx,{label:se("outlineFollowModeLabel"),description:"current"===c.features?.outline?.followMode?se("outlineFollowCurrentDesc"):"latest"===c.features?.outline?.followMode?se("outlineFollowLatestDesc"):se("outlineFollowManualDesc"),settingId:"outline-follow-mode",children:Le("select",{className:"settings-select",value:c.features?.outline?.followMode||"current",onChange:e=>d("features","outline","followMode",e.target.value),children:[ Ie("option",{value:"current",children:se("outlineFollowCurrent")}), Ie("option",{value:"latest",children:se("outlineFollowLatest")}), Ie("option",{value:"manual",children:se("outlineFollowManual")})]})}), Ie($x,{label:se("outlineShowWordCountLabel"),description:se("outlineShowWordCountDesc"),settingId:"outline-show-word-count",checked:c.features?.outline?.showWordCount??false,onChange:()=>d("features","outline","showWordCount",!c.features?.outline?.showWordCount)})]}), Le(Ox,{title:se("bookmarkSettings"),description:se("bookmarkSettingsDesc"),children:[ Ie(Fx,{label:se("inlineBookmarkModeLabel"),description:se("inlineBookmarkModeDesc"),settingId:"outline-inline-bookmark-mode",children:Le("select",{className:"settings-select",value:c.features?.outline?.inlineBookmarkMode||"always",onChange:e=>d("features","outline","inlineBookmarkMode",e.target.value),children:[ Ie("option",{value:"always",children:se("inlineBookmarkModeAlways")}), Ie("option",{value:"hover",children:se("inlineBookmarkModeHover")}), Ie("option",{value:"hidden",children:se("inlineBookmarkModeHidden")})]})}), Ie(Fx,{label:se("panelBookmarkModeLabel"),description:se("panelBookmarkModeDesc"),settingId:"outline-panel-bookmark-mode",children:Le("select",{className:"settings-select",value:c.features?.outline?.panelBookmarkMode||"always",onChange:e=>d("features","outline","panelBookmarkMode",e.target.value),children:[ Ie("option",{value:"always",children:se("inlineBookmarkModeAlways")}), Ie("option",{value:"hover",children:se("inlineBookmarkModeHover")}), Ie("option",{value:"hidden",children:se("inlineBookmarkModeHidden")})]})})]}), Ie(Ox,{title:se("scrollSettings"),children:Ie($x,{label:se("preventAutoScrollLabel"),description:se("preventAutoScrollDesc"),settingId:"outline-prevent-auto-scroll",checked:c.panel?.preventAutoScroll??false,onChange:()=>u("panel","preventAutoScroll",!c.panel?.preventAutoScroll)})})]}),r===Sr&&Le(_e,{children:[ Le(Ox,{title:se("conversationsSettingsTitle"),description:se("conversationsSettingsDesc"),children:[ Ie($x,{label:se("folderRainbowLabel"),description:se("folderRainbowDesc"),settingId:"conversation-folder-rainbow",checked:c.features?.conversations?.folderRainbow??true,onChange:()=>d("features","conversations","folderRainbow",!c.features?.conversations?.folderRainbow)}), Ie($x,{label:se("conversationsSyncUnpinLabel"),description:se("conversationsSyncUnpinDesc"),settingId:"conversation-sync-unpin",checked:c.features?.conversations?.syncUnpin??false,onChange:()=>d("features","conversations","syncUnpin",!c.features?.conversations?.syncUnpin)}), Ie($x,{label:se("conversationsSyncDeleteLabel"),description:se("conversationsSyncDeleteDesc"),settingId:"conversation-sync-delete",checked:c.features?.conversations?.syncDelete??true,onChange:()=>d("features","conversations","syncDelete",!(c.features?.conversations?.syncDelete??1))})]}), Le(Ox,{title:se("exportSettings"),children:[ Ie(Fx,{label:se("exportPackagingLabel"),description:se("exportPackagingDesc"),settingId:"export-packaging",children:Ie(zw,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:S,value:k,ariaLabel:se("exportPackagingLabel"),onChange:e=>u("export","packaging",e)})}), Ie($x,{label:se("exportFilenameTimestamp"),description:se("exportFilenameTimestampDesc"),settingId:"export-filename-timestamp",checked:c.export?.exportFilenameTimestamp??false,onChange:()=>u("export","exportFilenameTimestamp",!c.export?.exportFilenameTimestamp)}), Ie($x,{label:se("exportIncludeThoughtsLabel"),description:se("exportIncludeThoughtsDesc"),settingId:"export-include-thoughts",checked:c.export?.includeThoughts??true,onChange:()=>u("export","includeThoughts",!(c.export?.includeThoughts??1))}), Ie(Fx,{label:se("exportCustomUserName"),description:se("exportCustomUserNameDesc"),settingId:"export-custom-user-name",children:Ie(zk,{className:"settings-input",value:c.export?.customUserName||"",onChange:e=>u("export","customUserName",e),placeholder:"User",style:{width:"180px"}})}), Ie(Fx,{label:se("exportCustomModelName"),description:se("exportCustomModelNameDesc"),settingId:"export-custom-model-name",children:Ie(zk,{className:"settings-input",value:c.export?.customModelName||"",onChange:e=>u("export","customModelName",e),placeholder:"Site Name",style:{width:"180px"}})})]})]}),r===Cr&&Le(Ox,{title:se("promptSettingsTitle"),description:se("promptSettingsDesc"),children:[ Ie($x,{label:se("promptDoubleClickSendLabel"),description:se("promptDoubleClickSendDesc"),settingId:"prompt-double-click-send",checked:c.features?.prompts?.doubleClickToSend??false,onChange:()=>d("features","prompts","doubleClickToSend",!c.features?.prompts?.doubleClickToSend)}), Ie(Fx,{label:se("promptSubmitShortcutLabel"),description:se("promptSubmitShortcutDesc"),settingId:"shortcuts-prompt-submit-shortcut",children:Le("select",{className:"settings-select",value:c.features?.prompts?.submitShortcut??"enter",onChange:e=>d("features","prompts","submitShortcut",e.target.value),children:[ Ie("option",{value:"enter",children:se("promptSubmitShortcutEnter")}), Ie("option",{value:"ctrlEnter",children:se("promptSubmitShortcutCtrlEnter")})]})}), Ie($x,{label:se("queueSettingLabel"),description:se("queueSettingDesc"),settingId:"prompt-queue",checked:c.features?.prompts?.promptQueue??false,onChange:()=>d("features","prompts","promptQueue",!c.features?.prompts?.promptQueue)})]}),r===Mr&&Le(Ox,{title:se("readingHistoryTitle"),description:se("readingHistoryDesc"),children:[ Ie($x,{label:se("readingHistoryPersistenceLabel"),description:se("readingHistoryPersistenceDesc"),settingId:"reading-history-persistence",checked:c.readingHistory?.persistence??true,onChange:()=>u("readingHistory","persistence",!c.readingHistory?.persistence)}), Ie($x,{label:se("readingHistoryAutoRestoreLabel"),description:se("readingHistoryAutoRestoreDesc"),settingId:"reading-history-auto-restore",checked:c.readingHistory?.autoRestore??true,disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(w),onChange:()=>u("readingHistory","autoRestore",!c.readingHistory?.autoRestore)}), Ie(Fx,{label:se("readingHistoryCleanup"),settingId:"reading-history-cleanup-days",disabled:!c.readingHistory?.persistence,onDisabledClick:()=>m(w),children:Le("select",{className:"settings-select",value:c.readingHistory?.cleanupDays||30,onChange:e=>u("readingHistory","cleanupDays",parseInt(e.target.value)),disabled:!c.readingHistory?.persistence,children:[ Le("option",{value:1,children:["1 ",se("day")]}), Le("option",{value:3,children:["3 ",se("days")]}), Le("option",{value:7,children:["7 ",se("days")]}), Le("option",{value:30,children:["30 ",se("days")]}), Le("option",{value:90,children:["90 ",se("days")]}), Ie("option",{value:-1,children:se("forever")})]})})]}),r===Tr&&Le(Ox,{title:se("interactionEnhance"),description:se("interactionEnhanceDesc"),children:[ Ie($x,{label:se("assistantMermaidLabel"),description:se("assistantMermaidDesc"),settingId:"content-assistant-mermaid",checked:c.content?.assistantMermaid??true,onChange:()=>u("content","assistantMermaid",!(c.content?.assistantMermaid??1))}), Ie($x,{label:se("userQueryMarkdownLabel"),description:se("userQueryMarkdownDesc"),settingId:"content-user-query-markdown",checked:c.content?.userQueryMarkdown??true,onChange:()=>u("content","userQueryMarkdown",!(c.content?.userQueryMarkdown??1))}), Ie($x,{label:se("formulaCopyLabel"),description:se("formulaCopyDesc"),settingId:"content-formula-copy",checked:c.content?.formulaCopy??true,onChange:()=>u("content","formulaCopy",!c.content?.formulaCopy)}), Ie(Fx,{label:se("formulaCopyFormatLabel"),description:se("formulaCopyFormatDesc"),settingId:"content-formula-copy-format",disabled:!c.content?.formulaCopy,onDisabledClick:()=>m(x),children:Ie(zw,{className:"settings-select-dropdown",buttonClassName:"settings-select",options:E,value:C,ariaLabel:se("formulaCopyFormatLabel"),disabled:!c.content?.formulaCopy,onChange:e=>u("content","formulaCopyFormat",e)})}), Ie($x,{label:se("formulaDelimiterLabel"),description:se("formulaDelimiterDesc"),settingId:"content-formula-delimiter",checked:c.content?.formulaDelimiter??true,disabled:!c.content?.formulaCopy||"latex"!==C,onDisabledClick:()=>{c.content?.formulaCopy?Ni(se("formulaDelimiterLatexOnlyToast"),2e3,{},1500,"formula-delimiter-latex-only"):m(x);},onChange:()=>u("content","formulaDelimiter",!c.content?.formulaDelimiter)}), Ie($x,{label:se("tableCopyLabel"),description:se("tableCopyDesc"),settingId:"content-table-copy",checked:c.content?.tableCopy??true,onChange:()=>u("content","tableCopy",!c.content?.tableCopy)})]})]})},Fk=(e,t)=>{const n=se(e);return n===e?t:n},$k=({siteId:e})=>{const{settings:t,updateNestedSetting:n}=Ai();if(!t)return null;const r=t.globalSearch?.promptEnterBehavior||"smart",o=t.globalSearch?.doubleShift??Jo.globalSearch.doubleShift,i=t.globalSearch?.enableFuzzySearch??false,a=lr(),s=t.shortcuts?.keybindings?.[Un],l=null===s?null:s||er[Un],c=l?sr(l,a):"",d=[];o&&d.push(Fk("globalSearchTriggerDoubleShift","double-press Shift")),c&&d.push(c);const u=((e,t,n)=>{let r=Fk(e,t);return Object.keys(n).forEach(e=>{r=r.replace(new RegExp(`{${e}}`,"g"),n[e]);}),r})("globalSearchTriggerHint","Trigger: {shortcut}",{shortcut:d.join(" / ")||Fk("shortcutNotSet","Not set")}),h=`shortcut-binding-${Un}`; return Le("div",{children:[ Ie(jx,{title:Fk("navGlobalSearch","Global Search"),Icon:Wt}), Ie("p",{className:"settings-page-desc",children:`${Fk("globalSearchPageDesc","Configure Search Everywhere behavior and interaction details")} · ${u}`}), Le(Ox,{title:Fk("globalSearchMatchingSettingsTitle","Search Matching"),description:Fk("globalSearchMatchingSettingsDesc","Configure how Search Everywhere matches search results"),children:[ Ie(Fx,{label:Fk("globalSearchShortcutSettingLabel","全局搜索快捷键"),description:Fk("globalSearchShortcutSettingDesc","跳转到快捷键设置,自定义或禁用全局搜索快捷键。"),settingId:"global-search-shortcut-setting-link",children:Ie("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:yr,settingId:h}}));},children:Fk("globalSearchShortcutSettingAction","前往设置")})}), Ie($x,{label:Fk("doubleShiftToSearch","Double Shift to open Global Search"),description:Fk("doubleShiftToSearchDesc","Press Shift twice quickly to open Global Search"),checked:o,onChange:()=>n("globalSearch","doubleShift",!o),settingId:"global-search-double-shift"}), Ie($x,{label:Fk("globalSearchEnableFuzzySearchLabel","Enable fuzzy search"),description:Fk("globalSearchEnableFuzzySearchDesc","When enabled, Search Everywhere uses fuzzy matching for title, folder, tag, prompt content, and setting identifiers."),checked:i,onChange:()=>n("globalSearch","enableFuzzySearch",!i),settingId:"global-search-fuzzy-search"})]}), Ie(Ox,{title:Fk("globalSearchPromptSettingsTitle","Prompt Behavior"),description:Fk("globalSearchPromptSettingsDesc","Choose what happens when pressing Enter on a prompt result in Search Everywhere"),children:Ie(Fx,{label:Fk("globalSearchPromptEnterBehaviorLabel","Search Everywhere prompt Enter behavior"),description:Fk("globalSearchPromptEnterBehaviorDesc","Smart: insert directly when no variable, open variable dialog when needed; Locate only: switch to Prompts and locate the item."),settingId:"global-search-prompt-enter-behavior",children:Le("select",{className:"settings-select",value:r,onChange:e=>n("globalSearch","promptEnterBehavior",e.target.value),children:[ Ie("option",{value:"smart",children:Fk("globalSearchPromptEnterBehaviorSmart","Smart (Recommended)")}), Ie("option",{value:"locate",children:Fk("globalSearchPromptEnterBehaviorLocate","Locate Only")})]})})})]})},Uk=({iconNode:e,label:t,index:n,total:r,enabled:o=true,showToggle:i=false,onToggle:a,onDragStart:s,onDragOver:l,onDragEnd:c,onDrop:d,isDragging:u=false})=>Le("div",{className:"settings-sortable-item "+(u?"dragging":""),draggable:true,onDragStart:e=>s(e,n),onDragOver:e=>l(e,n),onDragEnd:c,onDrop:e=>d(e,n),style:{opacity:u?.4:1,cursor:"grab",border:u?"1px dashed var(--gh-primary)":void 0},children:[ Ie("div",{className:"settings-sortable-handle",style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"4px 8px 4px 0",cursor:"grab",color:"var(--gh-text-secondary, #9ca3af)"},children:Ie(bt,{size:16})}),e&&Ie("span",{className:"settings-sortable-item-icon",children:e}), Ie("span",{className:"settings-sortable-item-label",children:t}), Ie("div",{className:"settings-sortable-item-actions",children:i&&Ie(Mw,{checked:o,onChange:()=>a?.(),size:"sm"})})]}),jk=({siteId:e,initialTab:t})=>{const[n,r]=z(t||"panel"),{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l,updateDeepSetting:c}=Ai();_(()=>{t&&r(t);},[t]),se("enablePrerequisiteToast");const[d,u]=z(null),h=(e,t)=>({panel:{...o.panel,[e]:t}}),g=(e,t,n)=>{u({type:t,index:n}),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",`${t}:${n}`);},p=e=>{e.preventDefault(),e.dataTransfer.dropEffect="move";},m=(e,t)=>{if(e.preventDefault(),!d||"tab"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.features?.order||[]],[i]=r.splice(n,1);r.splice(t,0,i),l("features","order",r),u(null);},f=(e,t)=>{if(e.preventDefault(),!d||"button"!==d.type)return;const n=d.index;if(n===t)return;const r=[...o.quickButtons?.collapsed||[]],[i]=r.splice(n,1);r.splice(t,0,i),l("quickButtons","collapsed",r),u(null);},b=()=>{u(null);};if(!o)return null;const y=[{id:"panel",label:se("panelTab")},{id:"tabOrder",label:se("tabOrderTab")},{id:"shortcuts",label:se("shortcutsTab")},{id:"toolsMenu",label:se("toolboxMenu")}]; return Le("div",{children:[ Ie(jx,{title:se("navGeneral"),Icon:rt}), Ie("p",{className:"settings-page-desc",children:se("generalPageDesc")}), Ie(Ux,{tabs:y,activeTab:n,onTabChange:r}),"panel"===n&&Le(Ox,{title:se("panelSettings"),children:[ Ie(Fx,{label:se("panelModeLabel"),description:se("panelModeDesc"),settingId:"panel-mode",children:Ie("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[{value:"edge-snap",label:se("panelModeEdgeSnap"),Icon:Zt},{value:"floating",label:se("panelModeFloating"),Icon:Yt}].map((e,t)=>Le("button",{type:"button","aria-pressed":(o.panel?.panelMode??"edge-snap")===e.value,onClick:()=>l("panel","panelMode",e.value),style:{display:"inline-flex",alignItems:"center",gap:"5px",padding:"4px 12px",fontSize:"13px",border:"none",borderLeft:t>0?"1px solid var(--gh-border, #e5e7eb)":"none",cursor:"pointer",background:(o.panel?.panelMode??"edge-snap")===e.value?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:(o.panel?.panelMode??"edge-snap")===e.value?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:[ Ie(e.Icon,{size:14}),e.label]},e.value))})}), Ie(Fx,{label:se("defaultPositionLabel"),description:se("defaultPositionDesc"),settingId:"panel-default-position",children:Le("div",{style:{display:"inline-flex",borderRadius:"6px",overflow:"hidden",border:"1px solid var(--gh-border, #e5e7eb)"},children:[ Ie("button",{onClick:()=>l("panel","defaultPosition","left"),style:{padding:"4px 12px",fontSize:"13px",border:"none",cursor:"pointer",background:"left"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"left"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:se("defaultPositionLeft")}), Ie("button",{onClick:()=>l("panel","defaultPosition","right"),style:{padding:"4px 12px",fontSize:"13px",border:"none",borderLeft:"1px solid var(--gh-border, #e5e7eb)",cursor:"pointer",background:"right"===(o.panel?.defaultPosition||"right")?"var(--gh-primary, #4285f4)":"var(--gh-bg, #fff)",color:"right"===(o.panel?.defaultPosition||"right")?"#fff":"var(--gh-text-secondary, #6b7280)",transition:"all 0.2s"},children:se("defaultPositionRight")})]})}), Ie(Fx,{label:se("panelWidthLabel"),description:se("panelWidthDesc"),settingId:"panel-width",children:Ie(Pw,{value:Math.max(o.panel?.width??320,240),onChange:e=>{i(h("width",e));},onPreviewChange:e=>{a(h("width",e));},onCancelPreview:s,min:240,max:600,step:10,unit:"px",defaultValue:320,formatValue:e=>`${e}px`,ariaLabel:se("panelWidthLabel")})}), Ie(Fx,{label:se("panelHeightLabel"),description:se("panelHeightDesc"),settingId:"panel-height",children:Ie(Pw,{value:o.panel?.height??85,onChange:e=>{i(h("height",e));},onPreviewChange:e=>{a(h("height",e));},onCancelPreview:s,min:50,max:100,step:1,unit:"vh",defaultValue:85,formatValue:e=>`${e}vh`,ariaLabel:se("panelHeightLabel")})}),"edge-snap"===(o.panel?.panelMode??"edge-snap")&&Ie(Fx,{label:se("edgeSnapThresholdLabel"),description:se("edgeSnapThresholdDesc"),settingId:"panel-edge-snap-threshold",children:Ie(Pw,{value:o.panel?.edgeSnapThreshold??30,onChange:e=>{i(h("edgeSnapThreshold",e));},onPreviewChange:e=>{a(h("edgeSnapThreshold",e));},onCancelPreview:s,min:0,max:400,step:2,unit:"px",defaultValue:30,formatValue:e=>`${e}px`,ariaLabel:se("edgeSnapThresholdLabel")})}),"floating"===(o.panel?.panelMode??"edge-snap")&&Ie(Fx,{label:se("defaultEdgeDistanceLabel"),description:se("defaultEdgeDistanceDesc"),settingId:"panel-edge-distance",children:Ie(Pw,{value:o.panel?.defaultEdgeDistance??0,onChange:e=>{i(h("defaultEdgeDistance",e));},onPreviewChange:e=>{a(h("defaultEdgeDistance",e));},onCancelPreview:s,min:0,max:400,step:5,unit:"px",defaultValue:0,formatValue:e=>`${e}px`,ariaLabel:se("defaultEdgeDistanceLabel")})})]}),"tabOrder"===n&&Ie(Ox,{title:se("tabOrderSettings"),description:se("tabOrderDesc"),children:o.features?.order?.filter(e=>jr[e]).map((e,t)=>{const n=jr[e],r="prompts"===e?false!==o.features?.prompts?.enabled:"outline"===e?false!==o.features?.outline?.enabled:"conversations"!==e||false!==o.features?.conversations?.enabled; return Ie(Uk,{iconNode:n.IconComponent?Ie(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:se(n.label),index:t,total:o.features?.order.filter(e=>jr[e]).length,enabled:r,showToggle:true,onToggle:()=>{"prompts"===e?c("features","prompts","enabled",!r):"outline"===e?c("features","outline","enabled",!r):"conversations"===e&&c("features","conversations","enabled",!r);},onDragStart:e=>g(e,"tab",t),onDragOver:p,onDragEnd:b,onDrop:m,isDragging:"tab"===d?.type&&d?.index===t},e)})}),"shortcuts"===n&&Le(_e,{children:[ Le(Ox,{title:se("quickButtonsBehaviorTitle"),description:se("quickButtonsBehaviorDesc"),children:[ Ie($x,{label:se("quickButtonsHideWhenPanelOpenLabel"),description:se("quickButtonsHideWhenPanelOpenDesc"),settingId:"quick-buttons-hide-when-panel-open",checked:o.quickButtons?.hideWhenPanelOpen??false,onChange:()=>l("quickButtons","hideWhenPanelOpen",!o.quickButtons?.hideWhenPanelOpen)}), Ie(Fx,{label:se("quickButtonsProximityRadiusLabel"),description:se("quickButtonsProximityRadiusDesc"),settingId:"quick-buttons-proximity-radius",children:Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("input",{type:"range",min:"0",max:"300",step:"10",value:o.quickButtons?.proximityRadius??150,onChange:e=>l("quickButtons","proximityRadius",parseInt(e.target.value,10)),style:{width:"120px"}}), Le("span",{style:{fontSize:"12px",minWidth:"36px"},children:[o.quickButtons?.proximityRadius??150,"px"]})]})}), Ie(Fx,{label:se("quickButtonsOpacityLabel"),description:se("quickButtonsOpacityDesc"),settingId:"quick-buttons-opacity",children:Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("input",{type:"range",min:"0.4",max:"1",step:"0.05",value:o.quickButtons?.opacity??1,onChange:e=>l("quickButtons","opacity",parseFloat(e.target.value)),style:{width:"120px"}}), Le("span",{style:{fontSize:"12px",minWidth:"36px"},children:[Math.round(100*(o.quickButtons?.opacity??1)),"%"]})]})})]}), Ie(Ox,{title:se("collapsedButtonsOrderTitle"),description:se("collapsedButtonsOrderDesc"),children:o.quickButtons?.collapsed?.map((e,t)=>{if("manualAnchor"===e.id)return null;const n=Hr[e.id];return n?Ie(Uk,{iconNode:n.IconComponent?Ie(n.IconComponent,{size:18,color:"currentColor"}):n.icon,label:se(n.labelKey),index:t,total:o.quickButtons.collapsed.length,enabled:e.enabled,showToggle:n.canToggle,onToggle:()=>(e=>{const t=[...o.quickButtons?.collapsed||[]];t[e]={...t[e],enabled:!t[e].enabled},l("quickButtons","collapsed",t);})(t),onDragStart:e=>g(e,"button",t),onDragOver:p,onDragEnd:b,onDrop:f,isDragging:"button"===d?.type&&d?.index===t},e.id):null})})]}),"toolsMenu"===n&&Ie(Ox,{title:se("toolboxMenuTitle"),description:se("toolboxMenuDesc"),children:qo.filter(e=>e.id!==Do).map(e=>{const t=(o.quickButtons?.toolsMenu??qo.map(e=>e.id)).includes(e.id); return Ie($x,{label:se(e.labelKey),settingId:`tools-menu-${e.id}`,checked:t,onChange:()=>{const n=o.quickButtons?.toolsMenu??qo.map(e=>e.id),r=t?n.filter(t=>t!==e.id):[...n,e.id];l("quickButtons","toolsMenu",r);}},e.id)})})]})},Hk=[{id:"storage",name:"存储",nameKey:"permissionStorage",description:"permissionStorageDesc",icon:"💾"}],Wk=[{id:"notifications",name:"通知",nameKey:"permissionNotifications",description:"permissionNotificationsDesc",icon:"🔔",permissions:["notifications"]},{id:"cookies",name:"Cookie管理",nameKey:"permissionCookies",description:"permissionCookiesDesc",icon:"🍪",permissions:["cookies"]}],Gk=[{id:"webdav",name:"WebDAV 访问权限",nameKey:"permissionWebdavAccess",description:"permissionWebdavAccessDesc",icon:"☁️",origins:[""]}],Qk=()=>{const{updateNestedSetting:e}=Ai(),[t,n]=z({}),[r,o]=z(true),[i,a]=z({open:false,message:"",onConfirm:()=>{}}),s=void 0!==chrome.permissions,l=A(async()=>{o(true);const e={};for(const n of Wk)try{let t=!1;if(s)t=await chrome.permissions.contains({permissions:n.permissions||[]});else {const e=await kp({type:yp,permissions:n.permissions||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}for(const n of Gk)try{let t=!1;if(s)t=await chrome.permissions.contains({origins:n.origins||[]});else {const e=await kp({type:yp,origins:n.origins||[]});e&&e.success&&(t=e.hasPermission);}e[n.id]=t;}catch(t){console.error(`检查权限 ${n.id} 失败:`,t),e[n.id]=false;}n(e),o(false);},[s]),c=A(async e=>{try{if(s){await chrome.permissions.request({origins:e.origins?.length?e.origins:void 0,permissions:e.permissions?.length?e.permissions:void 0})&&n(t=>({...t,[e.id]:!0}));}else await kp({type:vp,permType:e.id,origins:e.origins,permissions:e.permissions}),setTimeout(()=>l(),2e3);}catch(t){console.error(`请求权限 ${e.id} 失败:`,t);}},[s,l]);_(()=>{if(l(),s&&"undefined"!=typeof window){"true"===new URLSearchParams(window.location.search).get("auto_request")&&setTimeout(()=>{const e=Gk[0];e&&c(e);},500);}},[l,s,c]);const d=t=>{let r=se("revokeConfirmDefault");"notifications"===t.id?r=se("revokeConfirmNotifications"):"webdav"===t.id&&(r=se("revokeConfirmWebdav")),a({open:true,message:Ie("div",{style:{whiteSpace:"pre-wrap"},children:r}),onConfirm:()=>(async t=>{try{let r=!1;if(s)r=await chrome.permissions.remove({origins:t.origins?.length?t.origins:void 0,permissions:t.permissions?.length?t.permissions:void 0});else {const e=await kp({type:"REVOKE_PERMISSIONS",origins:t.origins,permissions:t.permissions});e&&e.success&&(r=e.removed);}r&&(n(e=>({...e,[t.id]:!1})),"notifications"===t.id?e("tab","showNotification",!1):"webdav"===t.id&&e("content","watermarkRemoval",!1));}catch(r){console.error(`撤销权限 ${t.id} 失败:`,r);}finally{a(e=>({...e,open:false}));}})(t)});}; return Le("div",{children:[ Ie(jx,{title:se("navPermissions"),Icon:st}), Ie("p",{className:"settings-page-desc",children:se("permissionsPageDesc")}), Le(Ox,{title:se("optionalPermissions"),description:se("optionalPermissionsDesc"),children:[ Le("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px",paddingBottom:"12px",borderBottom:"1px solid var(--gh-border, #e5e7eb)"},children:[ Ie("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary, #9ca3af)"},children:se("permissionsSyncHint")}), Ie("button",{className:"settings-btn settings-btn-secondary",onClick:async e=>{e.preventDefault(),e.stopPropagation(),await l(),Li(se("permissionsRefreshed"),1500);},disabled:r,style:{fontSize:"12px",padding:"4px 12px",flexShrink:0},children:se(r?"refreshing":"refreshStatus")})]}),[...Wk,...Gk].map((e,n,r)=>Ie(Fx,{label:Le("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("span",{style:{fontSize:"18px"},children:e.icon}), Ie("span",{children:se(e.nameKey)})]}),description:se(e.description),style:n===r.length-1?{borderBottom:"none"}:{},children:Ie("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:t[e.id]?Le(_e,{children:[ Ie("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(16, 185, 129, 0.1)",color:"#10b981"},children:se("granted")}), Ie("button",{className:"settings-btn settings-btn-secondary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),d(e);},children:se("revoke")})]}):Le(_e,{children:[ Ie("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(239, 68, 68, 0.1)",color:"#ef4444"},children:se("notGranted")}), Ie("button",{className:"settings-btn settings-btn-primary",style:{padding:"4px 12px",fontSize:"12px"},onClick:t=>{t.preventDefault(),t.stopPropagation(),c(e);},children:se("allowRecommended")})]})})},e.id))]}), Ie(Ox,{title:se("requiredPermissions"),description:se("requiredPermissionsDesc"),children:Hk.map((e,t)=>Ie(Fx,{label:Le("span",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("span",{style:{fontSize:"18px"},children:e.icon}), Ie("span",{children:se(e.nameKey)})]}),description:se(e.description),style:t===Hk.length-1?{borderBottom:"none"}:{},children:Ie("span",{style:{padding:"4px 10px",borderRadius:"4px",fontSize:"12px",background:"rgba(107, 114, 128, 0.1)",color:"var(--gh-text-secondary, #6b7280)"},children:se("required")})},e.id))}),i.open&&Ie(Lw,{title:se("warning"),message:i.message,confirmText:se("confirm"),cancelText:se("cancel"),danger:true,onConfirm:i.onConfirm,onCancel:()=>a(e=>({...e,open:false}))})]})},Vk=({binding:e,onChange:t,onRemove:n,conflictWarning:r})=>{const[o,i]=z(false),a=lr(),s=A(e=>{if(!o)return;if(e.preventDefault(),e.stopPropagation(),["Control","Alt","Shift","Meta"].includes(e.key))return;if(!a&&e.getModifierState("AltGraph"))return;const n={key:or(e.key,e.code),alt:e.altKey,ctrl:a?e.metaKey:e.ctrlKey,shift:e.shiftKey};if(!(n.alt||n.ctrl||n.meta||n.shift)){if(!["Escape","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"].includes(e.key))return}a&&e.ctrlKey&&!e.metaKey||(t(n),i(false));},[o,t,a]),l=o?se("pressAnyKey"):e?sr(e,a):se("shortcutNotSet"); return Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie("button",{className:`shortcut-input ${o?"recording":""} ${e?"":"not-set"}`,onClick:()=>i(true),onKeyDown:s,onBlur:()=>{i(false);},style:{padding:"6px 12px",minWidth:"120px",fontSize:"13px",fontFamily:"monospace",border:o?"2px solid var(--gh-primary)":"1px solid var(--gh-border, #e5e7eb)",borderRadius:"6px",background:o?"var(--gh-bg-hover)":"var(--gh-bg)",color:e?"var(--gh-text)":"var(--gh-text-tertiary)",cursor:"pointer",textAlign:"center",transition:"all 0.2s",fontStyle:e?"normal":"italic"},children:l}),e&&Ie(up,{content:se("shortcutRemove"),children:Ie("button",{onClick:n,style:{padding:"4px 8px",fontSize:"12px",border:"1px solid var(--gh-border)",borderRadius:"4px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer",transition:"all 0.2s"},children:"✕"})}),r&&Ie("span",{style:{fontSize:"12px",color:"var(--gh-error, #ef4444)"},children:r})]})},Kk=({siteId:e})=>{const{settings:t,setSettings:n}=Ai(),r=t?.shortcuts,i=o.useMemo(()=>lr(),[]),a=A((e,t)=>{if(!t)return;const n=ir(t);if(!n)return;const o=r?.keybindings||{};for(const[r,i]of Object.entries(o)){if(r===e)continue;if(null===i)continue;const t=Jn[r];if(!t)continue;const o=ir(i);if(o&&(o.key===n.key&&!!o.alt==!!n.alt&&!!o.ctrl==!!n.ctrl&&!!o.shift==!!n.shift)){return [se("shortcutConflictWith"),`"${se(t.labelKey)}"`,se("shortcutConflict")].filter(Boolean).join(" ")}}},[r?.keybindings]),s=A((e,t)=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:t}}});},[r,n]),l=A(e=>{n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:{...r?.keybindings,[e]:null}}});},[r,n]),[c,d]=z(false),u=A(()=>{n({shortcuts:{...r,keybindings:{...er}}}),d(false);},[r,n]),h=Object.entries(Xn).map(([e,t])=>{const n=Object.entries(Jn).filter(([,t])=>t.category===e);return {categoryId:e,categoryMeta:t,actions:n}});return t?Le("div",{children:[ Ie(jx,{title:se("navShortcuts"),Icon:Et}), Ie("p",{className:"settings-page-desc",children:se("shortcutsPageDesc")}), Le(Ox,{title:se("shortcutsGlobalSettings"),children:[ Ie($x,{label:se("enableShortcuts"),description:se("enableShortcutsDesc"),checked:r?.enabled??true,settingId:"shortcuts-enabled",onChange:()=>n({shortcuts:{...r,enabled:!(r?.enabled??1),globalUrl:r?.globalUrl??"https://gemini.google.com",keybindings:r?.keybindings??er}})}),qi.hasCapability("commands")&&Le(_e,{children:[ Ie(Fx,{label:se("globalShortcutUrl"),description:(()=>{const e=se("globalShortcutUrlDesc",{shortcut:i?"⌥O":"Alt+O"});return "globalShortcutUrlDesc"===e?i?"按下全局快捷键 ⌥O 时打开的网址":"按下全局快捷键 Alt+O 时打开的网址":e})(),settingId:"shortcuts-global-url",children:Ie("input",{type:"text",className:"settings-input",value:r?.globalUrl||"https://gemini.google.com",onChange:e=>n({shortcuts:{...r,enabled:r?.enabled??true,globalUrl:e.target.value,keybindings:r?.keybindings??er}}),style:{width:"280px"},placeholder:"https://gemini.google.com"})}), Ie(Fx,{label:se("globalShortcutsTitle"),description:se("globalShortcutsDesc"),settingId:"shortcuts-browser-shortcuts",children:(()=>{const e=navigator.userAgent,t=e.includes("Chrome")&&!e.includes("Edg/"),n=e.includes("Edg/"),r=e.includes("Firefox");if(!(t||n||r)) return Ie("span",{style:{fontSize:"13px",color:"var(--gh-text-tertiary)"},children:se("browserNotSupported")});let o="chrome://extensions/shortcuts";return n&&(o="edge://extensions/shortcuts"),r?Ie("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)",lineHeight:"1.5"},children:se("firefoxShortcutsGuide")}):Ie("button",{onClick:()=>kp({type:"OPEN_URL",url:o}),style:{padding:"6px 12px",fontSize:"13px",border:"none",borderRadius:"6px",background:"var(--gh-primary)",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},children:se("openBrowserShortcuts")})})()})]}), Ie("div",{style:{marginTop:"16px",paddingTop:"16px",display:"flex",justifyContent:"flex-end"},children:Ie("button",{onClick:()=>d(true),style:{padding:"8px 16px",fontSize:"13px",border:"1px solid var(--gh-border)",borderRadius:"6px",background:"var(--gh-bg)",color:"var(--gh-text-secondary)",cursor:"pointer"},children:se("resetShortcuts")})})]}),h.map(({categoryId:e,categoryMeta:t,actions:n})=>Ie(Ox,{title:se(t.labelKey),children:n.map(([e,t])=>{const n=r?.keybindings?.[e],o=null===n?null:n||er[e],i=a(e,o); return Ie(Fx,{label:se(t.labelKey),disabled:!r?.enabled,settingId:`shortcut-binding-${e}`,children:Ie(Vk,{binding:o,onChange:t=>s(e,t),onRemove:()=>l(e),conflictWarning:i||void 0})},e)})},e)),c&&Ie(Lw,{title:se("resetShortcuts"),message:se("resetShortcutsConfirm"),danger:true,onConfirm:u,onCancel:()=>d(false)})]}):null};let Zk=null;const Yk=Bo()($o((e,t)=>(Zk=()=>e({_hasHydrated:true}),{keys:[],currentKeyId:"",_hasHydrated:false,addKey:t=>{const n={id:crypto.randomUUID(),...t,createdAt:Date.now()};return e(e=>({keys:[...e.keys,n]})),n},updateKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,...n}:e)})),deleteKey:t=>e(e=>({keys:e.keys.filter(e=>e.id!==t),currentKeyId:e.currentKeyId===t?"":e.currentKeyId})),setCurrentKey:t=>e({currentKeyId:t}),testKey:(t,n)=>e(e=>({keys:e.keys.map(e=>e.id===t?{...e,isValid:n.isValid,accountType:n.accountType,testedAt:Date.now()}:e)})),setKeys:t=>e({keys:t}),setHasHydrated:t=>e({_hasHydrated:t})}),{name:"claudeSessionKeys",storage:Oo(()=>di),partialize:e=>({keys:e.keys,currentKeyId:e.currentKeyId}),onRehydrateStorage:()=>()=>{Zk?.();}})),Jk=Object.freeze(Object.defineProperty({__proto__:null,useClaudeSessionKeysStore:Yk},Symbol.toStringTag,{value:"Module"})),Xk=({siteId:e})=>{const{keys:t,currentKeyId:n,addKey:r,deleteKey:o,setCurrentKey:i,testKey:a,setKeys:s}=Yk(),[l,c]=z({}),[d,u]=z({type:"none"}),[h,g]=z(null),[p,m]=z(null),[f,b]=z(false),[y,v]=z(""),w=e===so,x=t.find(e=>e.id===n),k=()=>u({type:"none"}),S=async(e,t)=>{try{await navigator.clipboard.writeText(t),m(e),Li(se("claudeKeyCopied"),Qr),setTimeout(()=>m(null),Qr);}catch{Li(se("claudeKeyCopyFailed"),Qr);}},C=async e=>{if(!e)return void Li(se("claudePleaseSelectKey"),Qr);if(e===n)return void Li(se("claudeAlreadyUsing"),Qr);if(qi.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Li(se("claudeRequestPermission"),Kr)}else {if(!(await kp({type:yp,permissions:["cookies"]})).hasPermission)return await kp({type:vp,permType:"cookies"}),void Li(se("claudeRequestPermission"),Kr)}const r=e?t.find(t=>t.id===e)?.key:"";await qi.setClaudeSessionKey(r||""),i(e),Li(se("claudeKeySwitched"),Vr);},A=async(e,t,n,r=true)=>{if(qi.hasCapability("tabs"))try{if((await kp({type:"CHECK_CLAUDE_GENERATING"})).isGenerating)return r&&Li(se("claudeGenerating"),Kr),!1}catch{}c(t=>({...t,[e]:true}));try{const o=await qi.testClaudeSessionKey(n);return o.isValid?(a(e,{isValid:!0,accountType:o.accountType}),r&&Li(`${t}: ${o.accountType}`,Vr),!0):(a(e,{isValid:!1}),r&&Li(`${t}: ${se("claudeKeyInvalid")}`,Vr),!1)}catch{return a(e,{isValid:false}),r&&Li(`${t}: ${se("claudeKeyTest")} ${se("claudeKeyInvalid")}`,Vr),false}finally{c(t=>({...t,[e]:false}));}},E=async e=>{const n=t.find(t=>t.id===e);n&&await A(e,n.name,n.key,true);}; return Le("div",{children:[ Le(Ox,{title:se("claudeSessionKeyTitle"),description:se("claudeSessionKeyDesc"),settingId:"claude-session-keys",children:[ Le("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px",marginBottom:"20px",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"12px",border:"1px solid var(--gh-border)",flexWrap:"wrap",gap:"12px"},children:[ Le("div",{style:{display:"flex",alignItems:"center",gap:"12px",flex:"1 1 auto"},children:[ Ie("span",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:se("claudeCurrentUsing")}), Ie("span",{style:{fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",gap:"8px"},children:x?Le(_e,{children:[ Le("span",{style:{fontWeight:600},children:["🔑 ",x.name]}),x.accountType&&Ie("span",{style:{padding:"2px 8px",borderRadius:"12px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text-secondary)"},children:x.accountType})]}):Ie("span",{style:{color:"var(--gh-text-secondary)"},children:se("claudeNoKeySelected")})})]}), Le("div",{style:{display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap"},children:[!w&&Le("div",{style:{color:"#ca8a04",backgroundColor:"rgba(234, 179, 8, 0.1)",fontSize:"12px",display:"flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"6px",border:"1px solid rgba(234, 179, 8, 0.2)",whiteSpace:"nowrap"},children:[ Ie("span",{children:"⚠️"}), Ie("span",{children:se("claudeNotOnSiteHint")})]}), Ie(up,{content:w?"":se("claudeNotOnSiteHint"),children:Ie("select",{className:"settings-select",value:n,onChange:e=>C(e.target.value),disabled:!w||0===t.length||f,style:{minWidth:"200px",padding:"8px 12px",fontSize:"13px",borderRadius:"8px",opacity:!w||0===t.length||f?.6:1,cursor:!w||f?"not-allowed":"pointer",backgroundColor:"var(--gh-bg)",border:"1px solid var(--gh-border)",color:"var(--gh-text)"},children:0===t.length?Ie("option",{value:"",children:se("claudePleaseAddKey")}):t.map(e=>Le("option",{value:e.id,children:["🔑 ",e.name," ",e.accountType?`(${e.accountType})`:""]},e.id))})})]})]}), Le("div",{style:{display:"flex",gap:"10px",marginBottom:"20px",flexWrap:"nowrap"},children:[ Le("button",{className:"settings-btn settings-btn-primary",onClick:()=>{u({type:"add"});},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["➕ ",se("claudeAddKey")]}), Ie("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{if(0===t.length)return;if(f)return;b(true);let e=0,n=0;try{for(let r=0;rsetTimeout(e,ao));}Li(se("claudeBatchTestDone").replace("{valid}",String(e)).replace("{invalid}",String(n)),Kr);}catch{Li(se("claudeBatchTestFailed"),Vr);}finally{b(false),v("");}},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,backgroundColor:f?"rgba(var(--gh-primary-rgb), 0.1)":void 0,color:f?"var(--gh-primary)":void 0,borderColor:f?"var(--gh-primary)":void 0,whiteSpace:"nowrap"},children:Le(_e,f?{children:[ Ie("div",{style:{marginRight:"8px",width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}),y]}:{children:["⚡ ",se("claudeBatchTest")]})}),qi.hasCapability("cookies")&&Ie(up,{content:w?"":se("claudeNotOnSiteHint"),children:Le("button",{className:"settings-btn settings-btn-secondary",onClick:async()=>{try{if(qi.hasCapability("permissions"))if(void 0!==chrome.permissions){if(!(await chrome.permissions.request({permissions:["cookies"]})))return void Li(se("claudeRequestPermission"),Kr)}else {if(!(await kp({type:yp,permissions:["cookies"]})).hasPermission)return await kp({type:vp,permType:"cookies"}),void Li(se("claudeRequestPermission"),Kr)}const e=await qi.getClaudeSessionKey();if(!e.success)return void Li(e.error||se("claudeNoCookieFound"),Vr);const n=t.find(t=>t.key===e.sessionKey);if(n)return void Li(se("claudeTokenExists").replace("{name}",n.name),Vr);u({type:"import-name",sessionKey:e.sessionKey});}catch(e){Li(se("claudeKeyCopyFailed")+": "+e.message,Kr);}},disabled:!w||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:!w||f?.6:1,backgroundColor:w?"var(--gh-bg)":"var(--gh-bg-secondary)",color:w?"var(--gh-primary)":"var(--gh-text-secondary)",borderColor:w?"var(--gh-primary)":"var(--gh-border)",whiteSpace:"nowrap"},children:["🌐 ",se("claudeImportFromBrowser")]})}), Le("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{const e=document.createElement("input");e.type="file",e.accept="application/json",e.onchange=async e=>{const n=e.target.files?.[0];if(n)try{const e=await n.text(),r=JSON.parse(e);if(!Array.isArray(r))return void Li(se("claudeInvalidJSON"),Vr);const o=new Set(t.map(e=>e.key)),i=r.filter(e=>!o.has(e.key));if(0===i.length)return void Li(se("claudeNoNewTokens"),Qr);s([...t,...i]),Li(se("claudeImported").replace("{count}",String(i.length)),Vr);}catch(r){Li(se("claudeInvalidJSON")+": "+r.message,Kr);}},e.click();},disabled:f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:f?.6:1,whiteSpace:"nowrap"},children:["📥 ",se("claudeImportJSON")]}), Le("button",{className:"settings-btn settings-btn-secondary",onClick:()=>{if(0===t.length)return void Li(se("claudeNoTokensToExport"),Qr);const e=JSON.stringify(t,null,2),n=new Blob([e],{type:"application/json"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=`claude-session-keys-${Date.now()}.json`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r),Li(se("claudeExported"),Qr);},disabled:0===t.length||f,style:{justifyContent:"center",padding:"8px 12px",flex:"1 1 auto",opacity:0===t.length||f?.6:1,whiteSpace:"nowrap"},children:["📤 ",se("claudeExportJSON")]})]}),0===t.length?Le("div",{style:{padding:"48px 24px",textAlign:"center",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-secondary)",borderRadius:"8px",border:"1px dashed var(--gh-border)"},children:[ Ie("div",{style:{marginBottom:"8px",fontSize:"24px"},children:"🔑"}), Ie("div",{children:se("claudeNoKeys")}), Ie("div",{style:{fontSize:"12px",marginTop:"4px"},children:se("claudeNoKeysHint")})]}):Ie("div",{style:{display:"flex",flexDirection:"column",gap:"12px"},children:t.map(e=>{const t=e.id===n,r=h===e.id; return Le("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"16px",padding:"16px 20px",backgroundColor:t?"var(--gh-bg)":"var(--gh-bg-secondary)",borderRadius:"12px",border:t?"2px solid var(--gh-primary)":"1px solid var(--gh-border)",transition:"all 0.2s ease",boxShadow:t?"var(--gh-shadow-brand)":"none"},onMouseEnter:()=>g(e.id),onMouseLeave:()=>g(null),children:[ Le("div",{style:{display:"flex",flexDirection:"column",gap:"6px",flex:"1 1 auto",minWidth:0},children:[ Le("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[ Ie("span",{style:{fontWeight:600,fontSize:"15px",color:"var(--gh-text)"},children:e.name}),t&&Ie("span",{style:{fontSize:"11px",color:"var(--gh-primary)",backgroundColor:"var(--gh-bg-secondary)",padding:"1px 6px",borderRadius:"4px",fontWeight:500,border:"1px solid var(--gh-border)"},children:"当前使用"}),(i=e.accountType,Ie("span",i?{style:{padding:"2px 8px",borderRadius:"4px",fontSize:"11px",fontWeight:500,backgroundColor:"var(--gh-bg-secondary)"},children:i}:{style:{color:"var(--gh-text-secondary)"},children:se("claudeKeyUntested")}))]}), Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie(up,{content:se("claudeKeyDoubleTapCopy"),children:Le("code",{onDoubleClick:()=>S(e.id,e.key),style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",color:"var(--gh-text-secondary)",backgroundColor:"var(--gh-bg-tertiary)",padding:"2px 6px",borderRadius:"4px",cursor:"pointer",maxWidth:"300px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.key.substring(0,32),"..."]})}),(r||p===e.id)&&Ie(up,{content:p===e.id?se("claudeCopied"):se("claudeCopyKey"),children:Ie("button",{onClick:t=>{t.stopPropagation(),S(e.id,e.key);},style:{background:"none",border:"none",cursor:p===e.id?"default":"pointer",fontSize:"12px",padding:"2px",color:p===e.id?"var(--gh-secondary)":"var(--gh-text-tertiary)"},children:p===e.id?"✓":Ie(Tt,{size:14})})})]})]}), Le("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[ Ie("div",{style:{fontSize:"13px",color:"var(--gh-text-secondary)"},children:(o=e.isValid,void 0===o?Ie("span",{style:{color:Jr},children:"-"}):Le("span",o?{style:{color:Zr,fontWeight:500},children:["✓ ",se("claudeKeyValid")]}:{style:{color:Yr,fontWeight:500},children:["✗ ",se("claudeKeyInvalid")]}))}), Le("div",{style:{display:"flex",gap:"8px"},children:[ Ie(up,{content:se(t?"claudeAlreadyUsing":w?"claudeKeyUse":"claudeNotOnSiteHint"),children:Ie("button",{className:"settings-btn settings-btn-secondary",onClick:()=>C(e.id),disabled:!w||t,style:{padding:"6px 12px",fontSize:"13px",opacity:!w||t?.5:1,cursor:!w||t?"not-allowed":"pointer"},children:se(t?"claudeKeyUsing":"claudeKeyUse")})}), Ie("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",minWidth:"60px",justifyContent:"center"},onClick:()=>E(e.id),disabled:l[e.id],children:l[e.id]?Ie("div",{style:{width:"14px",height:"14px",border:"2px solid currentColor",borderTopColor:"transparent",borderRadius:"50%",animation:"spin 1s linear infinite"}}):se("claudeKeyTest")}), Ie("button",{className:"settings-btn settings-btn-secondary",style:{padding:"6px 12px",fontSize:"13px",color:"var(--gh-danger)",borderColor:"rgba(239, 68, 68, 0.2)",backgroundColor:"rgba(239, 68, 68, 0.05)"},onClick:()=>{return t=e.id,n=e.name,void u({type:"delete",id:t,name:n});var t,n;},children:se("claudeKeyDelete")}), Ie("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n "})]})]})]},e.id);var o,i;})})]}),"add"===d.type&&Ie(eS,{onConfirm:(e,n)=>{e.trim()?n.trim()?io.CLAUDE_KEY.test(n)?t.some(e=>e.key===n)?Li(se("claudeKeyExists"),Vr):(r({name:e.trim(),key:n.trim()}),Li(se("claudeKeyAdded"),Qr),k()):Li(se("claudeKeyInvalidFormat"),Vr):Li(se("claudeKeyRequired"),Qr):Li(se("claudeNameRequired"),Qr);},onCancel:k}),"import-name"===d.type&&Ie(Nw,{title:se("claudeImportNameTitle"),defaultValue:`Import-${(new Date).toLocaleDateString()}`,placeholder:se("claudeImportNamePlaceholder"),onConfirm:e=>{if(!e.trim())return void Li(se("claudeNameRequired"),Qr);const t=d,n=r({name:e.trim(),key:t.sessionKey});i(n.id),Li(se("claudeKeyImported"),Qr),k(),setTimeout(()=>E(n.id),ao);},onCancel:k}),"delete"===d.type&&Ie(Lw,{title:se("claudeDeleteConfirmTitle"),message:se("claudeDeleteConfirmMsg").replace("{name}",d.name),confirmText:se("claudeKeyDelete"),danger:true,onConfirm:()=>{o(d.id),Li(se("claudeKeyDeleted"),Qr),k();},onCancel:k})]})},eS=({onConfirm:e,onCancel:t})=>{const[n,r]=z(""),[i,a]=z(""),s=o.useRef(null);o.useEffect(()=>{s.current?.focus();},[]);const l=()=>{e(n,i);}; return Le(Iw,{onClose:t,children:[ Ie("div",{className:"gh-dialog-title",children:se("claudeAddKey")}), Le("div",{style:{display:"flex",flexDirection:"column",gap:"16px",marginBottom:"24px"},children:[ Le("div",{children:[ Ie("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:se("claudeAddKeyNameTitle").split("-")[1].trim().replace("输入","")}), Ie("input",{ref:s,type:"text",className:"gh-dialog-input",value:n,onChange:e=>r(e.target.value),placeholder:se("claudeAddKeyNamePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&document.getElementById("claude-key-input")?.focus()})]}), Le("div",{children:[ Ie("div",{style:{marginBottom:"6px",fontSize:"14px",fontWeight:500,color:"var(--gh-text)"},children:"Session Key"}), Ie("input",{id:"claude-key-input",type:"text",className:"gh-dialog-input",value:i,onChange:e=>a(e.target.value),placeholder:se("claudeAddKeyValuePlaceholder"),style:{marginBottom:0},onKeyDown:e=>"Enter"===e.key&&l()})]})]}), Le("div",{className:"gh-dialog-buttons",children:[ Ie("button",{className:"gh-dialog-btn gh-dialog-btn-secondary",onClick:t,children:se("cancel")}), Ie("button",{className:"gh-dialog-btn gh-dialog-btn-primary",onClick:l,children:se("confirm")})]})]})},tS=({label:e,siteKey:t,settings:n,setSettings:r,placeholder:o,onDisabledClick:i,settingId:a})=>{const s=q(()=>n.modelLock?.[t]||{enabled:false,keyword:""},[n.modelLock,t]),[l,c]=z(s.keyword);_(()=>{c(s.keyword);},[s.keyword]);const d=A(()=>{l!==s.keyword&&r({modelLock:{...n.modelLock,[t]:{...s,keyword:l}}});},[l,s,n.modelLock,t,r]); return Le("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:s.enabled?"default":"not-allowed"},"data-setting-id":a,children:[ Ie("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:s.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:e}), Ie("div",{onMouseDown:e=>{s.enabled||(e.preventDefault(),i?.());},children:Ie("input",{type:"text",className:"settings-input",value:l,onChange:e=>c(e.target.value),onBlur:d,onKeyDown:e=>{"Enter"===e.key&&(d(),e.target.blur());},placeholder:o,disabled:!s.enabled,style:{width:"200px",opacity:s.enabled?1:.5,pointerEvents:s.enabled?"auto":"none"}})}), Ie(Mw,{checked:s.enabled,onChange:()=>{r({modelLock:{...n.modelLock,[t]:{...s,enabled:!s.enabled}}});}})]})},nS=({settings:e,setSettings:t,onDisabledClick:n,settingId:r})=>{const o="aistudio",i=e.modelLock?.[o]||{enabled:false,keyword:""},[a,s]=z(e.aistudio?.cachedModels||[]),[l,c]=z(false);_(()=>{e.aistudio?.cachedModels&&s(e.aistudio.cachedModels);},[e.aistudio?.cachedModels]); return Le("div",{style:{display:"flex",alignItems:"center",gap:"12px",marginBottom:"12px",cursor:i.enabled?"default":"not-allowed"},"data-setting-id":r,children:[ Ie("span",{style:{fontSize:"14px",fontWeight:500,flex:1,color:i.enabled?"var(--gh-text, #374151)":"var(--gh-text-secondary, #9ca3af)"},children:"AI Studio"}), Ie(up,{content:se("aistudioRefreshModelListTooltip"),children:Ie("button",{className:"icon-button",onClick:async()=>{c(true);try{const n=await kp({type:"GET_AISTUDIO_MODELS"});if(n.success&&n.models)s(n.models),t({aistudio:{...e.aistudio,cachedModels:n.models}}),Li(se("aistudioModelsFetched"),2e3);else {Li("NO_AISTUDIO_TAB"===n.error?se("aistudioNoTabError"):se("aistudioModelsError"),3e3);}}catch(n){Li(se("aistudioModelsError"),3e3),console.error("Refresh model list failed:",n);}finally{c(false);}},disabled:l,style:{padding:"4px",opacity:l?.5:1,cursor:l?"not-allowed":"pointer",background:"transparent",border:"none",borderRadius:"4px",display:"flex",alignItems:"center",justifyContent:"center"},children:Ie(Fe,{size:16})})}), Ie("div",{onMouseDown:e=>{i.enabled||(e.preventDefault(),n?.());},children:Le("select",{className:"settings-select",value:i.keyword||"",onChange:n=>{return r=n.target.value,void t({modelLock:{...e.modelLock,[o]:{...i,keyword:r}}});var r;},disabled:!i.enabled||0===a.length,style:{width:"200px",opacity:i.enabled?1:.5,pointerEvents:i.enabled?"auto":"none"},children:[0===a.length&&Ie("option",{value:"",children:se("aistudioRefreshModelListFirst")}),a.map(e=>Ie("option",{value:e.id,children:e.name},e.id))]})}), Ie(Mw,{checked:i.enabled,onChange:()=>{t({modelLock:{...e.modelLock,[o]:{...i,enabled:!i.enabled}}});}})]})},rS=({siteId:e,initialTab:t})=>{const[n,r]=z(t||Nr);_(()=>{t&&r(t);},[t]);const{settings:o,setSettings:i,setPreviewSettings:a,clearPreviewSettings:s,updateNestedSetting:l}=Ai(),c=se("enablePrerequisiteToast"),d=e=>Ni(c.replace("{setting}",e),2e3,{},1500,e),u=se("enablePageWidth"),h=se("enableUserQueryWidth"),g=se("modelLockTitle"),p=o?.layout?.pageWidth?.[e]||o?.layout?.pageWidth?._default,m=o?.layout?.userQueryWidth?.[e]||o?.layout?.userQueryWidth?._default,f=(e,t)=>{const n=Number.parseInt(e??t,10);return Number.isNaN(n)?Number.parseInt(t,10):n},b=f(p?.value,oo.PAGE_WIDTH.DEFAULT_PERCENT),y=f(m?.value,oo.USER_QUERY_WIDTH.DEFAULT_PERCENT),v=(t,n)=>{if(!o)return;const r="pageWidth"===t?oo.PAGE_WIDTH:oo.USER_QUERY_WIDTH,i=("pageWidth"===t?p:m)||{enabled:false,value:r.DEFAULT_PERCENT,unit:"%"},a=Math.min(r.MAX_PERCENT,Math.max(r.MIN_PERCENT,n));return {layout:{...o.layout,[t]:{...o.layout?.[t],[e]:{...i,value:String(a),unit:"%"}}}}},w=(e,t)=>{const n=v(e,t);n&&a(n);},x=(e,t)=>{const n=v(e,t);n&&i(n);};if(!o)return null;const k=[{id:Nr,label:se("tabLayout")},{id:Dr,label:se("tabModelLock")},{id:lo,label:se("tabGemini")},{id:po,label:"AI Studio"},{id:co,label:"ChatGPT"},{id:so,label:"Claude"}]; return Le("div",{children:[ Ie(jx,{title:se("navSiteSettings"),Icon:it}), Ie("p",{className:"settings-page-desc",children:se("siteSettingsPageDesc")}), Ie(Ux,{tabs:k,activeTab:n,onTabChange:r}),n===Nr&&Le(_e,{children:[ Le(Ox,{title:se("layoutSettingsTitle"),children:[ Ie($x,{label:se("enablePageWidth"),description:se("pageWidthDesc"),settingId:"layout-page-width-enabled",checked:p?.enabled??false,onChange:()=>{const t=p||{enabled:false,value:"81",unit:"%"};i({layout:{...o?.layout,pageWidth:{...o?.layout?.pageWidth,[e]:{...t,enabled:!t.enabled}}}});}}), Ie(Fx,{label:se("pageWidthValueLabel"),settingId:"layout-page-width-value",disabled:!p?.enabled,onDisabledClick:()=>d(u),children:Ie(Pw,{value:b,onChange:e=>x("pageWidth",e),onPreviewChange:e=>w("pageWidth",e),onCancelPreview:s,min:oo.PAGE_WIDTH.MIN_PERCENT,max:oo.PAGE_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(oo.PAGE_WIDTH.DEFAULT_PERCENT,10),disabled:!p?.enabled,formatValue:e=>`${e}%`,ariaLabel:se("pageWidthValueLabel")})})]}), Le(Ox,{title:se("userQueryWidthSettings"),children:[ Ie($x,{label:se("enableUserQueryWidth"),description:se("userQueryWidthDesc"),settingId:"layout-user-query-width-enabled",checked:m?.enabled??false,onChange:()=>{const t=m||{enabled:false,value:"81",unit:"%"};i({layout:{...o?.layout,userQueryWidth:{...o?.layout?.userQueryWidth,[e]:{...t,enabled:!t.enabled}}}});}}), Ie(Fx,{label:se("userQueryWidthValueLabel"),settingId:"layout-user-query-width-value",disabled:!m?.enabled,onDisabledClick:()=>d(h),children:Ie(Pw,{value:y,onChange:e=>x("userQueryWidth",e),onPreviewChange:e=>w("userQueryWidth",e),onCancelPreview:s,min:oo.USER_QUERY_WIDTH.MIN_PERCENT,max:oo.USER_QUERY_WIDTH.MAX_PERCENT,step:1,unit:"%",defaultValue:Number.parseInt(oo.USER_QUERY_WIDTH.DEFAULT_PERCENT,10),disabled:!m?.enabled,formatValue:e=>`${e}%`,ariaLabel:se("userQueryWidthValueLabel")})})]}), Ie(Ox,{title:se("zenModeTitle"),children:Ie($x,{label:se("zenModeLabel"),description:se("zenModeDesc"),settingId:"layout-zen-mode-enabled",checked:o.layout?.zenMode?.[e]?.enabled??false,onChange:()=>{const t=o.layout?.zenMode?.[e]||{enabled:false},n=!t.enabled,r={...o.layout,zenMode:{...o.layout?.zenMode,[e]:{...t,enabled:n}}};n&&(r.cleanMode={...o.layout?.cleanMode,[e]:{enabled:true}}),i({layout:r});}})}), Ie(Ox,{title:se("cleanModeTitle"),children:Ie($x,{label:se("cleanModeLabel"),description:se("cleanModeDesc"),settingId:"layout-clean-mode-enabled",checked:o.layout?.cleanMode?.[e]?.enabled??true,onChange:()=>{const t=o.layout?.cleanMode?.[e]||{enabled:true};i({layout:{...o.layout,cleanMode:{...o.layout?.cleanMode,[e]:{...t,enabled:!t.enabled}}}});}})})]}),n===Dr&&Le(Ox,{title:se("modelLockTitle"),description:se("modelLockDesc"),children:[ Ie(tS,{label:"Gemini",siteKey:"gemini",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini"}), Ie(tS,{label:"Gemini Enterprise",siteKey:"gemini-enterprise",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-gemini-enterprise"}), Ie(nS,{settings:o,setSettings:i,onDisabledClick:()=>d(g),settingId:"model-lock-aistudio"}), Ie(tS,{label:"ChatGPT",siteKey:"chatgpt",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-chatgpt"}), Ie(tS,{label:"Claude",siteKey:"claude",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-claude"}), Ie(tS,{label:"Grok",siteKey:"grok",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-grok"}), Ie(tS,{label:"Kimi",siteKey:"kimi",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-kimi"}), Ie(tS,{label:"Qianwen",siteKey:"qianwen",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qianwen"}), Ie(tS,{label:"Qwen Studio",siteKey:"qwenai",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-qwenai"}), Ie(tS,{label:"Yuanbao",siteKey:"yuanbao",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-yuanbao"}), Ie(tS,{label:"ima",siteKey:"ima",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-ima"}), Ie(tS,{label:"Z.ai",siteKey:"zai",settings:o,setSettings:i,placeholder:se("modelKeywordPlaceholder"),onDisabledClick:()=>d(g),settingId:"model-lock-zai"})]}),"gemini"===n&&Le(Ox,{title:se("geminiSettingsTab"),description:se("contentProcessingDesc"),children:[ Ie($x,{label:se("markdownFixLabel"),description:se("markdownFixDesc"),settingId:"gemini-markdown-fix",checked:o.content?.markdownFix??false,onChange:()=>l("content","markdownFix",!o.content?.markdownFix)}), Ie($x,{label:se("watermarkRemovalLabel"),description:se("watermarkRemovalDesc"),settingId:"gemini-watermark-removal",checked:o.content?.watermarkRemoval??false,onChange:async()=>{const e=o.content?.watermarkRemoval;if(e)l("content","watermarkRemoval",false);else {if(!qi.hasCapability("permissions"))return void l("content","watermarkRemoval",true);if(void 0!==chrome.permissions){await chrome.permissions.request({origins:[""]})&&l("content","watermarkRemoval",true);}else {const e=await kp({type:yp,origins:[""]});e.success&&e.hasPermission?l("content","watermarkRemoval",true):(await kp({type:vp,permType:"allUrls"}),Li(se("permissionRequestToast"),3e3));}}}}), Le("div",{className:"setting-subsection",style:{marginTop:"24px",paddingTop:"16px",borderTop:"1px solid var(--gh-border-color)"},children:[ Ie("h3",{style:{fontSize:"14px",fontWeight:600,marginBottom:"12px"},children:"Gemini Enterprise"}), Ie($x,{label:se("policyRetryLabel"),description:se("policyRetryDesc"),settingId:"gemini-policy-retry",checked:o.geminiEnterprise?.policyRetry?.enabled??false,onChange:()=>{const e=o.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3};i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...e,enabled:!e.enabled}}});}}),o.geminiEnterprise?.policyRetry?.enabled&&Ie(Fx,{label:se("maxRetriesLabel"),settingId:"gemini-policy-max-retries",children:Le("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[ Ie(qw,{value:o.geminiEnterprise?.policyRetry?.maxRetries??3,onChange:e=>i({geminiEnterprise:{...o.geminiEnterprise,policyRetry:{...o.geminiEnterprise?.policyRetry,maxRetries:e}}}),min:1,max:10,defaultValue:3,style:{width:"60px"}}), Ie("span",{style:{fontSize:"12px",color:"var(--gh-text-secondary)"},children:se("retryCountSuffix")})]})})]})]}),n===po&&Le(Ox,{title:se("aistudioSettingsTitle"),description:se("aistudioSettingsDesc"),children:[ Ie($x,{label:se("aistudioCollapseNavbar"),description:se("aistudioCollapseNavbarDesc"),settingId:"aistudio-collapse-navbar",checked:o.aistudio?.collapseNavbar??false,onChange:()=>i({aistudio:{...o.aistudio,collapseNavbar:!o.aistudio?.collapseNavbar}})}), Ie($x,{label:se("aistudioCollapseRunSettings"),description:se("aistudioCollapseRunSettingsDesc"),settingId:"aistudio-collapse-run-settings",checked:o.aistudio?.collapseRunSettings??false,onChange:()=>i({aistudio:{...o.aistudio,collapseRunSettings:!o.aistudio?.collapseRunSettings}})}), Ie($x,{label:se("aistudioCollapseTools"),description:se("aistudioCollapseToolsDesc"),settingId:"aistudio-collapse-tools",checked:o.aistudio?.collapseTools??false,onChange:()=>i({aistudio:{...o.aistudio,collapseTools:!o.aistudio?.collapseTools}})}), Ie($x,{label:se("aistudioCollapseAdvanced"),description:se("aistudioCollapseAdvancedDesc"),settingId:"aistudio-collapse-advanced",checked:o.aistudio?.collapseAdvanced??false,onChange:()=>i({aistudio:{...o.aistudio,collapseAdvanced:!o.aistudio?.collapseAdvanced}})}), Ie($x,{label:se("aistudioEnableSearch"),description:se("aistudioEnableSearchDesc"),settingId:"aistudio-enable-search",checked:o.aistudio?.enableSearch??true,onChange:()=>i({aistudio:{...o.aistudio,enableSearch:!o.aistudio?.enableSearch}})}), Ie($x,{label:se("aistudioRemoveWatermark"),description:se("aistudioRemoveWatermarkDesc"),settingId:"aistudio-remove-watermark",checked:o.aistudio?.removeWatermark??false,onChange:()=>{i({aistudio:{...o.aistudio,removeWatermark:!o.aistudio?.removeWatermark}}),Li(se("aistudioReloadHint"),3e3);}}), Ie($x,{label:se("aistudioMarkdownFixLabel"),description:se("aistudioMarkdownFixDesc"),settingId:"aistudio-markdown-fix",checked:o.aistudio?.markdownFix??false,onChange:()=>i({aistudio:{...o.aistudio,markdownFix:!o.aistudio?.markdownFix}})})]}),"claude"===n&&Ie(Xk,{siteId:e}),n===co&&Ie(Ox,{title:se("chatgptSettingsTitle"),description:se("chatgptSettingsDesc"),children:Ie($x,{label:se("chatgptMarkdownFixLabel"),description:se("chatgptMarkdownFixDesc"),settingId:"chatgpt-markdown-fix",checked:o.chatgpt?.markdownFix??false,onChange:()=>i({chatgpt:{...o.chatgpt,markdownFix:!o.chatgpt?.markdownFix}})})})]})},oS=(e,t)=>{const n=se(e);return n===e?t:n},iS=[{id:gr,Icon:rt,labelKey:"navGeneral",label:"基本设置"},{id:pr,Icon:ot,labelKey:"navAppearance",label:"外观主题"},{id:mr,Icon:at,labelKey:"navFeatures",label:"功能模块"},{id:fr,Icon:it,labelKey:"navSiteSettings",label:"站点配置"},{id:br,Icon:Wt,labelKey:"navGlobalSearch",label:"全局搜索"},{id:yr,Icon:Et,labelKey:"navShortcuts",label:"快捷键位"},{id:vr,Icon:({size:e=20,color:t="currentColor",className:n="",style:r})=>Ie("svg",{viewBox:"0 0 1027 1024",width:e,height:e,className:n,style:{display:"block",...r},children:Ie("path",{d:"M983.716 651.25l42.5-42.5L847.466 431.25 668.716 608.75l42.5 42.5 106.25-106.25 0 373.75L876.216 918.75 876.216 545 983.716 651.25zM533.716 793.75 533.716 421.25l-60 0 0 373.75-106.25-106.25L326.216 730l177.5 177.5 178.75-178.75L639.966 687.5 533.716 793.75zM297.466 835 238.716 835c-98.75 0-178.75-80-178.75-178.75S139.966 477.5 238.716 477.5c1.25 0 2.5 0 2.5 0l28.75 0c1.25 0 11.25 1.25 21.25-10 10-11.25 6.25-21.25 6.25-33.75 0-148.75 121.25-270 268.75-270 70 0 133.75 26.25 181.25 70 5 5 3.75 5 10 10 6.25 8.75 15 13.75 26.25 13.75 16.25 0 30-13.75 30-30 0-10-5-18.75-12.5-26.25-5-5-3.75-3.75-10-8.75-58.75-56.25-137.5-90-225-90-176.25 0-320 138.75-328.75 312.5-131.25 0-237.5 106.25-237.5 237.5s106.25 237.5 237.5 237.5l57.5 0c16.25 0 30-13.75 30-30C326.216 847.5 313.716 835 297.466 835L297.466 835z",fill:t})}),labelKey:"navBackup",label:"数据管理"},{id:wr,Icon:st,labelKey:"navPermissions",label:"权限管理"},{id:xr,Icon:lt,labelKey:"navAbout",label:"关于"}],aS=({isOpen:e,onClose:t,siteId:n})=>{const[r,o]=z(gr),[i,a]=z(void 0),[s,l]=z(null),[c,d]=z(false),{settings:u}=Ai(),h=Ei(),g=P(null),p=P(null),m=P(void 0),f=P(null);if(_(()=>{h&&u?.language&&ie(u.language);},[h,u?.language]),_(()=>{g.current&&(g.current.scrollTop=0);},[r]),_(()=>{if(!e)return;const n=e=>{"Escape"===e.key&&t();};return document.addEventListener("keydown",n),()=>document.removeEventListener("keydown",n)},[e,t]),_(()=>{const e=e=>{const t=(e=>{const t=zr(e.settingId),n=Br(t);return {page:e.page??n?.page,subTab:e.subTab??(e.page&&e.page!==n?.page?void 0:n?.subTab),settingId:t}})(e.detail||{});t.page&&iS.some(e=>e.id===t.page)&&o(t.page),a(t.subTab),t.settingId?l({settingId:t.settingId,token:Date.now()}):l(null);};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[]),_(()=>{if(!e||!s?.settingId)return;let t,n,r=false;const o=`[data-setting-id="${"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(s.settingId):JSON.stringify(s.settingId).slice(1,-1)}"]`,i=e=>{if(r)return;const n=g.current?.querySelector(o);return n?(void 0!==m.current&&(window.clearTimeout(m.current),m.current=void 0),f.current&&f.current!==n&&f.current.classList.remove("setting-locate-highlight"),n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.remove("setting-locate-highlight"),n.offsetWidth,n.classList.add("setting-locate-highlight"),f.current=n,m.current=window.setTimeout(()=>{n.classList.remove("setting-locate-highlight"),f.current===n&&(f.current=null),m.current=void 0;},2200),void l(null)):e>=12?(console.warn(`[Ophel] Failed to locate setting: ${s.settingId}`),void l(null)):void(t=window.setTimeout(()=>i(e+1),100))};return n=window.requestAnimationFrame(()=>i(0)),()=>{r=true,void 0!==n&&window.cancelAnimationFrame(n),void 0!==t&&window.clearTimeout(t);}},[e,r,i,s]),_(()=>()=>{ void 0!==m.current&&window.clearTimeout(m.current),f.current&&(f.current.classList.remove("setting-locate-highlight"),f.current=null);},[]),_(()=>{if(e){const e=p.current;if(!e)return;return es(e)}},[e,n]),_(()=>e?(document.body.style.overflow="hidden",()=>{document.body.style.overflow="";}):(document.body.style.overflow="",()=>{document.body.style.overflow="";}),[e]),!e)return null; return Ie("div",{className:"settings-modal-overlay",...Za,onClick:t,children:Le("div",{ref:p,className:"settings-modal-container "+(c?"maximized":""),onClick:e=>e.stopPropagation(),children:[ Le("div",{className:"settings-modal-actions",children:[ Ie(up,{content:se(c?"restore":"maximize"),children:Ie("button",{className:"settings-modal-action-btn",onClick:()=>d(!c),children:Ie(c?St:kt,{size:16})})}), Ie(up,{content:se("close"),children:Ie("button",{className:"settings-modal-action-btn close",onClick:t,children:Ie(Re,{size:16})})})]}), Le("aside",{className:"settings-sidebar",children:[ Ie("div",{className:"settings-sidebar-header",children:Le("div",{className:"settings-sidebar-logo",children:[ Ie("img",{src:Tw,alt:Aw}), Ie("span",{children:Aw})]})}), Le("nav",{className:"settings-sidebar-nav",children:[iS.filter(e=>!(!qi.hasCapability("permissions")&&e.id===wr)).map(e=>Le("button",{className:"settings-nav-item "+(r===e.id?"active":""),onClick:()=>{o(e.id),a(void 0),l(null);},children:[ Ie("span",{className:"settings-nav-item-icon",children:Ie(e.Icon,{size:22})}), Ie("span",{children:oS(e.labelKey,e.label)})]},e.id)), Ie(qx,{})]}), Ie(zx,{siteId:n})]}), Ie("main",{className:"settings-content",ref:g,children:(()=>{if(!u||!h) return Ie("div",{style:{padding:40,textAlign:"center"},children:se("loading")});switch(r){case gr: return Ie(jk,{siteId:n,initialTab:i});case fr: return Ie(rS,{siteId:n,initialTab:i});case pr: return Ie(ek,{siteId:n,initialTab:i});case mr: return Ie(Ok,{siteId:n,initialTab:i});case br: return Ie($k,{siteId:n});case yr: return Ie(Kk,{siteId:n});case wr: return Ie(Qk,{siteId:n});case vr: return Ie(vk,{siteId:n,onNavigate:o});case xr: return Ie(Hx,{});default: return Ie(jk,{siteId:n,initialTab:i})}})()})]})})},sS=e=>{const{isOpen:t,onClose:n,inputRef:r,resultsRef:i,activeOptionId:a,inputValue:s,inputPlaceholder:l,onInputChange:c,hotkeyLabel:d,fuzzySearchToggleLabel:u,fuzzySearchToggleAriaLabel:h,isFuzzySearchEnabled:g,onToggleFuzzySearch:p,syntaxHelpTriggerRef:m,syntaxHelpPopoverRef:f,showSyntaxHelp:b,onToggleSyntaxHelp:y,syntaxHelpTriggerAriaLabel:v,syntaxHelpTitle:w,syntaxHelpDescription:x,syntaxHelpItems:k,onApplySyntaxHelpItem:S,activeFilterChips:C,hasOverflowFilterChips:A,overflowFilterChipText:E,filterChipRemoveTitle:T,clearFiltersLabel:M,onRemoveFilterChip:_,onClearAllFilterChips:I,shouldShowSyntaxSuggestions:L,syntaxSuggestions:N,activeSyntaxSuggestionIndex:D,onHoverSyntaxSuggestion:q,onApplySyntaxSuggestion:R,syntaxDiagnostics:P,resolveSyntaxDiagnosticTitle:z,showShortcutNudge:B,shortcutNudgeMessage:O,closeLabel:F,dismissShortcutNudgeLabel:$,onHideShortcutNudge:U,onDismissShortcutNudgeForever:j,categoriesLabel:H,categories:W,activeCategoryId:G,onSelectCategory:Q,activeContext:V,listboxId:K,listboxLabel:Z,onResultsWheel:Y,visibleResults:J,groupedResults:X,getGroupLabel:ee,allCategoryItemLimit:te,isAllCategory:ne,emptyText:re,emptyGuideTitle:oe,emptyGuideDescription:ie,emptyGuideExamples:ae,renderSearchResultItem:se,resolveVisibleResultIndex:le,collapseLabel:ce,moreLabel:de,onToggleCategoryGroup:ue,footerTips:he,promptPreview:ge}=e,pe=o.useRef(null);return o.useEffect(()=>{if(!t)return;const e=pe.current;return e?es(e):void 0},[t]),t?Le("div",{className:"settings-search-overlay gh-interactive",onClick:n,children:[ Le("div",{ref:pe,className:"settings-search-modal",onClick:e=>e.stopPropagation(),children:[ Le("div",{className:"settings-search-input-wrap",children:[ Ie(Wt,{size:16}), Ie("button",{type:"button",className:"settings-search-fuzzy-toggle "+(g?"active":""),"aria-pressed":g,"aria-label":h,onClick:p,children:u}), Ie("input",{ref:r,className:"settings-search-input",role:"combobox","aria-autocomplete":"list","aria-expanded":true,"aria-haspopup":"listbox","aria-controls":K,"aria-activedescendant":a,value:s,onChange:e=>{c(e.target.value);},placeholder:l}), Le("span",{className:"settings-search-hotkey",children:["⌨ ",d]}), Le("div",{className:"settings-search-help",children:[ Ie("button",{ref:m,type:"button",className:"settings-search-help-trigger "+(b?"active":""),"aria-expanded":b,"aria-label":v,onClick:y,children:"?"}),b?Le("div",{ref:f,className:"settings-search-help-popover",role:"dialog","aria-label":w,children:[ Ie("div",{className:"settings-search-help-title",children:w}), Ie("div",{className:"settings-search-help-tip",children:x}), Ie("div",{className:"settings-search-help-items",children:k.map(e=>Le("button",{type:"button",className:"settings-search-help-item",onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),S(e);},children:[ Ie("span",{className:"settings-search-help-token",children:e.token}), Ie("span",{className:"settings-search-help-desc",children:e.description})]},e.id))})]}):null]})]}),C.length>0?Le("div",{className:"settings-search-filter-chips","aria-label":"active search filters",children:[C.map(e=>Le("button",{type:"button",className:"settings-search-filter-chip",onClick:()=>_(e.id),title:T,children:[ Ie("span",{className:"settings-search-filter-chip-label",children:e.label}), Ie("span",{className:"settings-search-filter-chip-close","aria-hidden":true,children:"×"})]},e.id)),A?Ie("span",{className:"settings-search-filter-chip-overflow",children:E}):null, Ie("button",{type:"button",className:"settings-search-filter-chip-clear-all",onClick:I,children:M})]}):null,L?Ie("div",{className:"settings-search-syntax-suggestions",role:"listbox",children:N.map((e,t)=>Le("button",{type:"button",role:"option","aria-selected":D===t,className:"settings-search-syntax-suggestion "+(D===t?"active":""),onMouseEnter:()=>q(t),onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),R(e);},children:[ Ie("span",{className:"settings-search-syntax-suggestion-token",children:e.label}), Ie("span",{className:"settings-search-syntax-suggestion-desc",children:e.description})]},e.id))}):null,P.length>0?Ie("div",{className:"settings-search-syntax-diagnostics",role:"status","aria-live":"polite",children:P.map(e=>Le("div",{className:"settings-search-syntax-diagnostic",children:[ Ie("span",{className:"settings-search-syntax-diagnostic-title",children:z(e.code)}), Le("span",{className:"settings-search-syntax-diagnostic-detail",children:[e.operator,e.value?`:${e.value}`:"",e.suggestion?` → ${e.suggestion}:`:""]})]},e.id))}):null,B&&O?Le("div",{className:"settings-search-shortcut-nudge",role:"status","aria-live":"polite",children:[ Ie("span",{className:"settings-search-shortcut-nudge-text",children:O}), Ie("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:U,children:F}), Ie("button",{type:"button",className:"settings-search-shortcut-nudge-action",onClick:j,children:$})]}):null,W.length>0?Ie("div",{className:"settings-search-categories",role:"tablist","aria-label":H,children:W.map(e=>Le("button",{type:"button",role:"tab","aria-selected":G===e.id,className:"settings-search-category "+(G===e.id?"active":""),onClick:()=>Q(e.id),children:[ Ie("span",{children:e.label}), Ie("span",{className:"settings-search-category-count",children:null==e.count?"-":e.count})]},e.id))}):null,V?Le("div",{className:"settings-search-context-bar",children:[ Ie("span",{className:"settings-search-context-label",children:V.label}), Ie("span",{className:"settings-search-context-meta",children:V.meta})]}):null, Ie("div",{id:K,className:"settings-search-results",role:"listbox","aria-label":Z,ref:i,onWheel:Y,children:0===J.length?Le("div",{className:"settings-search-empty",children:[ Ie("div",{children:re}), Ie("div",{className:"settings-search-empty-guide-title",children:oe}), Ie("div",{className:"settings-search-empty-guide-desc",children:ie}), Ie("div",{className:"settings-search-empty-guide-examples",children:ae.map(e=>Ie("button",{type:"button",className:"settings-search-empty-guide-example",onMouseDown:e=>{e.preventDefault(),e.stopPropagation();},onClick:t=>{t.preventDefault(),t.stopPropagation(),e.onClick();},children:e.token},e.id))})]}):ne?X.map(e=>Le("section",{className:"settings-search-group",children:[ Le("div",{className:"settings-search-group-title",children:[ Ie("span",{children:ee(e.category)}),e.totalCount>te?Le("span",{className:"settings-search-group-count",children:[e.items.length,"/",e.totalCount]}):null]}),e.items.map((e,t)=>se(e,le(e,t))),e.hasMore||e.isExpanded?Ie("button",{type:"button",className:"settings-search-group-more",onClick:()=>ue(e.category),children:e.isExpanded?ce:`${de} (+${e.remainingCount})`}):null]},e.category)):J.map((e,t)=>se(e,t))}), Ie("div",{className:"settings-search-footer",children:he})]}),ge]}):null},lS=new Map,cS=(e,t,n)=>{const r=((e,t)=>{if(!e||0===t.length)return [];const n=e.toLowerCase(),r=[];if(t.forEach(e=>{if(!e)return;let t=0;for(;te.start!==t.start?e.start-t.start:e.end-t.end);const o=[];return r.forEach(e=>{const t=o[o.length-1];!t||e.start>t.end?o.push({...e}):e.end>t.end&&(t.end=e.end);}),o})(e,t),o=((e,t)=>{if(!e||!t||0===t.length)return [];const n=Array.from(new Set(t.map(e=>Number(e)).filter(t=>Number.isInteger(t)&&t>=0&&te-t);if(0===n.length)return [];const r=[];let o=n[0],i=n[0];for(let a=1;a{for(let t=e.start;t{for(let t=e.start;te.text.length>0)},dS=o.memo(({item:e,index:t,optionIdPrefix:n,isActive:r,highlightTokens:i,outlineRoleLabels:a,matchReasonLabels:s,onMouseMove:l,onMouseEnter:c,onMouseLeave:d,onClick:u})=>{const h=(e,t="default",n)=>{const r=((e,t,n)=>{if(!e)return [];const r=((e,t,n)=>`${e}\0${t.join("\0")}\0${n?n.join(","):""}`)(e,t,n),o=lS.get(r);if(o)return o;const i=cS(e,t,n);if(lS.size>=500){const e=lS.keys().next().value;void 0!==e&&lS.delete(e);}return lS.set(r,i),i})(e,i,n);return r.map((e,n)=>{if("none"===e.matchType) return Ie(o.Fragment,{children:e.text},`plain-${n}-${e.text.length}`);const r=["settings-search-highlight","tag"===t?"settings-search-highlight-tag":"","code"===t?"settings-search-highlight-code":"","fuzzy"===e.matchType?"settings-search-highlight-fuzzy":""].filter(Boolean).join(" "); return Ie("mark",{className:r,children:e.text},`highlight-${n}-${e.text.length}`)})},g="outline"===e.category&&Boolean(e.outlineTarget),p="conversations"===e.category,m="prompts"===e.category,f=Boolean(e.tipId),b=g&&Boolean(e.outlineTarget?.isUserQuery),y=b?a.query:a.reply,v=Boolean(e.code)&&!g,w=e.fuzzyMatch?.field,x="title"===w?e.fuzzyMatch?.indexes:void 0,k="breadcrumb"===w?e.fuzzyMatch?.indexes:void 0,S="snippet"===w?e.fuzzyMatch?.indexes:void 0,C="code"===w?e.fuzzyMatch?.indexes:void 0,A="prompts"===e.category&&e.matchReasons?.includes("content")?`${s.content}: `:"",E=e.matchReasons&&e.matchReasons.length>0?e.matchReasons.map(e=>({reason:e,label:s[e]})):[]; return Le("div",{id:`${n}-${t}`,role:"option","aria-selected":r,tabIndex:-1,"data-global-search-index":t,"data-global-search-item-id":e.id,className:`settings-search-item ${r?"active":""} ${f?"tip-item":""} ${g?b?"outline-item outline-query":"outline-item outline-reply":""} ${p?"conversation-item":""}`.trim(),onMouseMove:l,onMouseEnter:e=>{m&&c(e);},onMouseLeave:()=>{m&&d();},onClick:u,children:[ Ie("div",{className:"settings-search-item-title",title:e.title,children:f?Le("div",{className:"gs-tip-item-head",children:[ Ie("span",{className:"gs-tip-icon","aria-hidden":"true",children:"💡"}), Ie("span",{className:"settings-search-item-title-text",children:h(e.title,"default",x)})]}):g?Le("div",{className:"settings-search-outline-head",children:[ Ie("span",{className:"settings-search-outline-role "+(b?"query":"reply"),title:y,children:y}),e.code?Ie("span",{className:"settings-search-outline-code",title:e.code,children:h(e.code,"code",C)}):null, Ie("span",{className:"settings-search-item-title-text",children:h(e.title,"default",x)})]}):Ie("span",{className:"settings-search-item-title-text",children:h(e.title,"default",x)})}),e.snippet?Le("div",{className:"settings-search-item-snippet",title:`${A}${e.snippet}`,children:[A?Ie("span",{className:"settings-search-item-snippet-prefix",children:A}):null,h(e.snippet,"default",S)]}):null, Le("div",{className:("settings-search-item-meta "+(v?"":"no-code")).trim(),children:[ Le("div",{className:"settings-search-item-meta-left",children:[ Ie("span",{className:"settings-search-item-breadcrumb",title:e.breadcrumb,children:h(e.breadcrumb,"default",k)}),"conversations"===e.category&&e.tagBadges&&e.tagBadges.length>0?Ie("div",{className:"settings-search-tag-list",children:e.tagBadges.map(e=>Ie("span",{className:"settings-search-tag",style:{backgroundColor:e.color},title:e.name,children:h(e.name,"tag")},e.id))}):null,E.length>0?Ie("div",{className:"settings-search-match-reason-list",children:E.map(e=>Ie("span",{className:"settings-search-match-reason-badge",children:e.label},e.reason))}):null]}),v?Ie("code",{title:e.code,children:h(e.code,"code",C)}):null]})]})}),uS=["type","folder","tag","is","level","date"],hS=["outline","conversations","prompts","settings"],gS=["pinned","unpinned"],pS=["0","1","2","3","4","5","6"],mS=["7d","30d"],fS=e=>e.trim().toLowerCase(),bS=e=>fS(e).split(" ").map(e=>e.trim()).filter(e=>e.length>0),yS=e=>e?e.replace(/^"|"$/g,"").replace(/\\([\\"\s:])/g,"$1").trim():"",vS=e=>{const t=e.trim().toLowerCase().match(/^(\d{1,3})d$/);if(!t)return null;const n=Number(t[1]);return !Number.isFinite(n)||n<=0?null:n},wS=(e,t)=>{const n=e.normalizedValue;return "type"===e.key?t.some(e=>"type"===e.key&&e.normalizedValue!==n):"is"===e.key?t.some(e=>"is"===e.key&&e.normalizedValue!==n):"level"===e.key?t.some(e=>"level"===e.key&&e.normalizedValue!==n):"date"===e.key&&t.some(e=>"date"===e.key&&e.normalizedValue!==n)},xS=(e,t)=>!!t&&("type"===e?hS.includes(t):"is"===e?gS.includes(t):"level"===e?pS.includes(t):"date"!==e||null!==vS(t)),kS=e=>"type"===e?"outline | conversations | prompts | settings":"is"===e?"pinned | unpinned":"level"===e?"0 ~ 6":"date"===e?"Nd (e.g. 7d, 30d)":void 0,SS=(e,t,n)=>`${e}:${t}:${n}`,CS=e=>{const t=e.trim().toLowerCase();if(!t)return null;const n=uS.find(e=>e.startsWith(t));if(n)return n;const r=uS.find(e=>t.startsWith(e));return r||null},AS=e=>{const t=e.match(/(^|\s)([^\s]*)$/);if(!t)return null;const n=t[2]||"",r=e.length;return {token:n,start:r-n.length,end:r}},ES=globalThis.fuzzysort,TS=ES&&"function"==typeof ES.single?ES:{single:()=>null,go:()=>[],prepare:e=>e,cleanup:()=>{}},MS=[{id:"passthrough"},{id:"panel-mode-toggle",highlightTarget:"header-title",shortcutIds:["togglePanelMode"]},{id:"shortcuts",highlightTarget:"shortcuts-btn",shortcutIds:["showShortcuts"]},{id:"global-search",highlightTarget:"search-btn",shortcutIds:["openGlobalSearch"]},{id:"copy-reply",shortcutIds:["copyLatestReply"]},{id:"prev-next-heading",highlightTarget:"outline-tab",shortcutIds:["prevHeading","nextHeading"]},{id:"export-conv",highlightTarget:"conversations-tab"},{id:"batch-select",highlightTarget:"conversations-tab"},{id:"export-markdown",highlightTarget:"toolbar-btn"},{id:"show-user-query",highlightTarget:"outline-tab"},{id:"notifications",highlightTarget:"settings-btn"}],_S=["outline","conversations","prompts","settings","tips"],IS=Object.entries(Pr).reduce((e,[t,n])=>(e[n]||(e[n]=[]),e[n].push(t),e),{}),LS=e=>{if("inbox"===e.id)return (()=>{const e=se("conversationsInbox");return "conversationsInbox"===e?"Inbox":e})();const t=(e.name||"").trim(),n=(e.icon||"").trim();return n&&t.startsWith(n)?t.slice(n.length).trim():t},NS=({normalizedQuery:e,fields:t})=>{if(!e)return null;let n=null;const r=e.length>=8?2:1;return t.forEach(t=>{if(!t.value)return;const r=TS.single(e,t.value);!r||r.score<.24||(!n||r.score>n.score)&&(n={score:r.score,matchReason:t.matchReason,highlightField:t.highlightField,indexes:Array.from(r.indexes||[]),isTypoFallback:false});}),n||(e.length<4?null:(t.forEach(t=>{if(!t.value)return;var o;((o=t.value)?o.split(/[^a-z0-9\u4e00-\u9fff]+/gi).map(e=>e.trim()).filter(e=>e.length>0):[]).forEach(o=>{if(Math.abs(o.length-e.length)>r)return;const i=((e,t,n)=>{const r=e.length,o=t.length;if(e===t)return 0;if(Math.abs(r-o)>n)return n+1;const i=new Array(o+1).fill(0),a=new Array(o+1),s=new Array(o+1);for(let l=0;l<=o;l+=1)a[l]=l;for(let l=1;l<=r;l+=1){s[0]=l;let r=s[0];for(let n=1;n<=o;n+=1){const o=e[l-1]===t[n-1]?0:1;let c=Math.min(a[n]+1,s[n-1]+1,a[n-1]+o);l>1&&n>1&&e[l-1]===t[n-2]&&e[l-2]===t[n-1]&&(c=Math.min(c,i[n-2]+1)),s[n]=c,cn)return n+1;for(let e=0;e<=o;e+=1)i[e]=a[e],a[e]=s[e];}return a[o]})(e,o,r);if(i>r)return;const a=Math.max(.24,.58-.14*i-.03*Math.abs(o.length-e.length));(!n||a>n.score)&&(n={score:a,matchReason:t.matchReason,highlightField:t.highlightField,indexes:void 0,isTypoFallback:true});});}),n))},DS=({normalizedQuery:e,tokens:t,index:n,fields:r,enableFuzzySearch:o,baseScoreWhenEmpty:i=1e3})=>{const a=r.map(e=>e.value).join(" "),s=t.every(e=>a.includes(e)),l=o&&e?NS({normalizedQuery:e,fields:r}):null;if(!s&&!l)return null;if(!e)return {score:i-n,matchLevel:0,exactHitCount:0,prefixHitCount:0,includesHitCount:0,matchReasons:[]};let c=0,d=0,u=0,h=0,g=0;const p=new Set;r.forEach(n=>{const r=n.value;if(!r)return;let o=0,i=false,a=false;r===e?(c+=n.exact,o=3,u+=1):r.startsWith(e)?(c+=n.prefix,o=2,h+=1):r.includes(e)&&(c+=n.includes,o=1,g+=1),d=Math.max(d,o),o>0&&n.matchReason&&p.add(n.matchReason),t.forEach(e=>{r.startsWith(e)&&(c+=n.tokenPrefix,i=true),r.includes(e)&&(c+=n.tokenIncludes,a=true);}),0===o?i?(d=Math.max(d,2),h+=1,n.matchReason&&p.add(n.matchReason)):a&&(d=Math.max(d,1),g+=1,n.matchReason&&p.add(n.matchReason)):d=Math.max(d,o);});const m=Boolean(l&&0===d);if(m&&l){const e=Math.round(64*l.score);c+=e+16,p.add("fuzzy"),l.matchReason&&p.add(l.matchReason);}return 0!==d||l?{score:c,matchLevel:d,exactHitCount:u,prefixHitCount:h,includesHitCount:g,matchReasons:Array.from(p),fuzzyMatch:m?{field:l?.highlightField,indexes:l?.indexes,isTypoFallback:l?.isTypoFallback}:void 0}:null},qS=(e,t)=>{if(t.scoreMeta.matchLevel!==e.scoreMeta.matchLevel)return t.scoreMeta.matchLevel-e.scoreMeta.matchLevel;if(t.scoreMeta.exactHitCount!==e.scoreMeta.exactHitCount)return t.scoreMeta.exactHitCount-e.scoreMeta.exactHitCount;if(t.scoreMeta.prefixHitCount!==e.scoreMeta.prefixHitCount)return t.scoreMeta.prefixHitCount-e.scoreMeta.prefixHitCount;if(t.scoreMeta.includesHitCount!==e.scoreMeta.includesHitCount)return t.scoreMeta.includesHitCount-e.scoreMeta.includesHitCount;if(t.scoreMeta.score!==e.scoreMeta.score)return t.scoreMeta.score-e.scoreMeta.score;const n=e.recency||0,r=t.recency||0;return r!==n?r-n:e.index-t.index},RS=({activeGlobalSearchPlainQuery:e,enableFuzzySearch:t,activeGlobalSearchSyntaxFilters:n,settingsSearchResults:r,resolveSettingSearchTitle:o,getSettingsBreadcrumb:i,conversationManager:a,conversationsSnapshot:s,foldersSnapshot:l,tagsSnapshot:c,promptsSnapshot:d,outlineManager:u,outlineSearchVersion:h,getLocalizedText:g,resolveShortcutLabel:p,passThroughModifierLabel:m,activeGlobalSearchCategory:f,expandedGlobalSearchCategories:b,allCategoryItemLimit:y})=>{const v=e.trimStart(),w=v.startsWith("tip:")||"tips"===f,x=q(()=>{if(!w)return [];const e=v.startsWith("tip:")?v.slice(4).trim().toLowerCase():v.trim().toLowerCase(),t=g({key:"featureTipsCategory",fallback:"Feature Tips"}),n=g({key:"featureTipShortcutNotConfigured",fallback:"Shortcut not configured"}),r=(e,t,r)=>se(`featureTip-${e}-${t}`,{modifier:m,shortcut:r.length>0?r.join(" / "):n});return MS.map(e=>{const n=e.shortcutIds?.map(e=>p(e)).filter(e=>Boolean(e))??[],o=r(e.id,"title",n),i=r(e.id,"desc",n),a=r(e.id,"path",n),s=n.join(" / "),l=s?`${i} [${s}]`:i;return {id:`tips:${e.id}`,title:o,breadcrumb:`${t} / ${a}`,snippet:l,category:"tips",tipId:e.id,tipHighlightTarget:e.highlightTarget,tipActionText:a,tipShortcutIds:e.shortcutIds}}).filter(t=>!e||[t.title,t.snippet,t.tipActionText].filter(e=>Boolean(e)).some(t=>t.toLowerCase().includes(e)))},[f,g,w,m,p,v]),k=q(()=>{if(w)return [];const n=fS(e),a=bS(e);return r.map((e,r)=>{const s=o(e),l=fS(s),c=fS((e.keywords||[]).join(" ")),d=fS(e.settingId),u=fS((IS[e.settingId]||[]).join(" ")),h=DS({normalizedQuery:n,tokens:a,index:r,enableFuzzySearch:t,fields:[{value:l,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:c,exact:0,prefix:0,includes:68,tokenPrefix:0,tokenIncludes:8,matchReason:"keyword"},{value:d,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"id",highlightField:"code"},{value:u,exact:0,prefix:0,includes:44,tokenPrefix:0,tokenIncludes:6,matchReason:"alias"}]});return null===h?null:{item:{id:`settings:${e.settingId}`,title:s,breadcrumb:i(e.settingId),code:e.settingId,category:"settings",settingId:e.settingId,matchReasons:h.matchReasons,fuzzyMatch:h.fuzzyMatch},scoreMeta:h,index:r}}).filter(e=>Boolean(e)).sort(qS).map(({item:e})=>e)},[e,t,i,w,o,r]),S=q(()=>{if(!a||w)return [];const n=a.getConversations(),r=a.getFolders(),o=a.getTags(),i=new Map(r.map(e=>[e.id,e])),s=new Map(o.map(e=>[e.id,e])),l=fS(e),c=bS(e),d=g({key:"untitledConversation",fallback:"Untitled conversation"});return n.map((e,n)=>{const r=e.title?.trim()||d,o=i.get(e.folderId),a=o?`${o.icon?`${o.icon} `:""}${LS(o)}`.trim():e.folderId,u=(e.tagIds||[]).map(e=>{const t=s.get(e);return t?{id:t.id,name:t.name,color:t.color}:null}).filter(e=>Boolean(e)),h=fS(r),g=fS(a),p=fS(u.map(e=>e.name).join(" ")),m=DS({normalizedQuery:l,tokens:c,index:n,enableFuzzySearch:t,fields:[{value:h,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:72,tokenPrefix:0,tokenIncludes:8,matchReason:"folder",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:64,tokenPrefix:0,tokenIncludes:8,matchReason:"tag"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)};return {item:{id:`conversations:${e.id}`,title:r,breadcrumb:a,category:"conversations",conversationId:e.id,conversationUrl:e.url,tagBadges:u,folderName:a,tagNames:u.map(e=>e.name),isPinned:Boolean(e.pinned),searchTimestamp:e.updatedAt||0,matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch},scoreMeta:f,index:n,recency:e.updatedAt||0}}).filter(e=>Boolean(e)).sort(qS).map(({item:e})=>e)},[a,s,l,c,g,e,t,w]),C=q(()=>{if(w)return [];const n=fS(e),r=bS(e),o=g({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),i=g({key:"uncategorized",fallback:"Uncategorized"}),a=d.map((e,a)=>{const s=e.title?.trim()||e.content?.trim().split("\n")[0]||`${o} #${a+1}`,l=e.content?.trim()||"",c=e.category?.trim()||i,d=`${o} / ${c}`,u=fS(s),h=fS(l),g=fS(c),p=fS(e.id),m=DS({normalizedQuery:n,tokens:r,index:a,enableFuzzySearch:t,fields:[{value:u,exact:220,prefix:140,includes:100,tokenPrefix:24,tokenIncludes:12,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:70,tokenPrefix:0,tokenIncludes:8,matchReason:"category",highlightField:"breadcrumb"},{value:h,exact:0,prefix:0,includes:60,tokenPrefix:0,tokenIncludes:6,matchReason:"content",highlightField:"snippet"},{value:p,exact:0,prefix:0,includes:20,tokenPrefix:0,tokenIncludes:4,matchReason:"id",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.pinned?6:0)},b=f.matchReasons.includes("content")?(({content:e,normalizedQuery:t,tokens:n,maxLength:r=84})=>{const o=e.replace(/\s+/g," ").trim();if(!o)return "";const i=Array.from(new Set([t,...n])).filter(Boolean),a=o.toLowerCase();let s=-1;if(i.forEach(e=>{const t=a.indexOf(e);-1!==t&&(-1===s||tr?`${o.slice(0,r).trim()}…`:o;let l=Math.max(0,s-Math.floor(.25*r));const c=Math.min(o.length,l+r);return c>=o.length&&(l=Math.max(0,o.length-r)),`${l>0?"…":""}${o.slice(l,c).trim()}${cBoolean(e)).sort(qS);return a.map(({item:e})=>e)},[e,t,g,w,d]),A=q(()=>{if(!u||w)return [];const n=(e=>{const t=[],n=e=>{e.forEach(e=>{t.push(e),e.children&&e.children.length>0&&n(e.children);});};return n(e),t})(u.getTree()),r=fS(e),o=bS(e),i=g({key:"globalSearchCategoryOutline",fallback:"Outline"}),a=g({key:"outlineOnlyUserQueries",fallback:"Queries"}),s=g({key:"globalSearchOutlineReplies",fallback:"Replies"});return n.map((e,n)=>{const l=e.text?.trim();if(!l)return null;const c=e.isUserQuery?`Q${e.queryIndex??n+1}`:`H${e.level}`,d=e.isUserQuery?a:s,u=e.isUserQuery?`${i} / ${d}`:`${i} / ${d} / H${e.level}`,h=fS(l),g=fS(e.isUserQuery?d:`${d} h${e.level}`),p=fS(c),m=DS({normalizedQuery:r,tokens:o,index:n,enableFuzzySearch:t,fields:[{value:h,exact:200,prefix:120,includes:90,tokenPrefix:16,tokenIncludes:10,matchReason:"title",highlightField:"title"},{value:g,exact:0,prefix:0,includes:48,tokenPrefix:0,tokenIncludes:6,matchReason:"type",highlightField:"breadcrumb"},{value:p,exact:0,prefix:0,includes:36,tokenPrefix:0,tokenIncludes:4,matchReason:"code",highlightField:"code"}]});if(null===m)return null;const f={...m,score:m.score+(e.isBookmarked?4:0)};return {item:{id:`outline:${e.index}`,title:l,breadcrumb:u,code:c,category:"outline",matchReasons:f.matchReasons,fuzzyMatch:f.fuzzyMatch,outlineTarget:{index:e.index,level:e.level,text:l,isUserQuery:Boolean(e.isUserQuery),id:e.id,navigationId:e.navigationId,queryIndex:e.queryIndex,isGhost:Boolean(e.isGhost),scrollTop:e.scrollTop}},scoreMeta:f,index:n}}).filter(e=>Boolean(e)).sort(qS).map(({item:e})=>e)},[e,t,u,g,h,w]),E=q(()=>[...x,...k,...S,...A,...C],[x,S,A,C,k]),T=q(()=>E.filter(e=>((e,t)=>0===t.length||t.every(t=>{const n=t.normalizedValue;if("type"===t.key)return e.category.toLowerCase().includes(n);if("folder"===t.key)return (e.folderName||e.breadcrumb||"").toLowerCase().includes(n);if("tag"===t.key)return (e.tagNames||e.tagBadges?.map(e=>e.name)||[]).some(e=>e.toLowerCase().includes(n));if("is"===t.key)return "pinned"===n?Boolean(e.isPinned):"unpinned"===n&&!e.isPinned;if("level"===t.key)return "outline"===e.category&&String(e.outlineTarget?.level??"")===n;if("date"===t.key){if("conversations"!==e.category&&"prompts"!==e.category)return false;const t=vS(n);if(null===t)return false;const r=e.searchTimestamp||0;return !(r<=0)&&Date.now()-r<=864e5*t}return true}))(e,n)),[n,E]),M=q(()=>{const e={all:0,outline:0,conversations:0,prompts:0,settings:0,tips:0};return T.forEach(t=>{e[t.category]+=1,e.all+=1;}),e},[T]),_=q(()=>"all"!==f?[]:_S.map(e=>{const t=T.filter(t=>t.category===e),n=Boolean(b[e]),r=n?t.length:y,o=t.slice(0,r),i=Math.max(0,t.length-o.length);return {category:e,items:o,totalCount:t.length,hasMore:i>0,isExpanded:n,remainingCount:i}}).filter(e=>e.items.length>0),[f,y,b,T]),I=q(()=>"all"!==f?T.filter(e=>e.category===f):_.flatMap(e=>e.items),[f,T,_]);return {filteredGlobalSearchResults:T,globalSearchResultCounts:M,groupedGlobalSearchResults:_,visibleGlobalSearchResults:I}},PS={"loading-history":"exportOverlayLoadingHistory",preparing:"exportOverlayPreparing",extracting:"exportOverlayExtracting",packaging:"exportOverlayPackaging",downloading:"exportOverlayDownloading",copying:"exportOverlayCopying",restoring:"exportOverlayRestoring"},zS={[gr]:{key:"navGeneral",fallback:"General"},[mr]:{key:"navFeatures",fallback:"Features"},[fr]:{key:"navSiteSettings",fallback:"Site Config"},[br]:{key:"navGlobalSearch",fallback:"Global Search"},[pr]:{key:"navAppearance",fallback:"Appearance"},[yr]:{key:"navShortcuts",fallback:"Keyboard Shortcuts"},[vr]:{key:"navBackup",fallback:"Data Management"},[wr]:{key:"navPermissions",fallback:"Permissions"},[xr]:{key:"navAbout",fallback:"About"}},BS={panel:{key:"panelTab",fallback:"Panel"},tabOrder:{key:"tabOrderTab",fallback:"Tab Order"},shortcuts:{key:"shortcutsTab",fallback:"Quick Buttons"},toolsMenu:{key:"toolboxMenu",fallback:"Toolbox"},[Ar]:{key:"tabSettingsTab",fallback:"Tab Settings"},[Er]:{key:"reminderTab",fallback:"Alerts"},[kr]:{key:"outlineSettingsTitle",fallback:"Outline"},[Sr]:{key:"conversationsSettingsTitle",fallback:"Conversations"},[Cr]:{key:"promptSettingsTitle",fallback:"Prompts"},[Mr]:{key:"readingHistorySettings",fallback:"Reading History"},[Tr]:{key:"contentProcessing",fallback:"Content"},[_r]:{key:"toolboxMenu",fallback:"Toolbox"},[Nr]:{key:"layoutTab",fallback:"Layout"},[Dr]:{key:"tabModelLock",fallback:"Model Lock"},gemini:{key:"geminiSettingsTab",fallback:"Gemini"},aistudio:{key:"aistudioSettingsTitle",fallback:"AI Studio"},chatgpt:{key:"chatgptSettingsTitle",fallback:"ChatGPT"},claude:{key:"claudeSettingsTab",fallback:"Claude"},[Ir]:{key:"themePresetsTab",fallback:"Theme Presets"},[Lr]:{key:"customStylesTab",fallback:"Custom Styles"}},OS=new Set(["Meta","OS","Command","Cmd"]),FS=new Set(["Control","Ctrl"]),$S=[{id:"all",label:{key:"globalSearchCategoryAll",fallback:"All"},placeholder:{key:"globalSearchPlaceholderAll",fallback:"Search all"},emptyText:{key:"globalSearchEmptyAll",fallback:"No matching results"}},{id:"outline",label:{key:"globalSearchCategoryOutline",fallback:"Outline"},placeholder:{key:"globalSearchPlaceholderOutline",fallback:"Search outline"},emptyText:{key:"globalSearchEmptyOutline",fallback:"No outline results"}},{id:"conversations",label:{key:"globalSearchCategoryConversations",fallback:"Conversations"},placeholder:{key:"globalSearchPlaceholderConversations",fallback:"Search conversations on current site"},emptyText:{key:"globalSearchEmptyConversations",fallback:"No conversation results"}},{id:"prompts",label:{key:"globalSearchCategoryPrompts",fallback:"Prompts"},placeholder:{key:"globalSearchPlaceholderPrompts",fallback:"Search prompts"},emptyText:{key:"globalSearchEmptyPrompts",fallback:"No prompt results"}},{id:"settings",label:{key:"globalSearchCategorySettings",fallback:"Settings"},placeholder:{key:"globalSearchPlaceholderSettings",fallback:"Search settings"},emptyText:{key:"globalSearchEmptySettings",fallback:"No matching settings"}},{id:"tips",label:{key:"featureTipsCategory",fallback:"Tips"},placeholder:{key:"featureTipSearchPlaceholder",fallback:"Search feature tips…"},emptyText:{key:"globalSearchEmptyTips",fallback:"No matching tips"}}],US={outline:{key:"globalSearchCategoryOutline",fallback:"Outline"},settings:{key:"globalSearchCategorySettings",fallback:"Settings"},conversations:{key:"globalSearchCategoryConversations",fallback:"Conversations"},prompts:{key:"globalSearchCategoryPrompts",fallback:"Prompts"},tips:{key:"featureTipsCategory",fallback:"Tips"}},jS={title:{key:"globalSearchMatchReasonTitle",fallback:"Title match"},folder:{key:"globalSearchMatchReasonFolder",fallback:"Folder match"},tag:{key:"globalSearchMatchReasonTag",fallback:"Tag match"},type:{key:"globalSearchMatchReasonType",fallback:"Type match"},code:{key:"globalSearchMatchReasonCode",fallback:"Code match"},category:{key:"globalSearchMatchReasonCategory",fallback:"Category match"},content:{key:"globalSearchMatchReasonContent",fallback:"Content match"},id:{key:"globalSearchMatchReasonId",fallback:"ID match"},keyword:{key:"globalSearchMatchReasonKeyword",fallback:"Keyword match"},alias:{key:"globalSearchMatchReasonAlias",fallback:"Alias match"},fuzzy:{key:"globalSearchMatchReasonFuzzy",fallback:"Fuzzy match"}},HS="settings-search-option",WS="ophel:global-search-shortcut-nudge:v1",GS={"aistudio-collapse-advanced":"aistudioCollapseAdvanced","aistudio-collapse-navbar":"aistudioCollapseNavbar","aistudio-collapse-run-settings":"aistudioCollapseRunSettings","aistudio-collapse-tools":"aistudioCollapseTools","aistudio-enable-search":"aistudioEnableSearch","aistudio-markdown-fix":"aistudioMarkdownFixLabel","aistudio-remove-watermark":"aistudioRemoveWatermark","appearance-custom-styles":"customCSS","appearance-sync-native-page-theme":"syncNativePageThemeLabel","appearance-preset-dark":"darkModePreset","appearance-preset-light":"lightModePreset","chatgpt-markdown-fix":"chatgptMarkdownFixLabel","conversation-sync-delete":"conversationsSyncDeleteLabel","global-search-fuzzy-search":"globalSearchEnableFuzzySearchLabel","global-search-double-shift":"doubleShiftToSearch","global-search-shortcut-setting-link":"globalSearchShortcutSettingLabel","global-search-prompt-enter-behavior":"globalSearchPromptEnterBehaviorLabel","claude-session-keys":"claudeSessionKeyTitle","content-assistant-mermaid":"assistantMermaidLabel","content-formula-copy":"formulaCopyLabel","content-formula-copy-format":"formulaCopyFormatLabel","content-formula-delimiter":"formulaDelimiterLabel","content-table-copy":"tableCopyLabel","content-user-query-markdown":"userQueryMarkdownLabel","conversation-folder-rainbow":"folderRainbowLabel","conversation-sync-unpin":"conversationsSyncUnpinLabel","export-custom-model-name":"exportCustomModelName","export-custom-user-name":"exportCustomUserName","export-filename-timestamp":"exportFilenameTimestamp","export-include-thoughts":"exportIncludeThoughtsLabel","export-images-base64":"exportImagesToBase64Label","export-packaging":"exportPackagingLabel","gemini-markdown-fix":"markdownFixLabel","gemini-policy-max-retries":"maxRetriesLabel","gemini-policy-retry":"policyRetryLabel","gemini-watermark-removal":"watermarkRemovalLabel","layout-page-width-enabled":"enablePageWidth","layout-page-width-value":"pageWidthValueLabel","layout-user-query-width-enabled":"enableUserQueryWidth","layout-user-query-width-value":"userQueryWidthValueLabel","layout-zen-mode-enabled":"zenModeTitle","outline-auto-update":"outlineAutoUpdateLabel","outline-follow-mode":"outlineFollowModeLabel","outline-inline-bookmark-mode":"inlineBookmarkModeLabel","outline-panel-bookmark-mode":"panelBookmarkModeLabel","outline-prevent-auto-scroll":"preventAutoScrollLabel","outline-show-word-count":"outlineShowWordCountLabel","outline-update-interval":"outlineUpdateIntervalLabel","panel-default-position":"defaultPositionLabel","panel-edge-distance":"defaultEdgeDistanceLabel","panel-edge-snap-threshold":"edgeSnapThresholdLabel","panel-height":"panelHeightLabel","panel-mode":"panelModeLabel","panel-width":"panelWidthLabel","prompt-double-click-send":"promptDoubleClickSendLabel","prompt-queue":"queueSettingLabel","quick-buttons-hide-when-panel-open":"quickButtonsHideWhenPanelOpenLabel","quick-buttons-opacity":"quickButtonsOpacityLabel","quick-buttons-proximity-radius":"quickButtonsProximityRadiusLabel","reading-history-auto-restore":"readingHistoryAutoRestoreLabel","reading-history-cleanup-days":"readingHistoryCleanup","reading-history-persistence":"readingHistoryPersistenceLabel","shortcuts-enabled":"enableShortcuts","shortcuts-global-url":"globalShortcutUrl","shortcuts-browser-shortcuts":"globalShortcutsTitle","shortcuts-prompt-submit-shortcut":"promptSubmitShortcutLabel","tab-auto-focus":"autoFocusLabel","tab-auto-rename":"autoRenameTabLabel","tab-notification-sound":"notificationSoundLabel","tab-notification-sound-preset":"notificationSoundPresetLabel","tab-notification-volume":"notificationVolumeLabel","tab-notification-repeat-count":"notificationRepeatCountLabel","tab-notification-repeat-interval":"notificationRepeatIntervalLabel","tab-notify-when-focused":"notifyWhenFocusedLabel","tab-open-new":"openNewTabLabel","tab-privacy-mode":"privacyModeLabel","tab-privacy-title":"privacyTitleLabel","tab-rename-interval":"renameIntervalLabel","tab-show-notification":"showNotificationLabel","tab-show-status":"showStatusLabel","tab-hide-status-when-read":"hideStatusWhenReadLabel","tab-title-format":"titleFormatLabel","tools-menu-export":"export","tools-menu-copyMarkdown":"exportToClipboard","tools-menu-move":"conversationsMoveTo","tools-menu-setTag":"conversationsSetTag","tools-menu-scrollLock":"shortcutToggleScrollLock","tools-menu-modelLock":"modelLockTitle","tools-menu-cleanup":"cleanup","tools-menu-settings":"tabSettings","usage-monitor-enabled":"usageMonitorEnabledLabel","usage-monitor-daily-limit":"usageMonitorDailyLimitLabel","usage-monitor-auto-reset":"usageMonitorAutoResetLabel"},QS={gemini:{key:"globalSearchSiteGemini",fallback:"Gemini"},"gemini-enterprise":{key:"globalSearchSiteGeminiEnterprise",fallback:"Gemini Enterprise"},aistudio:{key:"globalSearchSiteAIStudio",fallback:"AI Studio"},chatgpt:{key:"globalSearchSiteChatGPT",fallback:"ChatGPT"},claude:{key:"globalSearchSiteClaude",fallback:"Claude"},grok:{key:"globalSearchSiteGrok",fallback:"Grok"},qwenai:{key:"globalSearchSiteQwenAi",fallback:"Qwen Studio"},ima:{key:"globalSearchSiteIma",fallback:"ima"},zai:{key:"globalSearchSiteZai",fallback:"Z.ai"}},VS=e=>e.replace(/[-_]/g," ").replace(/\s+/g," ").trim().replace(/\b([a-z])/g,(e,t)=>t.toUpperCase()),KS=Object.freeze(Object.defineProperty({__proto__:null,App:()=>{const{settings:e,setSettings:t,updateDeepSetting:n,updateNestedSetting:r}=Ai(),o=Ei(),i=e?.features?.prompts?.submitShortcut??"enter";Ai(e=>e._syncVersion);const[a,s]=z(0),l=A(e=>{const t=se(e.key);return t===e.key?e.fallback:t},[a]),c=A((e,t)=>{let n=l(e);return Object.keys(t).forEach(e=>{n=n.replace(new RegExp(`{${e}}`,"g"),t[e]);}),n},[l]),d=q(()=>(()=>{if("undefined"==typeof navigator)return false;const e=navigator.platform?.toLowerCase?.()||"",t=navigator.userAgent?.toLowerCase?.()||"";return e.includes("mac")||t.includes("mac os")})(),[]),u=q(()=>ar(e?.shortcuts)||Jo.shortcuts,[e?.shortcuts]),h=q(()=>{if(!u.enabled)return null;const e=u.keybindings[Un];return null===e?null:e||er[Un]},[u]),g=h?sr(h,d):"",p=e?.globalSearch?.doubleShift??Jo.globalSearch.doubleShift,m=q(()=>{const e=[];return g&&e.push(g),p&&e.push("double shift"),e.join(" / ")},[g,p]),f=d?"⌘":"Ctrl",b=A(e=>{if(e===Un)return m||null;if(!u.enabled)return null;const t=u.keybindings[e];if(null===t)return null;const n=t||er[e];return n?sr(n,d):null},[m,d,u]),y=m||se("shortcutNotSet"),v=e?.globalSearch?.enableFuzzySearch??Jo.globalSearch.enableFuzzySearch,w=q(()=>m?c({key:"globalSearchShortcutNudge",fallback:"下次可按 {shortcut} 快速打开"},{shortcut:m}):"",[c,m]),x=A(()=>{if("undefined"==typeof window)return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0};try{const e=window.localStorage.getItem(WS);if(!e)return {shownCount:0,lastShownAt:0,dismissed:!1,shortcutUsedCount:0};const t=JSON.parse(e);return {shownCount:Number.isFinite(t.shownCount)?Math.max(0,Number(t.shownCount)):0,lastShownAt:Number.isFinite(t.lastShownAt)?Math.max(0,Number(t.lastShownAt)):0,dismissed:Boolean(t.dismissed),shortcutUsedCount:Number.isFinite(t.shortcutUsedCount)?Math.max(0,Number(t.shortcutUsedCount)):0}}catch{return {shownCount:0,lastShownAt:0,dismissed:false,shortcutUsedCount:0}}},[]),k=A(e=>{if("undefined"!=typeof window)try{window.localStorage.setItem(WS,JSON.stringify(e));}catch{}},[]),S=A(()=>{Ye.current&&(clearTimeout(Ye.current),Ye.current=null);},[]),C=A(e=>{e.stopPropagation();const t=e.target.closest(".gh-code-copy-btn");if(!t)return;const n=t.nextElementSibling?.textContent||"";n&&(navigator.clipboard?.writeText?navigator.clipboard.writeText(n).then(()=>{mp(t,{size:14});}).catch(()=>{Li(l({key:"copyFailed",fallback:"Copy failed"}));}):Li(l({key:"copyFailed",fallback:"Copy failed"})));},[l]),E=A(()=>{Ke.current&&(clearTimeout(Ke.current),Ke.current=null);},[]),T=A(e=>{E(),ye(e),we(e);},[E]),M=A(e=>{const t=e.trimStart();T(e),fe(e=>t.startsWith("tip:")?"tips"===e?e:"tips":"tips"===e?"all":e);},[T]),I=A(()=>{t({globalSearch:{...Jo.globalSearch,...e?.globalSearch||{},enableFuzzySearch:!v}});},[v,t,e?.globalSearch]),L=A(e=>{ye(e),E(),Ke.current=setTimeout(()=>{we(e),Ke.current=null;},140);},[E]),N=A(()=>{S(),De(false),Re("");},[S]),D=A(()=>{const e=x();k({...e,dismissed:true}),N();},[x,N,k]),R=A(()=>{const e=x(),t=e.shortcutUsedCount+1;k({...e,shortcutUsedCount:t,dismissed:e.dismissed||t>=2}),N();},[x,N,k]),O=A(()=>{if(!w)return;const e=x();if(e.dismissed)return;if(e.shortcutUsedCount>=2)return void k({...e,dismissed:true});if(e.shownCount>=3)return;const t=Date.now();e.lastShownAt>0&&t-e.lastShownAt<864e5||(k({...e,shownCount:e.shownCount+1,lastShownAt:t}),Re(w),De(true),S(),Ye.current=setTimeout(()=>{De(false),Re(""),Ye.current=null;},6e3));},[S,x,w,k]),F=A(e=>{const t=zS[e];return t?l(t):e},[l]),$=A(e=>{const t=BS[e];return t?l(t):e},[l]),U=A(e=>{const t=GS[e.settingId];if(t)return l({key:t,fallback:VS(e.settingId)});if(e.settingId.startsWith("model-lock-")){const t=e.settingId.slice(11),n=QS[t];if(n){return `${l({key:"tabModelLock",fallback:"Model Lock"})}: ${l(n)}`}}if(e.settingId.startsWith("shortcut-binding-")){const t=e.settingId.slice(17),n=Jn[t];if(n){return `${l({key:"navShortcuts",fallback:"Keyboard Shortcuts"})}: ${l({key:n.labelKey,fallback:n.label})}`}}return VS(e.settingId)},[l]),j=A(e=>{const t=Br(e);if(!t)return l({key:"globalSearchCategorySettings",fallback:"Settings"});const n=F(t.page);if(!t.subTab)return n;return `${n} / ${$(t.subTab)}`},[l,F,$]),H=q(()=>tv(),[]),W=q(()=>H?new qv(H):null,[H]),G=q(()=>H&&W?new zv(H,W):null,[H,W]);_(()=>{if(!G)return;return e?.features?.prompts?.promptQueue??false?G.start():G.stop(),()=>G.stop()},[G,e?.features?.prompts?.promptQueue]);const Q=q(()=>H?new bv(H):null,[H]),[V,K]=z(null);_(()=>{if(Q)return K(null),Q.onExportProgress(K);K(null);},[Q]);const Z=q(()=>{if(!H)return null;return new Av(H,e?.features?.outline??Jo.features.outline,e=>{n("features","outline","expandLevel",e);},e=>{n("features","outline","showUserQueries",e);})},[H,n]),[Y,J]=z(false),X=P(false),ee=A(e=>{X.current=e,J(e);},[]),te=A(e=>{ee(e),r("panel","panelExpanded",e);},[ee,r]),ne=P(e);_(()=>{ne.current=e;},[e]),_(()=>{if(o&&e&&!xt.current){xt.current=true;const t=e.panel?.panelMode??"edge-snap",n=e.panel?.defaultPosition??"right";ee(e.panel?.panelExpanded??true),yt("edge-snap"===t?n:null);}},[o,ee,e]),_(()=>{if(!xt.current||!e)return;const t=e.panel?.panelExpanded??true;t!==X.current&&ee(t);},[ee,e]);const[re,oe]=z(false),ae=P(new Set),le=P(null);_(()=>{const e=d?"Meta":"Control",t=d?OS:FS,n=e=>OS.has(e)?"Meta":FS.has(e)?"Control":e,r=e=>!!e&&(d?e.ctrlKey||e.altKey||e.shiftKey:e.metaKey||e.altKey||e.shiftKey),o=()=>{const e=Array.from(ae.current);return e.length>0&&e.every(e=>t.has(e))},i=()=>{null!==le.current&&(window.clearTimeout(le.current),le.current=null);},a=a=>{if(!((a?d?a.metaKey||t.has(n(a.key)):a.ctrlKey||t.has(n(a.key)):ae.current.has(e))&&o()&&!r(a)))return i(),void oe(false);re||null!==le.current||(le.current=window.setTimeout(()=>{le.current=null,o()&&ae.current.has(e)&&oe(true);},200));},s=t=>{const o=n(t.key);o!==e||r(t)||ae.current.clear(),ae.current.add(o),a(t);},l=e=>{ae.current.delete(n(e.key)),a(e);},c=()=>{ae.current.clear(),a();};return window.addEventListener("keydown",s,true),window.addEventListener("keyup",l,true),window.addEventListener("blur",c),()=>{i(),window.removeEventListener("keydown",s,true),window.removeEventListener("keyup",l,true),window.removeEventListener("blur",c);}},[d,re]);const[ce,de]=z(null),[ue,he]=z(false),[ge,pe]=z(false),[me,fe]=z("all"),[be,ye]=z(""),[ve,we]=z(""),[xe,ke]=z(0),[Se,Ce]=z(false),[Ae,Ee]=z("pointer"),[Te,Me]=z({}),[Ne,De]=z(false),[qe,Re]=z(""),[Pe,ze]=z(false),[Be,Oe]=z(-1),[Fe,$e]=z(()=>"undefined"!=typeof window&&Boolean(window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__)),[Ue,je]=z(()=>"undefined"!=typeof window&&window.__OPHEL_PENDING_UPDATE_VERSION__||null),He=P(null),We=P(null),Ge=P(null),Qe=P(null),Ve=P(null),Ke=P(null),Ze=P(0),Ye=P(null),Je=P("ui"),Xe=P(0),[et,tt]=z(0),nt=P(0),rt=P(null),{globalSearchPromptPreview:ot,globalSearchPromptPreviewPosition:it,clearPromptPreviewTimer:at,clearPromptPreviewHideTimer:st,hideGlobalSearchPromptPreview:lt,scheduleHideGlobalSearchPromptPreview:ct,scheduleGlobalSearchPromptPreview:dt,scheduleGlobalSearchPointerPreview:ut,refreshGlobalSearchPromptPreviewAnchorRect:ht}=(({settingsSearchResultsRef:e,pointerDelayMs:t,hideDelayMs:n})=>{const[r,o]=z(null),i=P(null),a=P(null),s=P(null),l=A(()=>{i.current&&(clearTimeout(i.current),i.current=null);},[]),c=A(()=>{a.current&&(clearTimeout(a.current),a.current=null);},[]),d=A(e=>"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):JSON.stringify(e).slice(1,-1),[]),u=A(t=>{const n=e.current;return n?n.querySelector(`[data-global-search-item-id="${d(t)}"]`):null},[d,e]),h=A(()=>{l(),c(),s.current=null,o(null);},[c,l]),g=A((e=n)=>{c(),a.current=setTimeout(()=>{h(),a.current=null;},e);},[c,n,h]),p=A(({item:e,anchorElement:t,delay:n,source:r})=>{"prompts"===e.category&&e.promptId&&e.promptContent&&e.promptContent.trim()&&(l(),c(),"keyboard"===r&&(s.current=e.id),i.current=setTimeout(()=>{"keyboard"===r&&s.current!==e.id||(o({itemId:e.id,content:e.promptContent,anchorRect:t.getBoundingClientRect()}),i.current=null);},n));},[c,l]),m=A(({item:e,anchorElement:n})=>{s.current=null,p({item:e,anchorElement:n,delay:t,source:"pointer"});},[t,p]),f=A(()=>{o(e=>{if(!e)return e;const t=u(e.itemId);if(!t)return null;const n=t.getBoundingClientRect();return Math.abs(n.top-e.anchorRect.top)<.5&&Math.abs(n.left-e.anchorRect.left)<.5&&Math.abs(n.right-e.anchorRect.right)<.5&&Math.abs(n.bottom-e.anchorRect.bottom)<.5?e:{...e,anchorRect:n}});},[u]),b=q(()=>{if(!r||"undefined"==typeof window)return null;const e=16,t=Math.max(280,Math.min(420,window.innerWidth-32)),n=Math.max(220,Math.min(420,window.innerHeight-32));let o=r.anchorRect.right+12;return o+t>window.innerWidth-e&&(o=r.anchorRect.left-t-12),o=Math.max(e,Math.min(o,window.innerWidth-t-e)),{top:Math.max(e,Math.min(r.anchorRect.top,window.innerHeight-e-n)),left:o}},[r]);return {globalSearchPromptPreview:r,globalSearchPromptPreviewPosition:b,clearPromptPreviewTimer:l,clearPromptPreviewHideTimer:c,hideGlobalSearchPromptPreview:h,scheduleHideGlobalSearchPromptPreview:g,scheduleGlobalSearchPromptPreview:p,scheduleGlobalSearchPointerPreview:m,refreshGlobalSearchPromptPreviewAnchorRect:f}})({settingsSearchResultsRef:Qe,pointerDelayMs:450,hideDelayMs:220}),[gt,pt]=z(null),[mt,ft]=z(false),[bt,yt]=z(null),vt=P(false),wt=P(false),xt=P(false),kt=A(()=>{const e=[],t=document.querySelectorAll("plasmo-csui, #ophel-userscript-root");for(const n of t)n.shadowRoot&&e.push(n.shadowRoot);return document.body&&e.push(document.body),e},[]),St=A(e=>{for(const t of kt()){const n=t.querySelector(e);if(n instanceof HTMLElement)return n}return null},[kt]),{isEdgePeeking:Ct,showEdgePeek:At,hideEdgePeek:Et,scheduleEdgePeekSync:Tt,showEdgePeekFromShortcut:Mt,markSuppressOverlayInit:_t,markSyncAfterOpen:It,handlePanelMouseEnter:Lt,handlePanelMouseLeave:Nt,handleInteractionChange:Dt}=Vv({edgeSnapState:bt,panelMode:e?.panel?.panelMode,isPanelExpanded:Y,findUiElement:St,getQueryRoots:kt,isSettingsOpenRef:vt}),[qt,Rt]=z(false),[Pt,zt]=z(null),Bt=P(false),Ot=P(false),Ft=P(null),$t=P(null),Ut=P(null),jt=P(false),Ht=A(()=>{Ft.current&&(clearTimeout(Ft.current),Ft.current=null);},[]),Wt=A(()=>{$t.current&&(clearTimeout($t.current),$t.current=null);},[]),Gt=A(()=>{Ht(),Wt(),Bt.current=false,Ot.current=false,Rt(false),zt(null);},[Ht,Wt]),Qt=A(()=>{if(jt.current)return false;const e=[".gh-main-panel",".quick-btn-group"],t=Ut.current;for(const n of e){const e=St(n);if(e){if(t){const n=e.getBoundingClientRect();if(t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom)return true;continue}if(e.matches(":hover"))return true}}return false},[St]),Vt=A(()=>{Ht(),Wt();const e=()=>{$t.current=null,Bt.current&&(Ot.current||Ja(kt())||Qt()?$t.current=setTimeout(e,250):(Bt.current=false,Rt(false),zt(null)));};$t.current=setTimeout(e,250);},[Ht,Wt,kt,Qt]),Kt=A(e=>{Dt(e),Ot.current=e,Bt.current&&(e?Wt():Vt());},[Wt,Dt,Vt]),Zt=A((e,t)=>{if(X.current)return;jt.current=false,Ht(),Wt();const n={left:e.left,right:e.right,top:e.top,bottom:e.bottom,width:e.width,height:e.height};if(zt(n),Bt.current)return;const r=300+(t?.waitForGroupDwell?300:0);Ft.current=setTimeout(()=>{Ft.current=null,X.current||(zt(n),Bt.current=true,Rt(true));},r);},[Ht,Wt]),Yt=A(()=>{Bt.current?Vt():Ht();},[Ht,Vt]),Jt=A(e=>{if(Bt.current)return Ht(),void Wt();Lt();},[Ht,Wt,Lt]),Xt=A(e=>{Bt.current?Vt():Nt();},[Nt,Vt]);_(()=>{Y&&qt&&Gt();},[Gt,qt,Y]),_(()=>{const e=e=>{jt.current=false,Ut.current={clientX:e.clientX,clientY:e.clientY};},t=()=>{jt.current=true,Ut.current=null,Ht(),Bt.current&&Vt();},n=()=>{"hidden"===document.visibilityState&&t();},r=e=>{null===e.relatedTarget&&t();},o=e=>{null===e.relatedTarget&&t();};return window.addEventListener("pointermove",e,true),window.addEventListener("pointerdown",e,true),window.addEventListener("blur",t),document.addEventListener("visibilitychange",n),document.addEventListener("pointerout",r,true),document.addEventListener("mouseout",o,true),()=>{window.removeEventListener("pointermove",e,true),window.removeEventListener("pointerdown",e,true),window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",n),document.removeEventListener("pointerout",r,true),document.removeEventListener("mouseout",o,true);}},[Ht,Vt]),_(()=>{if(!qt)return;let e=Ja(kt());e&&Wt();const t=new MutationObserver(()=>{const t=Ja(kt());t?Wt():e&&Vt(),e=t;});for(const n of kt())t.observe(n,{childList:true,subtree:true});return ()=>{t.disconnect();}},[Wt,kt,qt,Vt]),_(()=>()=>{Ht(),Wt();},[Ht,Wt]),_(()=>{const e=e=>{ge&&(wt.current=false,rt.current=null,E(),pe(false),fe("all"),ye(""),we(""),Oe(-1),ke(0),Ce(false),Ee("pointer"),Me({}),Ze.current=0),vt.current||(vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&At(),he(true));};return window.addEventListener("ophel:navigateSettingsPage",e),()=>window.removeEventListener("ophel:navigateSettingsPage",e)},[E,bt,ge,At]);const en=ov(e=>e.conversations),tn=dv(e=>e.folders),nn=pv(e=>e.tags),rn=Tv(e=>e.prompts),on=q(()=>(e=>{const t=/(^|\s)([a-z]+):((?:"(?:\\.|[^"])+")|(?:\\.|[^\s])+)/gi,n=[],r=[],o=[],i={};let a=t.exec(e);for(;a;){const s=(a[2]||"").toLowerCase(),l=a[3]||"",c=(a.index||0)+(a[1]?.length||0),d=c+`${s}:${l}`.length,u=l.startsWith('"')!==l.endsWith('"'),h=CS(s),g=yS(l),p=fS(g);if(!uS.includes(s)){r.push({id:`unknown:${s}:${a.index||0}`,code:"unknownOperator",operator:s,suggestion:h||void 0}),a=t.exec(e);continue}const m=s;if(u){r.push({id:`invalid:${m}:quote:${a.index||0}`,code:"invalidValue",operator:m,value:l}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!g){r.push({id:`invalid:${m}:empty:${a.index||0}`,code:"invalidValue",operator:m}),o.push({start:c,end:d}),a=t.exec(e);continue}if(!xS(m,p)){r.push({id:`invalid:${m}:${p}:${a.index||0}`,code:"invalidValue",operator:m,value:g,suggestion:kS(m)}),o.push({start:c,end:d}),a=t.exec(e);continue}const f=(i[m]||0)+1;i[m]=f;const b={id:SS(m,p,f),key:m,value:g,normalizedValue:p};wS(b,n)?(r.push({id:`conflict:${m}:${p}:${a.index||0}`,code:"conflict",operator:m,value:g}),o.push({start:c,end:d}),a=t.exec(e)):(o.push({start:c,end:d}),n.push(b),a=t.exec(e));}if(0===o.length)return {rawQuery:e,plainQuery:e.trim(),filters:n,diagnostics:r};o.sort((e,t)=>e.start-t.start);let s="",l=0;return o.forEach(t=>{lon.filters,[on.filters]),sn=q(()=>on.diagnostics,[on.diagnostics]),ln=q(()=>on.plainQuery,[on.plainQuery]),cn=q(()=>Ur(""),[]);_(()=>{if(!Z||!ge)return;const e=()=>{Z.refresh(),tt(e=>e+1);};e();const t=Z.subscribe(()=>{tt(e=>e+1);}),n=window.setInterval(()=>{e();},1200);return ()=>{t(),window.clearInterval(n);}},[ge,Z]);const dn=q(()=>Array.from(new Set(bS(ln))).sort((e,t)=>t.length-e.length),[ln]),{filteredGlobalSearchResults:un,globalSearchResultCounts:hn,groupedGlobalSearchResults:gn,visibleGlobalSearchResults:pn}=RS({activeGlobalSearchPlainQuery:ln,enableFuzzySearch:v,activeGlobalSearchSyntaxFilters:an,settingsSearchResults:cn,resolveSettingSearchTitle:U,getSettingsBreadcrumb:j,conversationManager:Q,conversationsSnapshot:en,foldersSnapshot:tn,tagsSnapshot:nn,promptsSnapshot:rn,outlineManager:Z,outlineSearchVersion:et,getLocalizedText:l,resolveShortcutLabel:b,passThroughModifierLabel:f,activeGlobalSearchCategory:me,expandedGlobalSearchCategories:Te,allCategoryItemLimit:12}),mn=q(()=>{const e=new Map;return pn.forEach((t,n)=>{e.set(t.id,n);}),e},[pn]),fn=q(()=>0===pn.length?-1:Math.min(xe,pn.length-1),[xe,pn.length]),bn=fn>=0?`${HS}-${fn}`:void 0,yn=q(()=>$S.find(e=>e.id===me)||$S[0],[me]),vn=q(()=>({label:l(yn.label),placeholder:l(yn.placeholder),emptyText:l(yn.emptyText)}),[yn,l]),wn=q(()=>$S.reduce((e,t)=>(e[t.id]=l(t.label),e),{}),[l]),xn=q(()=>Object.entries(US).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),kn=q(()=>Object.entries(jS).reduce((e,[t,n])=>(e[t]=l(n),e),{}),[l]),{activeGlobalSearchFilterChips:Sn,hasOverflowGlobalSearchFilterChips:Cn,globalSearchSyntaxDiagnosticMessages:An,globalSearchSyntaxHelpTitle:En,globalSearchSyntaxHelpDescription:Tn,globalSearchSyntaxHelpItems:Mn,globalSearchSyntaxSuggestions:_n,shouldShowGlobalSearchSyntaxSuggestions:In}=(({getLocalizedText:e,activeGlobalSearchSyntaxFilters:t,filterChipMaxCount:n,isGlobalSettingsSearchOpen:r,settingsSearchInputValue:o,filteredGlobalSearchResults:i,suggestionLimit:a})=>{const s=q(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),l=q(()=>({type:e({key:"globalSearchSyntaxOperatorType",fallback:"Type"}),folder:e({key:"globalSearchSyntaxOperatorFolder",fallback:"Folder"}),tag:e({key:"globalSearchSyntaxOperatorTag",fallback:"Tag"}),is:e({key:"globalSearchSyntaxOperatorIs",fallback:"State"}),level:e({key:"globalSearchSyntaxOperatorLevel",fallback:"Level"}),date:e({key:"globalSearchSyntaxOperatorDate",fallback:"Date"})}),[e]),c=q(()=>e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),[e]),d=q(()=>e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"}),[e]),u=q(()=>({type:e({key:"globalSearchSyntaxSuggestionTypeDesc",fallback:"Filter by result type"}),folder:e({key:"globalSearchSyntaxSuggestionFolderDesc",fallback:"Filter by folder or category"}),tag:e({key:"globalSearchSyntaxSuggestionTagDesc",fallback:"Filter by tag name"}),is:e({key:"globalSearchSyntaxSuggestionIsDesc",fallback:"Filter by status"}),level:e({key:"globalSearchSyntaxSuggestionLevelDesc",fallback:"Filter outline level (0 = user query)"}),date:e({key:"globalSearchSyntaxSuggestionDateDesc",fallback:"Filter by recent days (conversations and prompts only)"})}),[e]),h=q(()=>({outline:e({key:"globalSearchCategoryOutline",fallback:"Outline"}),conversations:e({key:"globalSearchCategoryConversations",fallback:"Conversations"}),prompts:e({key:"globalSearchCategoryPrompts",fallback:"Prompts"}),settings:e({key:"globalSearchCategorySettings",fallback:"Settings"})}),[e]),g=q(()=>({pinned:e({key:"globalSearchSyntaxPinned",fallback:"Pinned"}),unpinned:e({key:"globalSearchSyntaxUnpinned",fallback:"Unpinned"})}),[e]),p=q(()=>({unknownOperator:e({key:"globalSearchSyntaxDiagnosticUnknownOperator",fallback:"Unknown operator"}),invalidValue:e({key:"globalSearchSyntaxDiagnosticInvalidValue",fallback:"Invalid filter value"}),conflict:e({key:"globalSearchSyntaxDiagnosticConflict",fallback:"Conflicting filters removed"})}),[e]),m=q(()=>e({key:"globalSearchSyntaxHelpTitle",fallback:"Search syntax examples"}),[e]),f=q(()=>e({key:"globalSearchSyntaxHelpDesc",fallback:"Click to insert. Keywords are English-only."}),[e]),b=q(()=>e({key:"featureTipSearchPlaceholder",fallback:"Search feature tips…"}),[e]),y=q(()=>[{id:"help:tip:",token:"tip:",label:"tip:",description:b},{id:"help:type:outline",token:"type:outline",label:"type:outline",description:h.outline},{id:"help:type:conversations",token:"type:conversations",label:"type:conversations",description:h.conversations},{id:"help:type:prompts",token:"type:prompts",label:"type:prompts",description:h.prompts},{id:"help:type:settings",token:"type:settings",label:"type:settings",description:h.settings},{id:"help:is:pinned",token:"is:pinned",label:"is:pinned",description:g.pinned},{id:"help:is:unpinned",token:"is:unpinned",label:"is:unpinned",description:g.unpinned},{id:"help:level:0",token:"level:0",label:"level:0",description:e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"})},{id:"help:date:7d",token:"date:7d",label:"date:7d",description:d},{id:"help:date:30d",token:"date:30d",label:"date:30d",description:d},{id:"help:folder:inbox",token:"folder:inbox",label:"folder:inbox",description:u.folder},{id:"help:tag:work",token:"tag:work",label:"tag:work",description:u.tag}],[b,e,d,g.pinned,g.unpinned,u.folder,u.tag,h.conversations,h.outline,h.prompts,h.settings]),v=q(()=>t.slice(0,n).map(e=>({id:e.id,key:e.key,value:e.value,label:`${s[e.key]}: ${e.value}`})),[t,n,s]),w=t.length>n,x=q(()=>{if(!r)return [];const t=AS(o),n=t?.token||"",s=n.length>0,p=n.toLowerCase(),m=n.match(/^([a-z]+):(.*)$/i);if(m){const t=m[1].toLowerCase();if(!uS.includes(t))return [];const n=m[2]||"",r=n.toLowerCase(),o=[],s=e=>{o.some(t=>t.id===e.id)||o.push(e);};if("type"===t)hS.forEach(e=>{n&&!e.toLowerCase().startsWith(r)||s({id:`type:${e}`,token:`type:${e}`,label:`type:${e} · ${h[e]}`,description:u.type});});else if("is"===t)n&&!"pinned".startsWith(r)||s({id:"is:pinned",token:"is:pinned",label:`is:pinned · ${g.pinned}`,description:u.is}),n&&!"unpinned".startsWith(r)||s({id:"is:unpinned",token:"is:unpinned",label:`is:unpinned · ${g.unpinned}`,description:u.is});else if("level"===t)pS.forEach(t=>{n&&!t.startsWith(r)||s({id:`level:${t}`,token:`level:${t}`,label:`level:${t}`,description:"0"===t?e({key:"globalSearchSyntaxSuggestionLevelQueryDesc",fallback:"Outline user query"}):c});});else if("date"===t){const e=r.match(/^(\d{0,3})d?$/);if(e){const t=e[1];if(t){const e=`${t}d`;Number(t)>0&&s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});}}mS.forEach(e=>{n&&!e.startsWith(r)||s({id:`date:${e}`,token:`date:${e}`,label:`date:${e}`,description:d});});}if("folder"===t){const e=new Map;i.forEach(t=>{const o=(t.folderName||"").trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`folder:"${e}"`:`folder:${e}`;s({id:`folder:${e.toLowerCase()}`,token:t,label:`folder:${e}`,description:u.folder});});}if("tag"===t){const e=new Map;i.forEach(t=>{(t.tagNames||t.tagBadges?.map(e=>e.name)||[]).forEach(t=>{const o=t.trim();if(!o)return;const i=o.toLowerCase();n&&!i.includes(r)||e.set(i,o);});}),Array.from(e.values()).slice(0,a).forEach(e=>{const t=/\s/.test(e)?`tag:"${e}"`:`tag:${e}`;s({id:`tag:${e.toLowerCase()}`,token:t,label:`tag:${e}`,description:u.tag});});}return o.slice(0,a)}return uS.filter(e=>!s||e.startsWith(p)).map(e=>({id:`operator:${e}`,token:`${e}:`,label:`${e}: ${l[e]}`,description:u[e]})).slice(0,a)},[i,e,d,g,c,u,l,h,r,o,a]);return {activeGlobalSearchFilterChips:v,hasOverflowGlobalSearchFilterChips:w,globalSearchSyntaxDiagnosticMessages:p,globalSearchSyntaxHelpTitle:m,globalSearchSyntaxHelpDescription:f,globalSearchSyntaxHelpItems:y,globalSearchSyntaxSuggestions:x,shouldShowGlobalSearchSyntaxSuggestions:x.length>0&&Boolean(AS(o)?.token)}})({getLocalizedText:l,activeGlobalSearchSyntaxFilters:an,filterChipMaxCount:4,isGlobalSettingsSearchOpen:ge,settingsSearchInputValue:be,filteredGlobalSearchResults:un,suggestionLimit:8}),Ln=q(()=>l({key:"globalSearchResultsLabel",fallback:"Global search results"}),[l]),Nn=A(e=>{const t=AS(be),n=!e.token.endsWith(":"),r=`${e.token}${n?" ":""}`,o=t?`${be.slice(0,t.start)}${r}`:be.trim().length>0?`${be}${be.endsWith(" ")?"":" "}${r}`:r;M(o),Oe(-1),ke(0),window.requestAnimationFrame(()=>{const e=He.current;if(!e)return;const t=o.length;e.focus({preventScroll:true}),e.setSelectionRange(t,t);});},[be,M]),Dn=A(e=>{Nn(e),ze(false);},[Nn]),qn=A(e=>{const t=an.filter(t=>t.id!==e),n=(({plainQuery:e,filters:t})=>`${e} ${t.map(e=>{const t=e.value.replace(/([\\"])/g,"\\$1"),n=/\s/.test(e.value)?`"${t}"`:t;return `${e.key}:${n}`}).join(" ")}`.replace(/\s+/g," ").trim())({plainQuery:ln,filters:t});T(n),Oe(-1),ke(0);},[ln,an,T]),Rn=A(()=>{T(ln),Oe(-1),ke(0);},[ln,T]),Pn=q(()=>{if(fn<0)return null;const e=pn[fn];if(!e)return null;const t=xn[e.category],n=c({key:"globalSearchContextCurrentItem",fallback:"第 {current} 项"},{current:String(fn+1)});if("all"!==me)return {label:t,meta:`${n} · ${c({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(pn.length)})}`};const r=gn.find(t=>t.category===e.category);return r?{label:t,meta:`${n} · ${c({key:"globalSearchContextShownProgress",fallback:"已显示 {shown}/{total}"},{shown:String(r.items.length),total:String(r.totalCount)})}`}:{label:t,meta:`${n} · ${c({key:"globalSearchContextTotalItems",fallback:"共 {total} 项"},{total:String(pn.length)})}`}},[me,fn,c,gn,xn,pn]),zn=A(()=>{vt.current=false,he(false);const e=ne.current;if("edge-snap"!==e?.panel?.panelMode)return;const t=St(".gh-main-panel");if(!t)return;if(!(t.classList.contains("edge-snapped-left")||t.classList.contains("edge-snapped-right"))){const n=t.getBoundingClientRect(),r=e?.panel?.edgeSnapThreshold??30;n.left{Je.current=e,vt.current?(wt.current=true,zn()):wt.current=false,bt&&"edge-snap"===ne.current?.panel?.panelMode&&At();const t=document.activeElement;t instanceof HTMLElement&&t!==document.body?rt.current=t:rt.current=null,E(),ye(""),we(""),ze(false),Oe(-1),fe("all"),ke(0),Ce(false),Ee("pointer"),Me({}),Ze.current=0,pe(true);},[E,zn,bt,At]),On=A(e=>{const t=e?.restoreFocus??true,n=e?.reopenSettings??false,r=rt.current;if(rt.current=null,wt.current=false,E(),pe(false),fe("all"),ye(""),we(""),ze(false),Oe(-1),ke(0),Ce(false),Ee("pointer"),Me({}),Ze.current=0,n)return vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&At(),void he(true);Tt(),t&&r&&r.isConnected&&window.requestAnimationFrame(()=>{if(r.isConnected)try{r.focus({preventScroll:!0});}catch{r.focus();}});},[E,bt,Tt,At]),Fn=A(()=>{ge&&On({restoreFocus:false}),wt.current=false,vt.current=true,bt&&"edge-snap"===ne.current?.panel?.panelMode&&At(),he(true);},[On,bt,ge,At]),$n=A(async t=>{const n=++nt.current;if(On({restoreFocus:false}),t.tipId){if(t.tipHighlightTarget){const e=St(`[data-tip-target="${t.tipHighlightTarget}"]`);if(e)return e.classList.remove("feature-highlight"),e.offsetWidth,e.classList.add("feature-highlight"),setTimeout(()=>e.classList.remove("feature-highlight"),2500),void e.scrollIntoView({behavior:"smooth",block:"nearest"})}Li(t.tipActionText||t.snippet||t.title,3e3);}else if("settings"===t.category&&t.settingId)window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{settingId:t.settingId}}));else {if("outline"===t.category&&t.outlineTarget&&Z){const e=(t,n)=>{for(const r of t){if(r.index===n)return r;if(r.children&&r.children.length>0){const t=e(r.children,n);if(t)return t}}return null},r=e(Z.getTree(),t.outlineTarget.index);let o=r?.element||null;if(!o||!o.isConnected){const e=await Z.resolveOutlineTarget(t.outlineTarget,t.outlineTarget.queryIndex);e&&(o=e);}if(n!==nt.current)return;if(o&&o.isConnected)return Z.scrollToOutlineTarget(o),o.classList.add("outline-highlight"),void setTimeout(()=>o?.classList.remove("outline-highlight"),2e3);if(t.outlineTarget.isGhost&&void 0!==t.outlineTarget.scrollTop){const e=Z.getScrollContainer();if(e)return e.scrollTo({top:t.outlineTarget.scrollTop,behavior:"smooth"}),void Li(se("bookmarkContentMissing"),3e3)}return}if("prompts"===t.category&&t.promptId){const n=rn.find(e=>e.id===t.promptId);if(!n)return;const o=()=>{te(true);const t=(e?.features?.order||Jo.features.order).indexOf(cr);t>=0&&window.dispatchEvent(new CustomEvent("ophel:switchTab",{detail:{index:t}}));},i=()=>{de(null),o();const e={promptId:n.id};window.__ophelPendingLocatePrompt=e,window.dispatchEvent(new CustomEvent("ophel:locatePrompt",{detail:e}));};if("locate"===(e?.globalSearch?.promptEnterBehavior??"smart"))return void i();if(!W)return void o();if(r=n.content,/\{\{([^\s{}]+)\}\}/.test(r)){de(null),o();const e={promptId:n.id,submitAfterInsert:false};return window.__ophelPendingPromptVariableDialog=e,void window.dispatchEvent(new CustomEvent("ophel:openPromptVariableDialog",{detail:e}))}return void(async()=>{if(await W.insertPrompt(n.content))return W.updateLastUsed(n.id),de(n),void Li(`${se("inserted")}: ${n.title}`);i(),Li(se("insertFailed"));})()}var r;"conversations"===t.category&&t.conversationId&&H?.navigateToConversation(t.conversationId,t.conversationUrl);}},[H,On,St,Z,te,W,rn,e]);_(()=>{ge&&(He.current?.focus(),He.current?.select());},[ge]),_(()=>{ge&&"ui"===Je.current&&O();},[ge,O]),_(()=>()=>{S();},[S]);const jn=P(ge);_(()=>{jn.current=ge;},[ge]);const Hn=A(()=>{jn.current||(Xe.current=0,R(),Bn("shortcut"));},[R,Bn]);_(()=>{const e=e=>{if(jn.current)return;if("Shift"!==e.key&&(Xe.current=0),"Shift"!==e.key||e.repeat||e.ctrlKey||e.metaKey||e.altKey)return;const t=Date.now();if((ne.current?.globalSearch?.doubleShift??Jo.globalSearch.doubleShift)&&t-Xe.current<=360)return e.preventDefault(),e.stopPropagation(),Xe.current=0,R(),void Bn("shortcut");Xe.current=t;};return window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}},[R,Bn]),_(()=>{const e=()=>{Bn("event");};return window.addEventListener("ophel:openSettingsSearch",e),()=>{window.removeEventListener("ophel:openSettingsSearch",e);}},[Bn]),_(()=>()=>{E();},[E]),_(()=>{if(!ge||!Pe)return;const e=e=>{const t=e.composedPath?e.composedPath():[e.target];We.current&&t.includes(We.current)||Ge.current&&t.includes(Ge.current)||ze(false);};return document.addEventListener("mousedown",e,true),()=>{document.removeEventListener("mousedown",e,true);}},[ge,Pe]),_(()=>{if(!ge)return void lt();if("keyboard"!==Ae)return;const e=pn[xe];if(!e||"prompts"!==e.category)return void lt();const t=Qe.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${xe}"]`);n&&dt({item:e,anchorElement:n,delay:700,source:"keyboard"});},[lt,ge,dt,xe,Ae,pn]),_(()=>{ke(0),Ce(false),Ee("pointer"),Me({}),Ze.current=0,lt();},[me,lt,ve]),_(()=>{ge||lt();},[lt,ge]),_(()=>{ot&&Ve.current&&fp(Ve.current,{size:14});},[ot]),_(()=>{if(!ge||!ot)return;const e=()=>{ht();},t=Qe.current;return window.addEventListener("resize",e),window.addEventListener("scroll",e,true),t?.addEventListener("scroll",e),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,true),t?.removeEventListener("scroll",e);}},[ot,ge,ht]),_(()=>()=>{at(),st();},[st,at]),(({isGlobalSettingsSearchOpen:e,showGlobalSearchSyntaxHelp:t,setShowGlobalSearchSyntaxHelp:n,activeGlobalSearchCategory:r,categoryIds:o,setActiveGlobalSearchCategory:i,settingsSearchActiveIndex:a,setSettingsSearchActiveIndex:s,settingsSearchNavigationMode:l,setSettingsSearchNavigationMode:c,setSettingsSearchHoverLocked:d,shouldShowGlobalSearchSyntaxSuggestions:u,globalSearchSyntaxSuggestions:h,activeSearchSyntaxSuggestionIndex:g,setActiveSearchSyntaxSuggestionIndex:p,applyGlobalSearchSyntaxSuggestion:m,visibleGlobalSearchResults:f,navigateToSearchResult:b,closeGlobalSettingsSearch:y,getShouldReturnToSettingsOnEscape:v,settingsSearchResultsRef:w,keyboardSafeTop:x,keyboardSafeBottom:k})=>{const S=P(void 0);S.current=e=>{if("Escape"===e.key){if(e.preventDefault(),e.stopPropagation(),t)return void n(false);const r=v();return void y({restoreFocus:!r,reopenSettings:r})}if("Tab"===e.key){e.preventDefault(),e.stopPropagation();const t=o.findIndex(e=>e===r);if(t<0)return i("all"),s(0),d(false),void c("keyboard");const n=o.length,a=e.shiftKey?(t-1+n)%n:(t+1)%n;return i(o[a]),s(0),d(false),void c("keyboard")}if(u){if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e+1;return t>=h.length?0:t});if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),void p(e=>{if(0===h.length)return -1;const t=e-1;return t<0?h.length-1:t});if("Enter"===e.key&&g>=0){const t=h[g];if(!t)return;return e.preventDefault(),e.stopPropagation(),void m(t)}}if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e+1)%f.length);if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),d(true),c("keyboard"),void s(e=>0===f.length?0:(e-1+f.length)%f.length);if("Enter"===e.key){if(0===f.length)return;const t=f[a]||f[0];if(!t)return;f[a]||s(0),e.preventDefault(),e.stopPropagation(),b(t);}},_(()=>{if(!e)return;const t=e=>S.current?.(e);return window.addEventListener("keydown",t,true),()=>{window.removeEventListener("keydown",t,true);}},[e]),_(()=>{0!==f.length?a>=f.length&&s(0):0!==a&&s(0);},[a,s,f.length]),_(()=>{u?g>=h.length&&p(h.length-1):-1!==g&&p(-1);},[g,h.length,p,u]);const C=A((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),o=n.top+x,i=n.bottom-k;if(r.topi){const t=r.bottom-i,n=Math.max(0,e.scrollHeight-e.clientHeight);e.scrollTop=Math.min(n,e.scrollTop+t);}},[k,x]);_(()=>{if(!e)return;if("keyboard"!==l)return;const t=w.current;if(!t)return;const n=t.querySelector(`[data-global-search-index="${a}"]`);n&&C(t,n);},[C,e,a,l,w,f]);})({isGlobalSettingsSearchOpen:ge,showGlobalSearchSyntaxHelp:Pe,setShowGlobalSearchSyntaxHelp:ze,activeGlobalSearchCategory:me,categoryIds:$S.map(e=>e.id),setActiveGlobalSearchCategory:fe,settingsSearchActiveIndex:xe,setSettingsSearchActiveIndex:ke,settingsSearchNavigationMode:Ae,setSettingsSearchNavigationMode:Ee,setSettingsSearchHoverLocked:Ce,shouldShowGlobalSearchSyntaxSuggestions:In,globalSearchSyntaxSuggestions:_n,activeSearchSyntaxSuggestionIndex:Be,setActiveSearchSyntaxSuggestionIndex:Oe,applyGlobalSearchSyntaxSuggestion:Nn,visibleGlobalSearchResults:pn,navigateToSearchResult:$n,closeGlobalSettingsSearch:On,getShouldReturnToSettingsOnEscape:()=>wt.current,settingsSearchResultsRef:Qe,keyboardSafeTop:8,keyboardSafeBottom:12}),_(()=>{o&&e?.language&&(ie(e.language),s(e=>e+1));},[e?.language,o]);const Wn=A(e=>{de(e);},[]),Gn=A(()=>{de(null),H&&H.clearTextarea();},[H]);_(()=>{Z&&e&&Z.updateSettings(e.features?.outline);},[Z,e]),_(()=>{Q&&e&&Q.updateSettings({syncUnpin:e.features?.conversations?.syncUnpin??false});},[Q,e]);const Qn=q(()=>{const t=tv(),n=t?.getSiteId()||"_default",r=e?.theme?.sites?.[n]||e?.theme?.sites?._default;return Wv({mode:r?.mode||"light",adapter:H,lightPresetId:r?.lightStyleId||"google-gradient",darkPresetId:r?.darkStyleId||"classic-dark",syncNativePageTheme:e?.theme?.syncNativePageTheme??true})},[]),Vn=B(Qn.subscribe,Qn.getSnapshot);_(()=>{if(!o)return;return Qn.setOnModeChange((e,n)=>{if(!Ai.getState()._hasHydrated)return;const r=n||e,o=ne.current,i=o?.theme?.sites||{},a=tv(),s=a?.getSiteId()||"_default",l={lightStyleId:"google-gradient",darkStyleId:"classic-dark",mode:"light",...i[s]||i._default};t({theme:{...o?.theme,sites:{...i,[s]:{...l,mode:r}}}});}),()=>{Qn.setOnModeChange(void 0);}},[Qn,t,o]);const Kn=e?.theme?.sites,Zn=e?.features?.conversations?.syncUnpin,Yn=e?.features?.conversations?.syncDelete,Xn=e?.features?.outline?.enabled??true,tr=e?.features?.outline?.inlineBookmarkMode,nr=Boolean(e),rr=e?.quickButtons||Jo.quickButtons,or=rr.collapsed,ir=or.find(e=>"floatingToolbar"===e.id)?.enabled??true,lr=rr.floatingToolbar?.open??true,dr=e?.panel?.preventAutoScroll??false,ur=Z?.getGhostBookmarkIds().length??0;_(()=>{ir&&lr||(pt(null),ft(false));},[ir,lr]),_(()=>{if(!o)return;const e=tv(),t=e?.getSiteId()||"_default",n=Kn?.[t]||Kn?._default,r=n?.lightStyleId,i=n?.darkStyleId;r&&i&&Qn.setPresets(r,i);},[Kn,Qn,o]),_(()=>{o&&Qn.setCustomStyles(e?.theme?.customStyles||[]);},[e?.theme?.customStyles,Qn,o]),_(()=>{o&&Qn.setNativeThemeOverrideEnabled(e?.theme?.syncNativePageTheme??true);},[e?.theme?.syncNativePageTheme,Qn,o]);const hr=A(async e=>{await Qn.toggle(e);},[Qn]);_(()=>{if(o)return Qn.startThemeMonitoring(),()=>{Qn.stopThemeMonitoring();}},[Qn,o]),_(()=>{if(W&&W.init(),Q&&Q.init(),Z){Z.refresh();const e=setInterval(()=>{Z.refresh();},2e3),t=()=>Z.handleUrlChange();return window.addEventListener("gh-url-change",t),()=>{clearInterval(e),window.removeEventListener("gh-url-change",t),Q?.destroy();}}},[W,Q,Z]),_(()=>{if(!Q||"undefined"==typeof chrome)return;const e=(e,t,n)=>e?.type===wp&&(Q.destroy(),n({success:true}),true);return chrome.runtime.onMessage.addListener(e),()=>{chrome.runtime.onMessage.removeListener(e);}},[Q]),_(()=>{const e=e=>{if(window.__OPHEL_EXTENSION_UPDATE_DISMISSED__)return;const t=e,n=t.detail?.version||window.__OPHEL_PENDING_UPDATE_VERSION__||null;je(n),$e(true);};return window.addEventListener(Mp,e),window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__&&!window.__OPHEL_EXTENSION_UPDATE_DISMISSED__&&($e(true),je(window.__OPHEL_PENDING_UPDATE_VERSION__||null)),()=>{window.removeEventListener(Mp,e);}},[]),_(()=>(window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=Fe,Fe&&document.getElementById("ophel-extension-update-fallback")?.remove(),()=>{window.__OPHEL_EXTENSION_UPDATE_NOTICE_ACTIVE__=false;}),[Fe]);const gr=A(()=>{window.__OPHEL_EXTENSION_UPDATE_DISMISSED__=true,window.__OPHEL_EXTENSION_UPDATE_AVAILABLE__=false,$e(false);},[]),pr=A(()=>{window.location.reload();},[]);_(()=>{Q&&Q.updateSettings({syncUnpin:Zn??false,syncDelete:Yn??true});},[Q,Zn,Yn]),_(()=>{if(!(o&&Z&&H&&nr))return;const e=tr||"always";if(!Xn||"hidden"===e)return void Cv.cleanupInjectedArtifacts();const t=new Cv(Z,H,e);return ()=>{t.cleanup();}},[Z,H,Xn,tr,nr,o]);const mr=A(()=>{const e=ne.current;if(!e)return;const n=!e.panel?.preventAutoScroll;t({panel:{...e.panel,preventAutoScroll:n}}),Li(se(n?"preventAutoScrollEnabled":"preventAutoScrollDisabled"));},[t]),fr=A(async()=>{if(!Q||!H)return;const e=H.getSessionId();if(!e)return void Li(se("exportNeedOpenFirst"));await Q.exportConversation(e,"markdown")||Li(se("exportFailed"));},[Q,H]),br=A(()=>{if(!Q||!H)return;const e=H.getSessionId();if(!e)return void Li(se("noConversationToLocate"));const t=Q.getConversation(e);pt({convId:e,activeFolderId:t?.folderId});},[Q,H]),yr=A(()=>{if(!Z)return;const e=Z.clearGhostBookmarks();Li(0!==e?`${se("cleared")} (${e})`:se("floatingToolbarClearGhostEmpty"));},[Z]),vr=A(async()=>{if(!Q||!H)return;const e=H.getSessionId();if(!e)return void Li(se("exportNeedOpenFirst"));await Q.exportConversation(e,"clipboard")||Li(se("exportFailed"));},[Q,H]),wr=A(()=>{if(!H)return;const e=H.getSiteId(),n=ne.current;if(!n)return;const r=n.modelLock?.[e]||{enabled:false,keyword:""};if(!r.keyword)return void(r.enabled?(t({modelLock:{...n.modelLock,[e]:{...r,enabled:false}}}),Li(se("modelLockDisabled"))):(Li(se("modelLockNoKeyword")),t({modelLock:{...n.modelLock,[e]:{...r,enabled:true}}}),Fn(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"siteSettings",subTab:"modelLock"}}));},100)));const o=!r.enabled;t({modelLock:{...n.modelLock,[e]:{...r,enabled:o}}}),Li(se(o?"modelLockEnabled":"modelLockDisabled"));},[H,Fn,t]),xr=q(()=>{if(!H||!e)return false;const t=H.getSiteId();return e.modelLock?.[t]?.enabled||false},[H,e]),kr=A(()=>{Gt();const e=!X.current;e&&"edge-snap"===ne.current?.panel?.panelMode?(bt||yt(ne.current?.panel?.defaultPosition??"right"),At(),It()):e||Et(),te(e);},[bt,Et,Gt,It,te,At]);Sw({settings:e,adapter:H,outlineManager:Z,conversationManager:Q,onPanelToggle:kr,onThemeToggle:hr,onOpenSettings:Fn,onOpenGlobalSearch:Hn,isPanelVisible:Y,isSnapped:!!bt&&!Ct,onShowSnappedPanel:Mt,onToggleScrollLock:mr});const Sr=P(void 0);_(()=>{const t=e?.panel?.panelMode??"edge-snap";if(void 0!==Sr.current){if(Sr.current!==t)if(Sr.current=t,"edge-snap"===t){const t=e?.panel?.defaultPosition??"right";_t(X.current),yt(t),Et();}else yt(null),Et();}else Sr.current=t;},[Et,_t,e?.panel?.defaultPosition,e?.panel?.panelMode]);const Cr=P(e?.panel?.defaultPosition);_(()=>{const t=e?.panel?.defaultPosition;void 0===Cr.current&&t?Cr.current=t:t&&Cr.current!==t&&(Cr.current=t,bt&&(yt(t),Et()));},[bt,Et,e?.panel?.defaultPosition]);const Ar=A(e=>{if(!H||H.getSiteId()!==po)return;const t="ophel:aistudio-submit-shortcut-sync-toast",n=`synced:${e}`;let r=true;try{sessionStorage.getItem(t)===n?r=!1:sessionStorage.setItem(t,n);}catch{}if(!r)return;const o="ctrlEnter"===e?"Ctrl + Enter":"Enter";Li(`AI Studio ${se("promptSubmitShortcutLabel")}: ${o}`);},[H]);_(()=>{if(!H||H.getSiteId()!==po)return;const e=e=>{const t=e.detail,n=t?.submitShortcut;"enter"!==n&&"ctrlEnter"!==n||Ar(n);};return window.addEventListener(Dv,e),()=>{window.removeEventListener(Dv,e);}},[H,Ar]),_(()=>{H&&W&&H.getSiteId()===po&&W.syncAiStudioSubmitShortcut(i);},[H,W,i]),_(()=>{if(!H||!W)return;const e=e=>{if(!e.isTrusted)return;if("Enter"!==e.key)return;if(e.isComposing||229===e.keyCode)return;const t=e.composedPath();if(t.some(e=>e instanceof HTMLElement&&(e.classList?.contains("gh-queue-panel")||e.classList?.contains("gh-queue-input")||e.classList?.contains("gh-queue-item-edit-input"))))return;const n=t.find(e=>e instanceof HTMLElement&&H.isValidTextarea(e));if(!n)return;const r=e.ctrlKey||e.metaKey,o=r||e.altKey,a="ctrlEnter"===i?r&&!e.altKey&&!e.shiftKey:!o&&!e.shiftKey,s="ctrlEnter"===i&&!o&&!e.shiftKey;if(a)return e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),void(async()=>{W.syncAiStudioSubmitShortcut(i);await W.submitPrompt(i)&&de(null);})();s&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),(e=>{if(e instanceof HTMLTextAreaElement){const t=e.selectionStart??e.value.length,n=e.selectionEnd??e.value.length;return e.setRangeText("\n",t,n,"end"),void e.dispatchEvent(new Event("input",{bubbles:true}))}if("true"!==e.getAttribute("contenteditable"))return;e.focus();const t={key:"Enter",code:"Enter",keyCode:13,which:13,bubbles:true,cancelable:true,composed:true,shiftKey:true},n=e.innerHTML;e.dispatchEvent(new KeyboardEvent("keydown",t)),e.dispatchEvent(new KeyboardEvent("keypress",t)),e.dispatchEvent(new KeyboardEvent("keyup",t)),e.innerHTML===n&&(document.execCommand("insertLineBreak")||document.execCommand("insertParagraph"),e.dispatchEvent(new Event("input",{bubbles:true})));})(n));};return H.getSiteId()===so?(window.addEventListener("keydown",e,true),()=>{window.removeEventListener("keydown",e,true);}):(document.addEventListener("keydown",e,true),()=>{document.removeEventListener("keydown",e,true);})},[H,W,i]),_(()=>{if(!H||!ce)return;const e=()=>{de(null);},t=t=>{const n=H.getSubmitButtonSelectors();if(0===n.length)return;const r=t.composedPath();for(const o of r){if(o===document||o===window)break;for(const t of n)try{if(o.matches?.(t))return void setTimeout(e,100)}catch{}}};return document.addEventListener("click",t,true),()=>{document.removeEventListener("click",t,true);}},[H,ce]),_(()=>{if(!ce||!H)return;let e=window.location.href;const t=()=>{de(null),H.clearTextarea();},n=()=>{window.location.href!==e&&t();},r=setInterval(()=>{window.location.href!==e&&(e=window.location.href,t());},500);return window.addEventListener("popstate",n),()=>{clearInterval(r),window.removeEventListener("popstate",n);}},[ce,H]);const[Er,Tr]=z(null),Mr=A(()=>{if(!Q||!H)return;const e=H.getSessionId();e?Tr({convId:e}):Li(se("noConversationToLocate"));},[Q,H]),{tags:_r,addTag:Ir,updateTag:Lr,deleteTag:Nr}=pv(),Dr=A(e=>{Ee("pointer"),Me(t=>({...t,[e]:!t[e]}));},[]),qr=l({key:"extensionUpdateNoticeKicker",fallback:"Extension updated"}),Rr=Ue?c({key:"extensionUpdateNoticeWithVersion",fallback:`${Aw} has been updated to v{version}. Reload this page to keep using the latest version.`},{version:Ue}):l({key:"extensionUpdateNotice",fallback:`${Aw} has been updated. Reload this page to keep using the latest version.`}),Pr=l({key:"extensionUpdateNoticeAction",fallback:"Reload page"}),zr=se("close"),Or=V?se(PS[V.stage]):"",Fr=se("exportOverlayHint"),$r=q(()=>({query:l({key:"outlineOnlyUserQueries",fallback:"Query"}),reply:l({key:"globalSearchOutlineReplies",fallback:"Replies"})}),[l]);return H&&W&&Q&&Z?Le("div",{className:"gh-root "+(re?"gh-pass-through":""),children:[ Ie(Ex,{isOpen:Y||qt,isLauncherPeeking:qt,launcherPeekAnchorRect:Pt,onClose:()=>{Gt(),Et(),te(false);},promptManager:W,conversationManager:Q,outlineManager:Z,adapter:H,onThemeToggle:hr,themeMode:Vn,selectedPromptId:ce?.id,onPromptSelect:Wn,edgeSnapState:bt,isEdgePeeking:Ct,onEdgeSnap:e=>yt(e),onUnsnap:()=>{yt(null),Et();},onInteractionStateChange:Kt,onOpenSettings:()=>{Fn();},onMouseEnter:Jt,onMouseLeave:Xt}), Ie(Lx,{isPanelExpanded:Y,onPanelToggle:kr,onPanelLogoHoverStart:Zt,onPanelLogoHoverEnd:Yt,onThemeToggle:hr,themeMode:Vn,onExport:fr,onMove:br,onSetTag:Mr,onScrollLock:()=>mr(),onSettings:()=>{Fn(),setTimeout(()=>{window.dispatchEvent(new CustomEvent("ophel:navigateSettingsPage",{detail:{page:"general",subTab:"toolsMenu"}}));},50);},scrollLocked:dr,onCleanup:()=>{0!==ur?ft(true):Li(se("floatingToolbarClearGhostEmpty"));},onGlobalSearch:Bn,onCopyMarkdown:vr,onModelLockToggle:wr,isModelLocked:xr,onOpenSettings:Fn}),ce&&Ie(Dx,{title:ce.title,onClear:Gn,adapter:H}), Ie(aS,{isOpen:ue,onClose:zn,siteId:H.getSiteId()}), Ie(sS,{isOpen:ge,onClose:()=>{lt(),On();},inputRef:He,resultsRef:Qe,activeOptionId:bn,inputValue:be,inputPlaceholder:g?`${vn.placeholder}(${g})`:vn.placeholder,onInputChange:e=>{L(e),Oe(-1),ke(0);const t=e.trimStart();t.startsWith("tip:")&&"tips"!==me?fe("tips"):t.startsWith("tip:")||"tips"!==me||fe("all");},hotkeyLabel:y,fuzzySearchToggleLabel:l({key:"globalSearchFuzzySearchToggle",fallback:"Fuzzy"}),fuzzySearchToggleAriaLabel:l({key:"globalSearchFuzzySearchToggleAria",fallback:"Toggle fuzzy search"}),isFuzzySearchEnabled:v,onToggleFuzzySearch:I,syntaxHelpTriggerRef:We,syntaxHelpPopoverRef:Ge,showSyntaxHelp:Pe,onToggleSyntaxHelp:()=>ze(e=>!e),syntaxHelpTriggerAriaLabel:l({key:"globalSearchSyntaxHelpTriggerAria",fallback:"Open search syntax help"}),syntaxHelpTitle:En,syntaxHelpDescription:Tn,syntaxHelpItems:Mn,onApplySyntaxHelpItem:Dn,activeFilterChips:Sn,hasOverflowFilterChips:Cn,overflowFilterChipText:c({key:"globalSearchSyntaxChipOverflow",fallback:"+{count} more"},{count:String(an.length-4)}),filterChipRemoveTitle:l({key:"globalSearchSyntaxChipRemove",fallback:"Click to remove filter"}),clearFiltersLabel:l({key:"clear",fallback:"Clear"}),onRemoveFilterChip:qn,onClearAllFilterChips:Rn,shouldShowSyntaxSuggestions:In,syntaxSuggestions:_n,activeSyntaxSuggestionIndex:Be,onHoverSyntaxSuggestion:Oe,onApplySyntaxSuggestion:Nn,syntaxDiagnostics:sn,resolveSyntaxDiagnosticTitle:e=>An[e]||An.invalidValue,showShortcutNudge:Ne,shortcutNudgeMessage:qe,closeLabel:l({key:"close",fallback:"Close"}),dismissShortcutNudgeLabel:l({key:"globalSearchShortcutNudgeDismiss",fallback:"Don’t remind me"}),onHideShortcutNudge:N,onDismissShortcutNudgeForever:D,categoriesLabel:l({key:"globalSearchCategoriesLabel",fallback:"Global search categories"}),categories:$S.map(e=>({id:e.id,label:wn[e.id],count:"tips"===e.id&&"tips"!==me?null:hn[e.id]})),activeCategoryId:me,onSelectCategory:e=>{fe(e),ke(0);},activeContext:Pn,listboxId:"settings-search-results-listbox",listboxLabel:Ln,onResultsWheel:()=>{Ee("pointer"),Ze.current=Date.now()+200,lt();},visibleResults:pn,groupedResults:gn,getGroupLabel:e=>xn[e],allCategoryItemLimit:12,isAllCategory:"all"===me,emptyText:vn.emptyText,emptyGuideTitle:l({key:"globalSearchSyntaxEmptyGuideTitle",fallback:"Try search filters"}),emptyGuideDescription:l({key:"globalSearchSyntaxEmptyGuideDesc",fallback:"Use filter syntax to narrow results quickly"}),emptyGuideExamples:[{id:"example:type-prompts",token:"type:prompts",onClick:()=>Nn({id:"example:type-prompts",token:"type:prompts",label:"type:prompts",description:""})},{id:"example:is-pinned",token:"is:pinned",onClick:()=>Nn({id:"example:is-pinned",token:"is:pinned",label:"is:pinned",description:""})},{id:"example:folder-inbox",token:"folder:inbox",onClick:()=>Nn({id:"example:folder-inbox",token:"folder:inbox",label:"folder:inbox",description:""})},{id:"example:tag-work",token:"tag:work",onClick:()=>Nn({id:"example:tag-work",token:"tag:work",label:"tag:work",description:""})},{id:"example:level-0",token:"level:0",onClick:()=>Nn({id:"example:level-0",token:"level:0",label:"level:0",description:""})},{id:"example:date-7d",token:"date:7d",onClick:()=>Nn({id:"example:date-7d",token:"date:7d",label:"date:7d",description:""})}],renderSearchResultItem:(e,t)=>Ie(dS,{item:e,index:t,optionIdPrefix:HS,isActive:t===xe,highlightTokens:dn,outlineRoleLabels:$r,matchReasonLabels:kn,onMouseMove:()=>{Ee("pointer"),Date.now(){Ee("pointer"),ut({item:e,anchorElement:t.currentTarget});},onMouseLeave:()=>{ct();},onClick:()=>$n(e)},e.id),resolveVisibleResultIndex:(e,t)=>mn.get(e.id)??t,collapseLabel:l({key:"collapse",fallback:"Collapse"}),moreLabel:l({key:"floatingToolbarMore",fallback:"More"}),onToggleCategoryGroup:Dr,footerTips:l({key:"globalSearchFooterTips",fallback:"Enter to jump · ↑↓ to select · Tab category · Esc to close"}),promptPreview:ot&&it?Le(_e,{children:[ Ie("div",{ref:Ve,className:"settings-search-prompt-preview-float gh-markdown-preview",style:{top:it.top,left:it.left},onMouseEnter:()=>{at(),st();},onMouseLeave:()=>{ct();},onClick:C,dangerouslySetInnerHTML:{__html:qp(Hh(ot.content,false))}}), Ie("style",{children:"\n/* highlight.js GitHub Dark 主题\n 面板(Shadow DOM)通过 var() 跟随 Ophel 主题变量;\n 主文档注入(用户提问)var() 不可用,fallback 为 #1e1e1e */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview :not(pre) > code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview .gh-code-wrapper {\n position: relative;\n margin: 12px 0;\n}\n.gh-markdown-preview pre {\n margin: 0;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n"})]}):void 0}),gt&&Ie(Gw,{folders:Q.getFolders(),excludeFolderId:Q.getConversation(gt.convId)?.folderId,activeFolderId:gt.activeFolderId,onSelect:async e=>{await Q.moveConversation(gt.convId,e),pt(null);},onCancel:()=>pt(null)}),Er&&Ie(Qw,{tags:_r,conv:Q.getConversation(Er.convId),onCancel:()=>Tr(null),onCreateTag:async(e,t)=>Ir(e,t),onUpdateTag:async(e,t,n)=>Lr(e,t,n),onDeleteTag:async e=>{Nr(e);},onSetConversationTags:async(e,t)=>{await Q.updateConversation(e,{tagIds:t});},onRefresh:()=>{}}),mt&&Ie(jw,{title:se("floatingToolbarClearGhost"),message:se("floatingToolbarClearGhostConfirm").replace("{count}",String(ur)),danger:true,onConfirm:()=>{ft(false),yr();},onCancel:()=>ft(false)}),H&&G&&(e?.features?.prompts?.promptQueue??false)&&Ie(Tx,{adapter:H,dispatcher:G}), Ie(Zw,{isVisible:Boolean(V),text:Or,hint:Fr,tone:"export",blockPageInteraction:true}),Fe&&Le("section",{className:"gh-update-notice gh-interactive",role:"status","aria-live":"polite",children:[ Ie("button",{type:"button",className:"gh-update-notice-close","aria-label":zr,onClick:gr,children:Le("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[ Ie("path",{d:"M18 6 6 18"}), Ie("path",{d:"m6 6 12 12"})]})}), Le("div",{className:"gh-update-notice-kicker",children:[ Ie("svg",{className:"gh-update-notice-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:Ie("path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"})}),qr]}), Ie("p",{className:"gh-update-notice-message",children:Rr}), Ie("div",{className:"gh-update-notice-actions",children:Ie("button",{type:"button",className:"gh-update-notice-button gh-update-notice-button--primary",onClick:pr,children:Pr})})]}), Ie(Kw,{})]}):null}},Symbol.toStringTag,{value:"Module"})),ZS="[GeminiMyStuffBridge]",YS=[1,1,1,0,0,0,1,0],JS=[1,1,1,1,1,0,1,0],XS={"x-same-domain":"1","x-goog-ext-525001261-jspb":"[1,null,null,null,null,null,null,null,[4]]","x-goog-ext-73010989-jspb":"[]"};let eC=false;const tC=new Map,nC=new Map;function rC(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}function oC(e=window.location.pathname){return e.replace(/^\/u\/\d+/,"")}function iC(e){return "document"===e?JS:YS}function aC(e){let t=tC.get(e);return t||(t=new Map,tC.set(e,t)),t}function sC(e){return "string"==typeof e&&/^boq_assistant-bard-web-server_/i.test(e)}function lC(e){return "string"==typeof e&&/^\d{10,}$/.test(e)}function cC(e){return "string"==typeof e&&/^[A-Za-z0-9._:-]+:\d{13}$/.test(e)}function dC(e,t){for(const n of Object.values(e))if("string"==typeof n&&t(n))return n;return null}function uC(e,t){const n=e.match(t);return n?.[1]||n?.[0]||null}function hC(){const e=rC(),t=e.WIZ_global_data||{},n=document.querySelector('script[data-id="_gd"]')?.textContent||"",r=(sC(t.cfb2h)?t.cfb2h:null)||dC(t,sC)||uC(n,/"cfb2h":"([^"]+)"/)||uC(n,/boq_assistant-bard-web-server_[^"]+/),o=(lC(t.FdrFJe)?t.FdrFJe:null)||dC(t,lC)||uC(n,/"FdrFJe":"([^"]+)"/)||uC(n,/"\d{10,}"/)?.replace(/"/g,"")||null,i=(cC(t.SNlM0e)?t.SNlM0e:null)||dC(t,cC)||uC(n,/"SNlM0e":"([^"]+)"/)||uC(n,/[A-Za-z0-9._:-]+:\d{13}/)||null;return sC(r)&&lC(o)&&cC(i)?{bl:r,fSid:o,at:i,hl:document.documentElement.lang||navigator.language||"zh-CN"}:(console.warn(`${ZS} failed to resolve runtime tokens`,{hasGlobalData:Boolean(e.WIZ_global_data),bl:r,fSid:o,at:i}),null)}function gC(e){const t=new URL("/_/BardChatUi/data/batchexecute",window.location.origin);return t.searchParams.set("rpcids","jGArJ"),t.searchParams.set("source-path",oC()),t.searchParams.set("bl",e.bl),t.searchParams.set("f.sid",e.fSid),t.searchParams.set("hl",e.hl),t.searchParams.set("_reqid",String(Date.now()%1e6)),t.searchParams.set("rt","c"),t.toString()}function pC(e,t,n){const r=new URLSearchParams,o=n?[iC(t),30,n]:[iC(t),30];return r.set("f.req",JSON.stringify([[["jGArJ",JSON.stringify(o),null,"generic"]]])),r.set("at",e.at),r.toString()}function mC(e,t){const n=e.replace(/^\)\]\}'\s*\n\s*\n/,"").split("\n").map(e=>e.trim()).filter(Boolean);if(n.length<2)throw new Error("mystuff-response-lines-missing");const r=JSON.parse(n[1]),o=Array.isArray(r)?r[0]:null,i=Array.isArray(o)&&"string"==typeof o[2]?o[2]:null;if(!i)throw new Error("mystuff-payload-missing");const a=JSON.parse(i);return {items:(Array.isArray(a[0])?a[0]:[]).map(e=>function(e,t){if(!Array.isArray(t)||t.length<3)return null;const n=Array.isArray(t[0])?t[0]:[];if(n.length<2||"string"!=typeof n[0]||"string"!=typeof n[1])return null;const r=Array.isArray(t[1])?t[1]:[],o=Array.isArray(t[4])?t[4]:[];return {kind:e,conversationId:n[0],responseId:n[1],timestamp:"number"==typeof r[0]?r[0]:0,timestampNano:"number"==typeof r[1]?r[1]:0,status:"number"==typeof t[2]?t[2]:0,title:"string"==typeof t[3]&&t[3].trim()?t[3].trim():void 0,thumbnailUrl:"string"==typeof o[1]&&o[1]?o[1]:void 0,resourceId:"string"==typeof t[5]&&t[5]?t[5]:void 0}}(t,e)).filter(e=>null!==e),nextPageToken:"string"==typeof a[1]&&a[1]?a[1]:null}}function fC(e){return e.flatMap(e=>Array.from(aC(e).values()))}function bC(e){window.postMessage({type:Tp,payload:e},"*"),window.dispatchEvent(new CustomEvent(Tp,{detail:e}));}async function yC(e){if(!e?.requestId||!function(e=window.location.pathname){const t=oC(e);return "/mystuff"===t||"/mystuff/"===t||t.startsWith("/mystuff/")||"/library"===t||"/library/"===t||t.startsWith("/library/")}())return;const t=function(e){return Array.isArray(e)&&0!==e.length?Array.from(new Set(e.filter(e=>"media"===e||"document"===e))):["media","document"]}(e.kinds),n=e.force||t.some(e=>0===aC(e).size);try{n&&await Promise.all(t.map(t=>async function(e,t){const n=aC(e);if(!t&&n.size>0)return Array.from(n.values());const r=nC.get(e);if(r)return r;const o=(async()=>{const t=new Map;let r;for(let n=0;n<80;n+=1){const o=hC();if(!o)throw new Error("mystuff-runtime-tokens-missing");const i=await rC().fetch(gC(o),{method:"POST",credentials:"include",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",...XS},body:pC(o,e,r)}),a=await i.text();if(!i.ok)throw console.warn(`${ZS} fetch failed`,{kind:e,page:n,status:i.status,preview:a.slice(0,240)}),new Error(`mystuff-fetch-failed:${i.status}`);const s=mC(a,e);if(s.items.forEach(e=>{return t.set(`${(n=e).conversationId}:${n.responseId}`,e);var n;}),console.info(`${ZS} fetched page`,{kind:e,page:n,itemCount:s.items.length,nextPageToken:s.nextPageToken}),!s.nextPageToken)break;r=s.nextPageToken;}return n.clear(),t.forEach((e,t)=>n.set(t,e)),Array.from(n.values())})();nC.set(e,o);try{return await o}finally{nC.delete(e);}}(t,Boolean(e.force))));const r=fC(t);bC({requestId:e.requestId,items:r,kinds:t,reason:n?"sync":"snapshot",timestamp:Date.now()});}catch(r){console.warn(`${ZS} sync request failed`,{requestId:e.requestId,kinds:t,error:r}),bC({requestId:e.requestId,items:fC(t),kinds:t,reason:"snapshot",timestamp:Date.now()});}}function vC(){eC||"gemini.google.com"!==window.location.hostname||(eC=true,window.addEventListener("message",e=>{e.data?.type===Ep&&yC(e.data.payload);}),window.addEventListener(Ep,e=>{yC(e.detail);}),console.info(`${ZS} initialized`));}function wC(){return "undefined"!=typeof unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}class xC{urlPatterns;urlPathEndsWith;silenceThreshold;requestBodyRules;onComplete;onStart;domValidation;_activeCount=0;_silenceTimer=null;_isMonitoring=false;_originalFetch=null;_originalXhrOpen=null;_originalXhrSend=null;_lastUrl="";_hasTriggeredStart=false;_boundHookedFetch;constructor(e={}){this.urlPatterns=e.urlPatterns||[],this.urlPathEndsWith=e.urlPathEndsWith||[],this.silenceThreshold=e.silenceThreshold||3e3,this.requestBodyRules=e.requestBodyRules||[],this.onComplete=e.onComplete||(()=>{}),this.onStart=e.onStart||null,this.domValidation=e.domValidation||null,this._boundHookedFetch=this._hookedFetch.bind(this);}start(){if(this._isMonitoring)return;const e=wC();this._originalFetch=e.fetch,e.fetch=this._boundHookedFetch,this._hookXHR(),this._isMonitoring=true;}stop(){if(!this._isMonitoring)return;const e=wC();this._originalFetch&&(e.fetch=this._originalFetch,this._originalFetch=null),this._unhookXHR(),this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),this._isMonitoring=false,this._activeCount=0,this._hasTriggeredStart=false;}_isTargetUrl(e){if(!e)return false;if(!(0===this.urlPatterns.length||this.urlPatterns.some(t=>e.includes(t))))return false;if(0===this.urlPathEndsWith.length)return true;try{const t=new URL(e,window.location.origin).pathname;return this.urlPathEndsWith.some(e=>t.endsWith(e))}catch{return this.urlPathEndsWith.some(t=>e.endsWith(t))}}_tryTriggerComplete(){if(this._activeCount>0)return;const e={activeCount:this._activeCount,lastUrl:this._lastUrl,timestamp:Date.now()};if(this.domValidation)try{if(!this.domValidation(e))return void(this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),1e3))}catch(t){console.error(t);}this._hasTriggeredStart=false;try{this.onComplete(e);}catch(t){console.error(t);}}async _hookedFetch(...e){const t=wC(),n=this._extractFetchUrl(e);if(!this._isTargetUrl(n))return this._originalFetch.call(t,...e);if(this._activeCount++,this._lastUrl=n,this._silenceTimer&&(clearTimeout(this._silenceTimer),this._silenceTimer=null),!this._hasTriggeredStart&&this.onStart){this._hasTriggeredStart=true;try{const t=await this._extractFetchRequestMetadata(e);this.onStart({url:n,timestamp:Date.now(),type:"fetch",...t});}catch{}}try{const n=await this._originalFetch.call(t,...e),r=n.clone();return this._readStream(r).catch(()=>{}),n}catch(r){throw this._decrementAndSchedule(),r}}async _readStream(e){try{if(!e.body)return;const t=e.body.getReader();for(;;){const{done:e}=await t.read();if(e)break}}catch{}finally{this._decrementAndSchedule();}}_decrementAndSchedule(){this._activeCount=Math.max(0,this._activeCount-1),this._silenceTimer&&clearTimeout(this._silenceTimer),this._silenceTimer=setTimeout(()=>this._tryTriggerComplete(),this.silenceThreshold);}_hookXHR(){const e=this,t=wC().XMLHttpRequest;this._originalXhrOpen=t.prototype.open,this._originalXhrSend=t.prototype.send,t.prototype.open=function(t,n,...r){return this._networkMonitorUrl=n?n.toString():"",e._originalXhrOpen.call(this,t,n,...r)},t.prototype.send=function(t){const n=this._networkMonitorUrl||"";if(!e._isTargetUrl(n))return e._originalXhrSend.call(this,t);if(e._activeCount++,e._lastUrl=n,e._silenceTimer&&(clearTimeout(e._silenceTimer),e._silenceTimer=null),!e._hasTriggeredStart&&e.onStart){e._hasTriggeredStart=true;try{const r=e._extractRequestMetadata(t);e.onStart({url:n,timestamp:Date.now(),type:"xhr",...r});}catch{}}const r=()=>{e._decrementAndSchedule();};return this.addEventListener("load",r),this.addEventListener("error",r),this.addEventListener("abort",r),this.addEventListener("timeout",r),e._originalXhrSend.call(this,t)};}_unhookXHR(){const e=wC().XMLHttpRequest;this._originalXhrOpen&&(e.prototype.open=this._originalXhrOpen,this._originalXhrOpen=null),this._originalXhrSend&&(e.prototype.send=this._originalXhrSend,this._originalXhrSend=null);}_extractFetchUrl(e){const t=e[0];return t?"string"==typeof t?t:t instanceof URL?t.toString():"object"==typeof t&&"string"==typeof t.url?t.url:"function"==typeof t.toString?t.toString():"":""}async _extractFetchRequestMetadata(e){if(0===this.requestBodyRules.length)return {};const t=await this._bodyToText(e[1]?.body);if(null!==t)return this._extractRequestMetadata(t);const n=e[0];if(n&&"object"==typeof n&&"function"==typeof n.clone&&"function"==typeof n.text)try{const e=n.clone();if(e&&"function"==typeof e.text){const t=await e.text();return this._extractRequestMetadata(t)}}catch{}return {}}async _bodyToText(e){if("string"==typeof e)return e;if(!e||"object"!=typeof e)return null;const t=Object.prototype.toString.call(e);if("[object URLSearchParams]"===t)return "function"==typeof e.toString?e.toString():null;if("[object Blob]"===t&&"function"==typeof e.text)try{return await e.text()}catch{return null}if(ArrayBuffer.isView(e))try{return (new TextDecoder).decode(e)}catch{return null}if(e instanceof ArrayBuffer)try{return (new TextDecoder).decode(e)}catch{return null}return null}_extractRequestMetadata(e){if("string"!=typeof e||0===e.trim().length||0===this.requestBodyRules.length)return {};try{const t=JSON.parse(e),n={};for(const e of this.requestBodyRules)"json-field-exists"===e.type&&void 0!==t[e.field]&&Object.assign(n,e.metadata);return {...n}}catch{return {}}}}let kC=null,SC=false;const CC=Object.freeze(Object.defineProperty({__proto__:null,initNetworkMonitor:function(){SC||(SC=true,vC(),window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};e.source!==window&&t!==Sp&&t!==Ap&&t!==Cp||t===Sp&&(kC&&kC.stop(),kC=new xC({urlPatterns:n?.urlPatterns,urlPathEndsWith:n?.urlPathEndsWith,silenceThreshold:n?.silenceThreshold,requestBodyRules:n?.requestBodyRules,onStart:e=>window.postMessage({type:Cp,payload:e},"*"),onComplete:e=>window.postMessage({type:Ap,payload:e},"*")}),kC.start());}));}},Symbol.toStringTag,{value:"Module"})),AC="gh-assistant-mermaid-style",EC=".gh-assistant-mermaid",TC="data-ophel-assistant-mermaid-managed",MC="data-ophel-assistant-mermaid-original-display",_C="data-ophel-assistant-mermaid-preview-id",IC="data-ophel-assistant-mermaid-render-token",LC="data-ophel-assistant-mermaid-fullscreen",NC="data-ophel-assistant-mermaid-restore-zoom",DC="data-ophel-assistant-mermaid-fullscreen-max-zoom",qC="OPHEL_ASSISTANT_MERMAID_RENDER_RESPONSE",RC="http://www.w3.org/2000/svg";function PC(e){{const t=window.__OPHEL_USERSCRIPT_ASSET_URLS__?.[e];return "string"==typeof t&&t.length>0?t:null}}function zC(){return "1"===document.documentElement.getAttribute("data-ophel-assistant-mermaid-runner")}function BC(e,t){const n=e.createElementNS(RC,"svg");return n.setAttribute("viewBox",t),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),n.classList.add("gh-assistant-mermaid-btn-icon"),n}class OC{adapter;enabled;stopWatch=null;rescanTimer=null;clickHandler=null;messageHandler=null;fullscreenChangeHandler=null;runtimePromise=null;processedBlocks=new WeakMap;blockPanels=new WeakMap;panelBlocks=new WeakMap;injectedRoots=new WeakSet;pendingRequests=new Map;previewIdCounter=0;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(window.clearInterval(this.rescanTimer),this.rescanTimer=null),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,true),this.clickHandler=null),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.fullscreenChangeHandler&&(document.removeEventListener("fullscreenchange",this.fullscreenChangeHandler),document.removeEventListener("webkitfullscreenchange",this.fullscreenChangeHandler),this.fullscreenChangeHandler=null);for(const e of this.pendingRequests.values())window.clearTimeout(e.timeoutId),e.reject(new Error("Assistant Mermaid renderer stopped"));this.pendingRequests.clear(),this.processedBlocks=new WeakMap,this.blockPanels=new WeakMap,this.panelBlocks=new WeakMap,this.cleanupInjectedPanels();}refreshLocalizedTexts(){os.query(EC,{all:true,shadow:true}).forEach(e=>{if(!(e instanceof HTMLElement))return;const t=e.querySelector("[data-mermaid-action='preview']"),n=e.querySelector("[data-mermaid-action='code']"),r=e.querySelector("[data-mermaid-action='copy']"),o=e.querySelector("[data-mermaid-action='download']"),i=e.querySelector("[data-mermaid-action='zoom-reset']"),a=e.querySelector("[data-mermaid-action='zoom-out']"),s=e.querySelector("[data-mermaid-action='zoom-in']"),l=e.querySelector("[data-mermaid-action='fullscreen']");t&&(t.textContent=se("assistantMermaidPreviewTab")),n&&(n.textContent=se("assistantMermaidCodeTab")),r&&(r.textContent=se("assistantMermaidCopyCode")),o&&(o.textContent=se("assistantMermaidDownloadPng")),i&&this.configureZoomResetButton(i),a&&this.configureZoomOutButton(a),s&&this.configureZoomInButton(s),l&&this.configureFullscreenButton(l);});}init(){if("fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const e=this.getAssistantSelector();e&&(this.injectStyles(document),this.initClickHandler(),this.initMessageHandler(),this.initFullscreenChangeHandler(),this.stopWatch=os.each(e,e=>{this.processResponseElement(e);},{shadow:true}),this.startRescanTimer());}getAssistantSelector(){return this.adapter.getExportConfig()?.assistantResponseSelector||null}initClickHandler(){this.clickHandler||(this.clickHandler=e=>{const t=e.composedPath(),n=t.find(e=>e instanceof HTMLElement&&e.hasAttribute("data-mermaid-action"))||e.target?.closest("[data-mermaid-action]");if(!n)return;const r=t.find(e=>e instanceof HTMLElement&&e.matches(EC))||n.closest(EC);if(!r)return;const o=this.panelBlocks.get(r);if(!o)return;e.preventDefault(),e.stopPropagation();const i=n.dataset.mermaidAction;"preview"!==i&&"code"!==i?"zoom-in"!==i&&"zoom-out"!==i&&"zoom-reset"!==i?"fullscreen"!==i?"copy"!==i?"download"===i&&this.downloadMermaidPng(r).catch(e=>{console.error("[AssistantMermaidRenderer] PNG download failed:",e),Li(se("assistantMermaidDownloadFailed"),2e3);}):this.copyMermaidSource(r).catch(e=>{console.error("[AssistantMermaidRenderer] Copy failed:",e);}):this.togglePreviewFullscreen(r).catch(e=>{console.error("[AssistantMermaidRenderer] Fullscreen failed:",e),Li(se("assistantMermaidFullscreenFailed"),2e3);}):this.adjustPreviewZoom(r,i):this.setView(o,r,i);},document.addEventListener("click",this.clickHandler,true));}initMessageHandler(){this.messageHandler||(this.messageHandler=e=>{const t=e.data;if(e.source!==window&&t?.type!==qC)return;if(t?.type!==qC)return;const n="string"==typeof t.requestId?t.requestId:"";if(!n)return;const r=this.pendingRequests.get(n);r&&(window.clearTimeout(r.timeoutId),this.pendingRequests.delete(n),t.success?r.resolve():r.reject(new Error(t.error||"Mermaid render failed")));},window.addEventListener("message",this.messageHandler));}initFullscreenChangeHandler(){this.fullscreenChangeHandler||(this.fullscreenChangeHandler=()=>{const e=os.query(`${EC}[${LC}='1']`,{shadow:true});if(!e)return;const t=e.querySelector(".gh-assistant-mermaid-preview");t?document.fullscreenElement!==t?this.restorePreviewZoomAfterFullscreen(e):this.fitPreviewToFullscreen(e,t):this.clearFullscreenState(e);},document.addEventListener("fullscreenchange",this.fullscreenChangeHandler),document.addEventListener("webkitfullscreenchange",this.fullscreenChangeHandler));}startRescanTimer(){this.rescanTimer||(window.setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.getAssistantSelector();if(!e)return;const t=os.query(e,{all:true,shadow:true});for(const n of t)this.processResponseElement(n);}processResponseElement(e){if(!this.enabled||"fallback"!==this.adapter.getAssistantMermaidSupportMode())return;const t=e.getRootNode();t instanceof ShadowRoot&&this.injectStyles(t);this.adapter.getAssistantMermaidBlocks(e).forEach(({element:e,source:t})=>{this.processMermaidBlock(e,t);});}async processMermaidBlock(e,t){if(!e.isConnected)return;const n=e.getRootNode();n instanceof ShadowRoot&&this.injectStyles(n);const r=cs(t);if(!r)return;const o=this.getMermaidTheme(),i=`${o}::${r}`;if(this.processedBlocks.get(e)===i)return;const a=this.ensurePanel(e),s=a.querySelector(".gh-assistant-mermaid-preview");if(!s)return;const l=a.dataset.view||"preview",c=this.ensurePreviewId(s),d=this.createRequestId();s.setAttribute(IC,d);try{if(await this.ensureRuntime(),await this.requestRender(d,c,r,o),!e.isConnected)return;if(!a.isConnected||!s.isConnected)return;if(s.getAttribute(IC)!==d)return;a.hidden=!1,a.dataset.source=r,this.setPreviewEnabled(a,!0),this.setDownloadEnabled(a,!0),this.setZoomEnabled(a,!0),this.applyPreviewZoom(a,1),this.processedBlocks.set(e,i),this.setView(e,a,l);}catch(u){if(!e.isConnected||!a.isConnected||!s.isConnected||s.getAttribute(IC)!==d)return;console.warn("[AssistantMermaidRenderer] Mermaid render skipped:",u),!function(e){const t=e instanceof Error?e.message:String(e);return ["runtime asset url is unavailable","failed to load script","runner did not initialize","runtime is unavailable","render timed out","preview container not found"].some(e=>t.toLowerCase().includes(e))}(u)?(this.processedBlocks.set(e,i),this.applyRenderFallback(e,a,r)):(this.processedBlocks.delete(e),this.cleanupPanel(e));}}ensurePanel(e){const t=this.blockPanels.get(e)||(e.previousElementSibling?.matches?.(EC)?e.previousElementSibling:null);if(t?.isConnected)return this.blockPanels.set(e,t),this.panelBlocks.set(t,e),t;const n=document.createElement("div");n.className="gh-assistant-mermaid",n.hidden=true;const r=document.createElement("div");r.className="gh-assistant-mermaid-toolbar";const o=document.createElement("div");o.className="gh-assistant-mermaid-toolbar-group";const i=document.createElement("div");i.className="gh-assistant-mermaid-actions";const a=document.createElement("button");a.type="button",a.className="gh-assistant-mermaid-btn",a.dataset.mermaidAction="preview",a.textContent=se("assistantMermaidPreviewTab");const s=document.createElement("button");s.type="button",s.className="gh-assistant-mermaid-btn",s.dataset.mermaidAction="code",s.textContent=se("assistantMermaidCodeTab");const l=document.createElement("button");l.type="button",l.className="gh-assistant-mermaid-btn",l.dataset.mermaidAction="copy",l.textContent=se("assistantMermaidCopyCode");const c=document.createElement("button");c.type="button",c.className="gh-assistant-mermaid-btn",c.dataset.mermaidAction="download",c.textContent=se("assistantMermaidDownloadPng");const d=document.createElement("div");d.className="gh-assistant-mermaid-toolbar-group";const u=document.createElement("div");u.className="gh-assistant-mermaid-zoom";const h=document.createElement("button");h.type="button",h.className="gh-assistant-mermaid-btn is-icon",h.dataset.mermaidAction="zoom-out",this.configureZoomOutButton(h);const g=document.createElement("button");g.type="button",g.className="gh-assistant-mermaid-btn is-icon",g.dataset.mermaidAction="zoom-reset",this.configureZoomResetButton(g);const p=document.createElement("button");p.type="button",p.className="gh-assistant-mermaid-btn is-icon",p.dataset.mermaidAction="zoom-in",this.configureZoomInButton(p);const m=document.createElement("button");m.type="button",m.className="gh-assistant-mermaid-btn is-icon",m.dataset.mermaidAction="fullscreen",this.configureFullscreenButton(m),u.append(h,g,p,m),o.append(i,u),i.append(a,s),d.append(c,l),r.append(o,d);const f=document.createElement("div");return f.className="gh-assistant-mermaid-preview",this.ensurePreviewId(f),n.append(r,f),e.before(n),e.setAttribute(TC,"true"),e.hasAttribute(MC)||e.setAttribute(MC,e.style.display||""),this.blockPanels.set(e,n),this.panelBlocks.set(n,e),n}configureZoomResetButton(e){const t=se("assistantMermaidFitToPage");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=BC(e,"0 0 24 24"),n=e.createElementNS(RC,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M9 3a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v4.5a1 1 0 0 0 2 0V4h4a1 1 0 0 0 1-1m6 0a1 1 0 0 1 1-1h4a2 2 0 0 1 2 2v4.5a1 1 0 1 1-2 0V4h-4a1 1 0 0 1-1-1m1 19a1 1 0 1 1 0-2h4v-4.5a1 1 0 1 1 2 0V20a2 2 0 0 1-2 2zm-7-1a1 1 0 0 1-1 1H4a2 2 0 0 1-2-2v-4.5a1 1 0 1 1 2 0V20h4a1 1 0 0 1 1 1M8 10h8v4H8zm-2 0a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomOutButton(e){const t=se("assistantMermaidZoomOut");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=BC(e,"0 0 24 24"),n=e.createElementNS(RC,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M10.5 17a6.5 6.5 0 1 0 0-13 6.5 6.5 0 0 0 0 13m0 2a8.46 8.46 0 0 0 5.263-1.825l.03.032 5 5a1 1 0 0 0 1.414-1.414l-5-5-.032-.03A8.5 8.5 0 1 0 10.5 19M8 9.5a1 1 0 0 0 0 2h5a1 1 0 1 0 0-2z"),t.appendChild(n),t}(e.ownerDocument||document));}configureZoomInButton(e){const t=se("assistantMermaidZoomIn");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=BC(e,"0 0 24 24"),n=e.createElementNS(RC,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("fill-rule","evenodd"),n.setAttribute("clip-rule","evenodd"),n.setAttribute("d","M17 10.5a6.5 6.5 0 1 1-13 0 6.5 6.5 0 0 1 13 0m-1.237 6.675a8.5 8.5 0 1 1 1.413-1.413l.031.03 5 5a1 1 0 0 1-1.414 1.415l-5-5zM7 10.5a1 1 0 0 1 1-1h1.5V8a1 1 0 0 1 2 0v1.5H13a1 1 0 1 1 0 2h-1.5V13a1 1 0 1 1-2 0v-1.5H8a1 1 0 0 1-1-1"),t.appendChild(n),t}(e.ownerDocument||document));}configureFullscreenButton(e){const t=se("assistantMermaidFullscreen");e.classList.add("is-icon"),e.setAttribute("aria-label",t),e.title=t,e.replaceChildren(function(e){const t=BC(e,"0 0 24 24"),n=e.createElementNS(RC,"path");return n.setAttribute("fill","currentColor"),n.setAttribute("d","M22 3v7a1 1 0 1 1-2 0V4h-6a1 1 0 1 1 0-2h7a1 1 0 0 1 1 1M11.005 21a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-7a1 1 0 0 1 2.002 0v6h6.003a1 1 0 0 1 1 1"),t.appendChild(n),t}(e.ownerDocument||document));}ensurePreviewId(e){const t=e.getAttribute(_C);if(t)return t;this.previewIdCounter+=1;const n=`gh-assistant-mermaid-preview-${Date.now()}-${this.previewIdCounter}`;return e.setAttribute(_C,n),n}setView(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");if(!r)return;t.dataset.view=n,r.hidden="preview"!==n,e.style.display="preview"===n?"none":e.getAttribute(MC)||"";t.querySelectorAll("[data-mermaid-action='preview'], [data-mermaid-action='code']").forEach(e=>{e instanceof HTMLElement&&e.classList.toggle("is-active",e.dataset.mermaidAction===n);});}setPreviewEnabled(e,t){const n=e.querySelector("[data-mermaid-action='preview']");n&&(n.disabled=!t);}setZoomEnabled(e,t){e.querySelectorAll("[data-mermaid-action='zoom-out'], [data-mermaid-action='zoom-reset'], [data-mermaid-action='zoom-in'], [data-mermaid-action='fullscreen']").forEach(e=>{e instanceof HTMLButtonElement&&(e.disabled=!t);});}setDownloadEnabled(e,t){const n=e.querySelector("[data-mermaid-action='download']");n&&(n.disabled=!t);}adjustPreviewZoom(e,t){const n=Number.parseFloat(e.dataset.zoom||"1");if("zoom-reset"===t)return void this.applyPreviewZoom(e,1);const r="zoom-in"===t?n+.25:n-.25;this.applyPreviewZoom(e,r);}applyPreviewZoom(e,t){const n=e.querySelector(".gh-assistant-mermaid-preview"),r=n?.querySelector("svg");if(!n||!r)return void this.setZoomEnabled(e,false);const o=Math.min(this.getMaxPreviewZoom(e),Math.max(.5,t));e.dataset.zoom=`${o}`;const i=this.getPreviewBaseWidth(r);r.style.maxWidth="none",r.style.width=`${Math.max(1,Math.round(i*o))}px`,r.style.height="auto",this.updateZoomButtonState(e,o);}getMaxPreviewZoom(e){const t=Number.parseFloat(e.getAttribute(DC)||"");return Math.max(3,Number.isFinite(t)?t:0)}getPreviewBaseWidth(e){const t=Number.parseFloat(e.dataset.ophelBaseWidth||"");if(Number.isFinite(t)&&t>0)return t;const n=e.getBoundingClientRect().width,r=Number.parseFloat(e.getAttribute("width")||"")||e.viewBox?.baseVal?.width||320,o=n>0?n:r;return e.dataset.ophelBaseWidth=`${o}`,o}getPreviewBaseDimensions(e){const t=this.getPreviewBaseWidth(e),n=e.getBoundingClientRect(),r=Number.parseFloat(e.getAttribute("width")||""),o=Number.parseFloat(e.getAttribute("height")||""),i=e.viewBox?.baseVal?.width||0,a=e.viewBox?.baseVal?.height||0;return {width:t,height:t*(i>0&&a>0&&a/i||n.width>0&&n.height>0&&n.height/n.width||r>0&&o>0&&o/r||.75)}}updateZoomButtonState(e,t){const n=e.querySelector("[data-mermaid-action='zoom-out']"),r=e.querySelector("[data-mermaid-action='zoom-reset']"),o=e.querySelector("[data-mermaid-action='zoom-in']"),i=this.getMaxPreviewZoom(e);n&&(n.disabled=t<=.5),r&&(r.disabled=Math.abs(t-1)<.001),o&&(o.disabled=t>=i);}applyRenderFallback(e,t,n){const r=t.querySelector(".gh-assistant-mermaid-preview");r&&r.replaceChildren(),t.hidden=false,t.dataset.source=n,this.setPreviewEnabled(t,false),this.setDownloadEnabled(t,false),this.setZoomEnabled(t,false),this.setView(e,t,"code");}async togglePreviewFullscreen(e){const t=e.querySelector(".gh-assistant-mermaid-preview");if(!t)throw new Error("Mermaid preview container not found");const n=this.panelBlocks.get(e);if(n&&"preview"!==e.dataset.view&&this.setView(n,e,"preview"),document.fullscreenElement!==t){if("function"!=typeof t.requestFullscreen)throw new Error("Fullscreen API is unavailable");e.setAttribute(LC,"1"),e.setAttribute(NC,e.dataset.zoom||"1");try{await t.requestFullscreen();}catch(r){throw this.clearFullscreenState(e),r}}else await document.exitFullscreen();}fitPreviewToFullscreen(e,t){const n=t.querySelector("svg");if(!n)return void this.setZoomEnabled(e,false);const{width:r,height:o}=this.getPreviewBaseDimensions(n);if(r<=0||o<=0)return;const i=Math.max(1,t.clientWidth-48),a=Math.max(1,t.clientHeight-48),s=Math.min(i/r,a/o);e.setAttribute(DC,`${Math.max(3,s)}`),this.applyPreviewZoom(e,s),t.scrollTop=0,t.scrollLeft=0;}restorePreviewZoomAfterFullscreen(e){const t=Number.parseFloat(e.getAttribute(NC)||"")||1;this.clearFullscreenState(e),this.applyPreviewZoom(e,t);}clearFullscreenState(e){e.removeAttribute(LC),e.removeAttribute(NC),e.removeAttribute(DC);}async copyMermaidSource(e){const t=e.dataset.source||"";t&&(await navigator.clipboard.writeText(t),Li(se("copySuccess"),1500));}async downloadMermaidPng(e){const t=e.querySelector(".gh-assistant-mermaid-preview"),n=t?.querySelector("svg");if(!n)throw new Error("Mermaid preview svg not found");const{width:r,height:o}=this.getSvgExportDimensions(n),i=Math.max(1,Math.round(r)),a=Math.max(1,Math.round(o));let s;try{s=await this.renderSvgToPngBlob(n,i,a);}catch(c){if(!n.querySelector("foreignObject")||!function(e){const t=e instanceof Error?e.message:String(e),n=e instanceof DOMException||e instanceof Error?e.name:"",r=t.toLowerCase();return n.toLowerCase().includes("securityerror")||r.includes("tainted canvas")||r.includes("tainted canvases may not be exported")}(c))throw c;s=await this.renderSvgToPngBlob(n,i,a,{downgradeForeignObjects:true});}const l=URL.createObjectURL(s);try{const e=document.createElement("a");e.href=l,e.download=this.createPngFilename(),e.click();}finally{URL.revokeObjectURL(l);}Li(se("assistantMermaidDownloadSuccess"),1500);}getSvgExportDimensions(e){const t=e.getBoundingClientRect(),n=Number.parseFloat(e.style.width||""),r=Number.parseFloat(e.style.height||""),o=Number.parseFloat(e.getAttribute("width")||""),i=Number.parseFloat(e.getAttribute("height")||""),a=e.viewBox?.baseVal?.width||0,s=e.viewBox?.baseVal?.height||0,l=t.width||n||o||this.getPreviewBaseWidth(e)||a||320;return {width:l,height:l*(t.width>0&&t.height>0&&t.height/t.width||n>0&&r>0&&r/n||o>0&&i>0&&i/o||a>0&&s>0&&s/a||.75)}}serializeSvgForPng(e,t,n,r={}){const o=e.cloneNode(true);return o.setAttribute("xmlns",RC),o.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.style.width=`${t}px`,o.style.height=`${n}px`,o.style.maxWidth="none",r.downgradeForeignObjects&&this.downgradeForeignObjectsForPng(e,o),(new XMLSerializer).serializeToString(o)}async renderSvgToPngBlob(e,t,n,r={}){const o=this.serializeSvgForPng(e,t,n,r),i=URL.createObjectURL(new Blob([o],{type:"image/svg+xml;charset=utf-8"}));try{const e=await this.loadSvgImage(i),r=document.createElement("canvas");r.width=Math.ceil(2*(t+48)),r.height=Math.ceil(2*(n+48));const o=r.getContext("2d");if(!o)throw new Error("Canvas 2D context is unavailable");return o.scale(2,2),o.fillStyle="dark"===this.getMermaidTheme()?"#0f172a":"#ffffff",o.fillRect(0,0,r.width/2,r.height/2),o.drawImage(e,24,24,t,n),await this.canvasToBlob(r)}finally{URL.revokeObjectURL(i);}}downgradeForeignObjectsForPng(e,t){const n=Array.from(e.querySelectorAll("foreignObject"));Array.from(t.querySelectorAll("foreignObject")).forEach((e,r)=>{const o=this.createForeignObjectTextFallback(n[r],t.ownerDocument);e.replaceWith(o);});}createForeignObjectTextFallback(e,t){const n=t.createElementNS(RC,"g");if(!e)return n;const r=this.getForeignObjectMetric(e,"x"),o=this.getForeignObjectMetric(e,"y"),i=this.getForeignObjectMetric(e,"width"),a=this.getForeignObjectMetric(e,"height"),s=this.getForeignObjectLines(e);if(0===s.length||i<=0||a<=0)return n;const l=e.querySelector("*")||null,c=l?window.getComputedStyle(l):null,d=Math.max(10,Number.parseFloat(c?.fontSize||"")||Math.min(16,Math.max(12,.35*a))),u=Number.parseFloat(c?.lineHeight||"")||Math.max(1.2*d,a/Math.max(s.length,1)),h=r+i/2,g=o+a/2-(s.length-1)*u/2,p=c?.color||("dark"===this.getMermaidTheme()?"#e5e7eb":"#111827"),m=c?.fontFamily||"Arial, sans-serif",f=c?.fontWeight||"400";return s.forEach((e,r)=>{const o=t.createElementNS(RC,"text");o.setAttribute("x",`${h}`),o.setAttribute("y",`${g+r*u}`),o.setAttribute("text-anchor","middle"),o.setAttribute("dominant-baseline","middle"),o.setAttribute("fill",p),o.setAttribute("font-size",`${d}`),o.setAttribute("font-family",m),o.setAttribute("font-weight",f),o.textContent=e,n.appendChild(o);}),n}getForeignObjectMetric(e,t){const n=Number.parseFloat(e.getAttribute(t)||"");if(Number.isFinite(n))return n;const r=e instanceof SVGGraphicsElement?e.getBBox():{x:0,y:0,width:0,height:0};return "x"===t?r.x:"y"===t?r.y:"width"===t?r.width:"height"===t?r.height:0}getForeignObjectLines(e){const t=e.querySelector("*")||null;return (t&&"string"==typeof t.innerText&&t.innerText||t?.textContent||e.textContent||"").replace(/\r\n/g,"\n").split("\n").map(e=>e.replace(/\s+/g," ").trim()).filter(Boolean)}loadSvgImage(e){return new Promise((t,n)=>{const r=new Image;r.decoding="async",r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load Mermaid SVG image")),r.src=e;})}canvasToBlob(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(new Error("Failed to convert Mermaid canvas to PNG blob"));},"image/png");})}createPngFilename(){return `ophel-mermaid-${(new Date).toISOString().replace(/[:.]/g,"-")}.png`}cleanupInjectedPanels(){os.query(`[${TC}]`,{all:true,shadow:true}).forEach(e=>{e instanceof HTMLElement&&(e.style.display=e.getAttribute(MC)||"",e.removeAttribute(TC),e.removeAttribute(MC));});os.query(EC,{all:true,shadow:true}).forEach(e=>e.remove());}cleanupPanel(e){const t=this.blockPanels.get(e);t?.isConnected&&t.remove(),e.style.display=e.getAttribute(MC)||"",e.removeAttribute(TC),e.removeAttribute(MC);}injectStyles(e){if(this.injectedRoots.has(e))return;if(e.querySelector?.(`#${AC}`))return;const t=document.createElement("style");t.id=AC,t.textContent="\n.gh-assistant-mermaid {\n margin: 12px 0;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n border-radius: 10px;\n background: var(--gh-bg-secondary, rgba(255, 255, 255, 0.9));\n overflow: hidden;\n}\n\n.gh-assistant-mermaid-toolbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n padding: 8px 10px;\n border-bottom: 1px solid var(--gh-border, rgba(148, 163, 184, 0.2));\n background: var(--gh-bg-primary, rgba(248, 250, 252, 0.96));\n}\n\n.gh-assistant-mermaid-actions {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-toolbar-group {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-zoom {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n}\n\n.gh-assistant-mermaid-btn {\n appearance: none;\n border: 1px solid var(--gh-border, rgba(148, 163, 184, 0.28));\n background: transparent;\n color: var(--gh-text-secondary, #64748b);\n border-radius: 999px;\n padding: 4px 10px;\n font-size: 12px;\n line-height: 1.4;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;\n}\n\n.gh-assistant-mermaid-btn.is-icon {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 30px;\n padding: 4px 8px;\n}\n\n.gh-assistant-mermaid-btn-icon {\n width: 14px;\n height: 14px;\n display: block;\n flex: 0 0 auto;\n}\n\n.gh-assistant-mermaid-btn:hover {\n background: rgba(59, 130, 246, 0.08);\n color: var(--gh-text, #0f172a);\n border-color: rgba(59, 130, 246, 0.28);\n}\n\n.gh-assistant-mermaid-btn.is-active {\n background: rgba(59, 130, 246, 0.14);\n color: #2563eb;\n border-color: rgba(59, 130, 246, 0.3);\n}\n\n.gh-assistant-mermaid-btn:disabled {\n opacity: 0.56;\n cursor: not-allowed;\n}\n\n.gh-assistant-mermaid-preview {\n padding: 12px;\n overflow-x: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.96));\n}\n\n.gh-assistant-mermaid-preview:fullscreen,\n.gh-assistant-mermaid-preview:-webkit-full-screen {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100%;\n height: 100%;\n padding: 24px;\n box-sizing: border-box;\n overflow: auto;\n background: var(--gh-bg-primary, rgba(255, 255, 255, 0.98));\n}\n\n.gh-assistant-mermaid-preview[hidden] {\n display: none !important;\n}\n\n.gh-assistant-mermaid-preview svg {\n display: block;\n max-width: 100%;\n height: auto;\n margin: 0 auto;\n}\n\n.gh-assistant-mermaid-preview:fullscreen svg,\n.gh-assistant-mermaid-preview:-webkit-full-screen svg {\n margin: auto;\n flex: 0 0 auto;\n}\n\nbody.dark-theme .gh-assistant-mermaid,\nhtml.dark .gh-assistant-mermaid,\nhtml[dark-theme] .gh-assistant-mermaid {\n background: rgba(15, 23, 42, 0.88);\n}\n\nbody.dark-theme .gh-assistant-mermaid-toolbar,\nhtml.dark .gh-assistant-mermaid-toolbar,\nhtml[dark-theme] .gh-assistant-mermaid-toolbar,\nbody.dark-theme .gh-assistant-mermaid-preview,\nhtml.dark .gh-assistant-mermaid-preview,\nhtml[dark-theme] .gh-assistant-mermaid-preview {\n background: rgba(15, 23, 42, 0.92);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn,\nhtml.dark .gh-assistant-mermaid-btn,\nhtml[dark-theme] .gh-assistant-mermaid-btn {\n color: rgba(226, 232, 240, 0.82);\n border-color: rgba(148, 163, 184, 0.26);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn:hover,\nhtml.dark .gh-assistant-mermaid-btn:hover,\nhtml[dark-theme] .gh-assistant-mermaid-btn:hover {\n color: #eff6ff;\n background: rgba(59, 130, 246, 0.18);\n}\n\nbody.dark-theme .gh-assistant-mermaid-btn.is-active,\nhtml.dark .gh-assistant-mermaid-btn.is-active,\nhtml[dark-theme] .gh-assistant-mermaid-btn.is-active {\n color: #93c5fd;\n}\n",e instanceof ShadowRoot?e.prepend(t):document.head.appendChild(t),this.injectedRoots.add(e);}getMermaidTheme(){const e=document.documentElement.className,t=document.body.className,n=/\bdark\b/i.test(e),r=/\bdark-theme\b/i.test(t),o=document.documentElement.hasAttribute("dark-theme");return n||r||o?"dark":"default"}createRequestId(){return `gh-assistant-mermaid-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}async ensureRuntime(){if(!zC())return this.runtimePromise||(this.runtimePromise=(async()=>{const e=PC("assistantMermaidVendor"),t=PC("assistantMermaidRunner");if(!e||!t)throw new Error("Assistant Mermaid runtime asset URL is unavailable");if(await this.injectScript(e,"ophel-assistant-mermaid-vendor"),await this.injectScript(t,"ophel-assistant-mermaid-runner"),!zC())throw new Error("Assistant Mermaid runner did not initialize")})().catch(e=>{throw this.runtimePromise=null,e})),this.runtimePromise}injectScript(e,t){const n=`script[data-ophel-runtime="${t}"]`,r=document.querySelector(n);return "true"===r?.dataset.loaded?Promise.resolve():new Promise((n,o)=>{const i=r||document.createElement("script"),a=()=>{i.removeEventListener("load",s),i.removeEventListener("error",l);},s=()=>{a(),i.dataset.loaded="true",n();},l=()=>{a(),o(new Error(`Failed to load script: ${e}`));};i.addEventListener("load",s,{once:true}),i.addEventListener("error",l,{once:true});try{i.dataset.ophelRuntime=t,i.dataset.loaded="false",i.async=!1;if((i.getAttribute("src")||i.src)!==e&&!zp(i,e))throw new Error(`Failed to set trusted script src: ${e}`);r||(document.head||document.documentElement).appendChild(i);}catch(c){a(),o(c instanceof Error?c:new Error(`Failed to load script: ${e}`));}})}requestRender(e,t,n,r){return new Promise((o,i)=>{const a=window.setTimeout(()=>{this.pendingRequests.delete(e),i(new Error("Assistant Mermaid render timed out"));},15e3);this.pendingRequests.set(e,{resolve:o,reject:i,timeoutId:a}),window.postMessage({type:"OPHEL_ASSISTANT_MERMAID_RENDER_REQUEST",requestId:e,previewId:t,source:n,theme:r},"*");})}}const FC="ghTableCopy",$C=[".ProseMirror",".ql-editor",".cm-editor",".monaco-editor"],UC=".gh-user-query-markdown, .gh-markdown-preview";class jC{settings;siteAdapter=null;formulaCopyInitialized=false;tableCopyInitialized=false;formulaDblClickHandler=null;stopTableWatch=null;rescanTimer=null;static FORMULA_HOST_SELECTOR=[".math-block",".math-inline",".katex",".katex-display","math","[data-math]","[data-custom-copy-text]",'annotation[encoding="application/x-tex"]'].join(", ");constructor(e,t){this.settings=e,this.siteAdapter=t||null;}updateSettings(e){e.formulaCopy!==this.settings.formulaCopy&&(e.formulaCopy?(this.settings=e,this.initFormulaCopy()):this.destroyFormulaCopy()),e.tableCopy!==this.settings.tableCopy&&(e.tableCopy?(this.settings=e,this.initTableCopy()):this.destroyTableCopy()),this.settings=e;}initFormulaCopy(){if(this.formulaCopyInitialized)return;this.formulaCopyInitialized=true;const e=false!==this.siteAdapter?.supportsFormulaCopy(),t="gh-formula-copy-style";if(e&&!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent="\n .math-block, .math-inline, .katex {\n user-select: none !important;\n cursor: pointer !important;\n }\n .math-block:hover, .math-inline:hover, .katex:hover {\n outline: none !important;\n box-shadow: inset 0 0 0 2px #4285f4;\n border-radius: 4px;\n }\n .math-block:hover .katex,\n .math-inline:hover .katex {\n outline: none !important;\n box-shadow: none !important;\n }\n ",document.head.appendChild(e);}this.formulaDblClickHandler=t=>{const n=t.target instanceof Element?t.target:t.target instanceof Node?t.target.parentElement:null;if(n)try{const r=n.closest(jC.FORMULA_HOST_SELECTOR);if(!r)return;if(!e)return Li(se("formulaFormatUnsupported")),t.preventDefault(),void t.stopPropagation();const o=this.extractFormulaCopyPayload(n,r);if(o?.latex||o?.mathml)return this.copyFormula(o),t.preventDefault(),void t.stopPropagation();Li(se("formulaSourceUnavailable")),t.preventDefault(),t.stopPropagation();}catch(r){console.error("[FormulaCopy] Unexpected error:",r),Li(se("copyFailed"));}},document.addEventListener("dblclick",this.formulaDblClickHandler,true);}extractFormulaCopyPayload(e,t){const n=this.siteAdapter?.extractFormulaCopySource(e,t),r=this.normalizeFormulaCopySource(n);if(r)return r;const o=t.closest(".math-block, .math-inline, [data-math], [data-custom-copy-text]");if(o){const e=this.unwrapMathDelimiters(o.getAttribute("data-math")||o.getAttribute("data-custom-copy-text")||o.getAttribute("copy-text")||""),t=this.serializeMathElement(o.querySelector("math"));if(e||t)return {latex:e,mathml:t,isBlock:o.classList.contains("math-block")||o.matches(".math-block")||this.isBlockMathElement(o)}}const i=t.closest(".katex, .katex-display")||e.closest(".katex, .katex-display"),a=t.closest("math")||e.closest("math")||i?.querySelector("math")||null,s=t.matches('annotation[encoding="application/x-tex"]')?t:i?.querySelector('annotation[encoding="application/x-tex"]')||a?.querySelector('annotation[encoding="application/x-tex"]')||null,l=this.unwrapMathDelimiters(s?.textContent||""),c=this.serializeMathElement(a);return l||c?{latex:l,mathml:c,isBlock:!!i?.closest(".katex-display")||this.isBlockMathElement(a)}:null}normalizeFormulaCopySource(e){if(!e)return null;const t=this.unwrapMathDelimiters(e.latex||""),n=e.mathml?.trim()||"";return t||n?{latex:t,mathml:n,isBlock:e.isBlock??this.isBlockMathml(n)}:null}isBlockMathElement(e){return !!e&&"block"===e.getAttribute("display")}isBlockMathml(e){return /\sdisplay=(["'])block\1/i.test(e)}serializeMathElement(e){if(!e)return "";try{return (new XMLSerializer).serializeToString(e).trim()}catch(t){return console.warn("[FormulaCopy] Failed to serialize MathML:",t),e instanceof HTMLElement?e.outerHTML.trim():""}}unwrapMathDelimiters(e){const t=e.trim();if(!t)return "";const n=[["$$","$$"],["\\(","\\)"],["\\[","\\]"],["$","$"]];for(const[r,o]of n)if(t.startsWith(r)&&t.endsWith(o)&&t.length>r.length+o.length)return t.slice(r.length,t.length-o.length).trim();return t}copyFormula(e){if("latex"===("mathml"===this.settings.formulaCopyFormat?"mathml":"latex"))return e.latex?void this.copyLatex(e.latex,e.isBlock):void Li(se("formulaSourceUnavailable"));const t=e.mathml||this.renderLatexToMathml(e.latex||"",e.isBlock);t?this.copyText(t):Li(se("formulaFormatUnsupported"));}copyLatex(e,t){const n=e.replace(/\r\n?/g,"\n").trim();let r=n;if(this.settings.formulaDelimiter){const e=t&&(n.includes("\n")||/(^|[^\\])\\\\($|[^\\])/.test(n));r=t?e?`$$\n${n}\n$$`:`$$${n}$$`:`$${n}$`;}this.copyText(r);}renderLatexToMathml(e,t){const n=e.replace(/\r\n?/g,"\n").trim();if(!n)return "";try{const e=Fh(n,{displayMode:t}),r=document.createElement("template");return r.innerHTML=e,this.serializeMathElement(r.content.querySelector("math"))}catch(r){return console.warn("[FormulaCopy] Failed to convert LaTeX to MathML:",r),""}}copyText(e){navigator.clipboard?.writeText?navigator.clipboard.writeText(e).then(()=>Li(se("formulaCopied"))).catch(e=>{console.error("[FormulaCopy] Copy failed:",e),Li(se("copyFailed"));}):Li(se("copyFailed"));}destroyFormulaCopy(){this.formulaCopyInitialized=false;const e=document.getElementById("gh-formula-copy-style");e&&e.remove(),this.formulaDblClickHandler&&(document.removeEventListener("dblclick",this.formulaDblClickHandler,true),this.formulaDblClickHandler=null);}initTableCopy(){if(this.tableCopyInitialized)return;this.tableCopyInitialized=true;const e="gh-table-copy-style";if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent="\n .gh-table-copy-btn {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 28px;\n height: 28px;\n border: none;\n border-radius: 6px;\n background: rgba(255,255,255,0.9);\n color: #374151;\n cursor: pointer;\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n transition: opacity 0.2s, background 0.2s;\n z-index: 10;\n box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n }\n .gh-table-container:hover .gh-table-copy-btn,\n table-block:hover .gh-table-copy-btn,\n ucs-markdown-table:hover .gh-table-copy-btn {\n opacity: 1;\n }\n .gh-table-copy-btn:hover {\n background: #4285f4;\n color: white;\n }\n ",document.head.appendChild(t);}this.siteAdapter?.usesShadowDOM()??false?this.startRescanTimer():this.stopTableWatch=os.each("table",e=>{this.injectTableButton(e);},{shadow:true});}startRescanTimer(){this.rescanTables(),this.rescanTimer=setInterval(()=>{this.rescanTables();},1e3);}rescanTables(){if(document.hidden)return;const e=os.query("table",{all:true,shadow:true});for(const t of e)this.injectTableButton(t);}injectTableButton(e){if(e.dataset[FC])return;const t=!!e.closest(UC);if(t||!this.isTableInsideEditableHost(e))try{let n;if(t)n=e,e.style.position="relative";else {if(n=e.closest("table-block, ucs-markdown-table"),!n){if(n=e.parentNode,!n)return;n.classList.add("gh-table-container");}n.style.position="relative";}const r=document.createElement("button");r.className="gh-table-copy-btn",r.appendChild(pp({size:14,color:"#6b7280"})),r.title=se("tableCopyLabel");const o=n.tagName?.toLowerCase(),i="ucs-markdown-table"===o||n.closest("ucs-markdown-table")||n.classList.contains("gh-table-container")?"80px":"4px";Object.assign(r.style,{position:"absolute",top:"4px",right:i,width:"28px",height:"28px",border:"none",borderRadius:"6px",background:"rgba(255,255,255,0.9)",color:"#374151",cursor:"pointer",fontSize:"14px",display:"flex",alignItems:"center",justifyContent:"center",opacity:"0.6",transition:"opacity 0.2s, background 0.2s, transform 0.2s",zIndex:"10",boxShadow:"0 1px 3px rgba(0,0,0,0.1)",pointerEvents:"auto"}),r.addEventListener("mouseenter",()=>{r.style.opacity="1",r.style.transform="scale(1.1)";}),r.addEventListener("mouseleave",()=>{r.style.opacity="0.6",r.style.transform="scale(1)";}),r.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation();const n=this.tableToMarkdown(e);navigator.clipboard.writeText(n).then(()=>{Li(se("tableCopied")),mp(r,{size:14});}).catch(e=>{console.error("[TableCopy] Copy failed:",e),Li(se("copyFailed"));});}),n.appendChild(r),e.dataset[FC]="true";}catch(n){console.error("[TableCopy] Error injecting button:",n);}}isTableInsideEditableHost(e){let t=e;for(;t;){if(t instanceof HTMLElement){if(t.matches(UC))return false;if(this.isEditableHost(t))return true}t=os.getComposedParent(t);}return false}isEditableHost(e){if(e.isContentEditable)return true;if("textbox"===e.getAttribute("role"))return true;if($C.some(t=>{try{return e.matches(t)}catch{return false}}))return true;const t=e.getAttribute("contenteditable");return !!t&&"false"!==t.toLowerCase()}tableToMarkdown(e){const t=e.querySelectorAll("tr");if(0===t.length)return "";const n=[];let r=false;const o=e=>{if(this.settings.formulaCopy){const t=e.cloneNode(true);return t.querySelectorAll(".math-block, .math-inline").forEach(e=>{const t=e,n=t.getAttribute("data-math");if(n){const e=t.classList.contains("math-block");let r;r=this.settings.formulaDelimiter?e?`$$${n}$$`:`$${n}$`:n,t.replaceWith(document.createTextNode(r));}}),t.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""}return e.innerText?.trim().replace(/\|/g,"\\|").replace(/\n/g," ")||""};return t.forEach((e,t)=>{const i=e.querySelectorAll("th, td"),a=Array.from(i).map(e=>o(e));if(n.push("| "+a.join(" | ")+" |"),!r&&(e.querySelector("th")||0===t)){const e=Array.from(i).map(e=>e.classList.contains("align-center")?":---:":e.classList.contains("align-right")?"---:":"---");n.push("| "+e.join(" | ")+" |"),r=true;}}),n.join("\n")}destroyTableCopy(){this.tableCopyInitialized=false,this.stopTableWatch&&(this.stopTableWatch(),this.stopTableWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);const e=document.getElementById("gh-table-copy-style");e&&e.remove(),os.query(".gh-table-copy-btn",{all:true,shadow:true})?.forEach(e=>e.remove()),os.query("[data-gh-table-copy]",{all:true,shadow:true})?.forEach(e=>{e instanceof HTMLElement&&e.removeAttribute("data-gh-table-copy");}),os.query(".gh-table-container",{all:true,shadow:true})?.forEach(e=>{e.classList.remove("gh-table-container");});}stop(){this.destroyFormulaCopy(),this.destroyTableCopy();}}const HC="gh-page-width-styles",WC="gh-page-width-shadow",GC="gh-user-query-width-styles",QC="gh-user-query-width-shadow",VC="gh-zen-mode-styles",KC="gh-zen-mode-shadow",ZC="gh-clean-mode-styles",YC="gh-clean-mode-shadow",JC="gh-zen-mode-exit-host";class XC{siteAdapter;pageWidthConfig;userQueryWidthConfig=null;pageWidthStyle=null;userQueryWidthStyle=null;zenModeStyle=null;zenModeEnabled=false;zenModeExitHost=null;zenModeRootClassState=null;cleanModeStyle=null;cleanModeEnabled=false;processedShadowRoots=new WeakSet;shadowCheckInterval=null;constructor(e,t){this.siteAdapter=e,this.pageWidthConfig=t;}updateConfig(e){this.pageWidthConfig=e,this.apply();}apply(){if(this.removeStyle(this.pageWidthStyle),this.pageWidthStyle=null,!this.pageWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generatePageWidthCSS();this.pageWidthStyle=this.injectStyle(HC,e),this.refreshShadowInjection();}updateUserQueryConfig(e){this.userQueryWidthConfig=e,this.applyUserQueryWidth();}applyUserQueryWidth(){if(this.removeStyle(this.userQueryWidthStyle),this.userQueryWidthStyle=null,!this.userQueryWidthConfig?.enabled)return void this.refreshShadowInjection();const e=this.generateUserQueryWidthCSS();this.userQueryWidthStyle=this.injectStyle(GC,e),this.refreshShadowInjection();}updateZenMode(e){this.zenModeEnabled=e,this.applyZenMode();}applyZenMode(){if(this.removeStyle(this.zenModeStyle),this.zenModeStyle=null,!this.zenModeEnabled)return this.cleanupZenModeRootClass(),this.unmountZenModeExitButton(),void this.refreshShadowInjection();this.syncZenModeRootClass();const e=this.generateZenModeCSS();e&&(this.zenModeStyle=this.injectStyle(VC,e)),this.mountZenModeExitButton(),this.refreshShadowInjection();}updateCleanMode(e){this.cleanModeEnabled=e,this.applyCleanMode();}applyCleanMode(){if(this.removeStyle(this.cleanModeStyle),this.cleanModeStyle=null,!this.cleanModeEnabled)return void this.refreshShadowInjection();const e=this.generateCleanModeCSS();e&&(this.cleanModeStyle=this.injectStyle(ZC,e)),this.refreshShadowInjection();}generatePageWidthCSS(){const e=`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,t=this.siteAdapter.getWidthSelectors(),n=this.buildCSSFromSelectors(t,e,true);if("%"===this.pageWidthConfig.unit){return `${n}\n@media (max-width: 480px) {\n${this.buildCSSFromSelectors(t,"95%",true)}\n}`}return n}generateUserQueryWidthCSS(){if(!this.userQueryWidthConfig)return "";const e=`${this.userQueryWidthConfig.value||"81"}${this.userQueryWidthConfig.unit||"%"}`,t=this.siteAdapter.getUserQueryWidthSelectors();return this.buildCSSFromSelectors(t,e,false)}generateZenModeCSS(){const e=this.siteAdapter.getZenModeConfig(),t=this.siteAdapter.getCleanModeConfig();if(!e&&!t)return "";const n=[...e?.hide||[],...t?.hide||[]],r=[...e?.styles||[],...t?.styles||[]];return [n.map(e=>`${e} { display: none !important; }`).join("\n"),this.buildZenModeStyleCSS(r)].filter(Boolean).join("\n")}generateCleanModeCSS(){const e=this.siteAdapter.getCleanModeConfig();if(!e)return "";return [(e.hide||[]).map(e=>`${e} { display: none !important; }`).join("\n"),this.buildZenModeStyleCSS(e.styles||[])].filter(Boolean).join("\n")}buildCSSFromSelectors(e,t,n){return e.map(e=>{const{selector:r,globalSelector:o,property:i,value:a,transformValue:s,extraCss:l,noCenter:c}=e,d=a||t,u=s?s(d):d;return `${n&&o||r} { ${i}: ${u} !important; ${c?"":"margin-left: auto !important; margin-right: auto !important;"} ${l||""} }`}).join("\n")}injectStyle(e,t){const n=document.createElement("style");return n.id=e,n.textContent=t,document.head.appendChild(n),n}removeStyle(e){e&&e.remove();}buildZenModeStyleCSS(e){return e.map(e=>{const t=e.globalSelector||e.selector,n=e.extraCss||"";return `${t} { ${e.property}: ${e.value} !important; ${n} }`}).join("\n")}syncZenModeRootClass(){const e=this.siteAdapter.getZenModeConfig()?.rootClass;if(!e)return;const t=this.zenModeRootClassState;if(!t||t.selector!==e.selector||t.className!==e.className){const t=document.querySelector(e.selector);if(!(t instanceof HTMLElement))return;this.zenModeRootClassState={selector:e.selector,className:e.className,removeOnDisable:!t.classList.contains(e.className)};}document.querySelectorAll(e.selector).forEach(t=>{t instanceof HTMLElement&&!t.classList.contains(e.className)&&t.classList.add(e.className);});}cleanupZenModeRootClass(){if(!this.zenModeRootClassState?.removeOnDisable)return void(this.zenModeRootClassState=null);const{selector:e,className:t}=this.zenModeRootClassState;document.querySelectorAll(e).forEach(e=>{e instanceof HTMLElement&&e.classList.remove(t);}),this.zenModeRootClassState=null;}mountZenModeExitButton(){if(!document.body)return;if(this.zenModeExitHost?.isConnected)return;const e=document.getElementById(JC);e instanceof HTMLElement&&e.remove();const t=document.createElement("div");t.id=JC,t.style.cssText=["position: fixed","z-index: 2147483647","pointer-events: auto"].join(";");const n=this.siteAdapter.getThemeColors().primary||"#2563eb",r=se("zenModeExitButton"),o=t.attachShadow({mode:"open"});o.innerHTML=qp(`\n \n \n `);const i=o.querySelector(".zen-exit-btn");i?.addEventListener("click",this.handleZenModeExit),document.body.appendChild(t),this.zenModeExitHost=t;}unmountZenModeExitButton(){if(this.zenModeExitHost?.shadowRoot){const e=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-btn");e?.removeEventListener("click",this.handleZenModeExit);}this.zenModeExitHost?.remove(),this.zenModeExitHost=null;}handleZenModeExit=()=>{const e=this.siteAdapter.getSiteId();this.updateZenMode(false),Ai.getState().updateDeepSetting("layout","zenMode",e,{enabled:false});};refreshLocalizedTexts(){if(!this.zenModeEnabled||!this.zenModeExitHost?.shadowRoot)return;const e=se("zenModeExitButton"),t=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-text"),n=this.zenModeExitHost.shadowRoot.querySelector(".zen-exit-btn");t&&(t.textContent=e),n&&n.setAttribute("aria-label",e);}refreshShadowInjection(){if(!(this.pageWidthConfig?.enabled||this.userQueryWidthConfig?.enabled||this.zenModeEnabled||this.cleanModeEnabled))return this.stopShadowInjection(),void this.clearAllShadowStyles();this.startShadowInjection();}startShadowInjection(){this.injectToAllShadows(),this.shadowCheckInterval||(this.shadowCheckInterval=setInterval(()=>this.injectToAllShadows(),1e3));}stopShadowInjection(){this.shadowCheckInterval&&(clearInterval(this.shadowCheckInterval),this.shadowCheckInterval=null);}injectToAllShadows(){if(!document.body)return;this.zenModeEnabled&&this.syncZenModeRootClass();const e=this.siteAdapter;os.walkShadowRoots((t,n)=>{if(!n||e.shouldInjectIntoShadow(n)){if(this.pageWidthConfig?.enabled){const n=`${this.pageWidthConfig.value}${this.pageWidthConfig.unit}`,r=e.getWidthSelectors();let o=this.buildCSSFromSelectors(r,n,false);if("%"===this.pageWidthConfig.unit){o=`${o}\n@media (max-width: 480px) {\n${this.buildCSSFromSelectors(r,"95%",false)}\n}`;}os.cssToShadow(t,o,WC);}else this.removeStyleFromShadow(t,WC);if(this.userQueryWidthConfig?.enabled){const n=this.userQueryWidthConfig.value||"81",r=this.userQueryWidthConfig.unit||"%",o=this.buildCSSFromSelectors(e.getUserQueryWidthSelectors(),`${n}${r}`,false);os.cssToShadow(t,o,QC);}else this.removeStyleFromShadow(t,QC);if(this.zenModeEnabled){const e=this.generateZenModeCSS();e?os.cssToShadow(t,e,KC):this.removeStyleFromShadow(t,KC);}else this.removeStyleFromShadow(t,KC);if(this.cleanModeEnabled){const e=this.generateCleanModeCSS();e?os.cssToShadow(t,e,YC):this.removeStyleFromShadow(t,YC);}else this.removeStyleFromShadow(t,YC);this.processedShadowRoots.add(t);}});}removeStyleFromShadow(e,t){const n=e.getElementById(t);n&&n.remove();}clearAllShadowStyles(){document.body&&os.walkShadowRoots(e=>{this.removeStyleFromShadow(e,WC),this.removeStyleFromShadow(e,QC),this.removeStyleFromShadow(e,KC),this.removeStyleFromShadow(e,YC),this.processedShadowRoots.delete(e);});}}const eA=/]*>[\s\S]*?<\/code>/gi,tA=/]*>([\s\S]*?)<\/b>/gi,nA=/]*>([\s\S]*?)<\/strong>/gi,rA=/\*\*([^*]+(?:\*(?!\*)[^*]*)*)\*\*/g,oA=/###OPHEL_CODE_(\d+)###/g;class iA{stopObserver=null;enabled=false;config;constructor(e){this.config=e;}start(){this.enabled||(this.enabled=true,this.fixAllParagraphs(),this.stopObserver=os.each(this.config.selector,(e,t)=>{t&&setTimeout(()=>this.fixParagraph(e),100);}));}stop(){this.enabled&&(this.enabled=false,this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}fixAllParagraphs(){os.query(this.config.selector,{all:true}).forEach(e=>this.fixParagraph(e));}fixParagraph(e){if(!e.isConnected)return;if(this.config.shouldIgnore?.(e))return void delete e.dataset.mdFixerHash;if(this.config.shouldSkip?.(e))return void setTimeout(()=>this.fixParagraph(e),500);const t=e.innerHTML;if(e.dataset.mdFixerHash===String(t.length))return;if(!t.includes("(n.push(e),`###OPHEL_CODE_${n.length-1}###`)).replace(nA,"**$1**");r=r.replace(tA,"**$1**");let o=false;if(r=r.replace(rA,(e,t)=>(o=true,`${t}`)),o){const o=r.replace(oA,(e,t)=>n[parseInt(t,10)]);t!==o&&Rp(e,o);}e.dataset.mdFixerHash=String(e.innerHTML.length);}}class aA{adapter;config;isLocked=false;verifyTimer=null;configDebounceTimer=null;constructor(e,t){this.adapter=e,this.config=t;}updateConfig(e){const t=this.config.enabled,n=this.config.keyword;this.config=e;(!t&&e.enabled||e.enabled&&e.keyword!==n)&&(this.configDebounceTimer&&clearTimeout(this.configDebounceTimer),this.configDebounceTimer=setTimeout(()=>{this.configDebounceTimer=null,this.isLocked=false,this.start(50);},500));}start(e=1500){this.config.enabled&&this.config.keyword&&(this.isLocked||setTimeout(()=>{this.isLocked||this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();});},e));}relock(e=300){this.config.enabled&&this.config.keyword&&(this.stop(),this.isLocked=false,this.start(e));}startVerification(){this.verifyTimer&&clearInterval(this.verifyTimer);let e=0,t=0;this.verifyTimer=setInterval(()=>{e++;const n=this.adapter.getModelSwitcherConfig(this.config.keyword);if(!n)return void this.finishVerification();const r=this.adapter.findElementBySelectors(n.selectorButtonSelectors);if(!r)return void this.finishVerification();const o=this.adapter.getModelLockCheckText(r).toLowerCase().trim(),i=n.targetModelKeyword.toLowerCase().trim();o?o.includes(i)?(t++,(t>=2||e>=3)&&this.finishVerification()):(t=0,e<=2?(this.finishVerification(),this.adapter.lockModel(this.config.keyword,()=>{this.startVerification();})):this.finishVerification()):e>=3&&this.finishVerification();},1500);}finishVerification(){this.isLocked=true,this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null);}stop(){this.configDebounceTimer&&(clearTimeout(this.configDebounceTimer),this.configDebounceTimer=null),this.verifyTimer&&(clearInterval(this.verifyTimer),this.verifyTimer=null),this.isLocked=true;}}class sA{adapter;settings;retryCounts=new Map;lastPromptValues=new WeakMap;monitorInitialized=false;constructor(e,t){this.adapter=e,this.settings=t,window.addEventListener("message",this.handleMessage.bind(this)),this.settings.enabled&&this.initNetworkMonitor();}updateSettings(e){const t=this.settings.enabled;this.settings=e,!t&&e.enabled&&this.initNetworkMonitor();}initNetworkMonitor(){if(this.monitorInitialized)return;const e=this.adapter.getNetworkMonitorConfig?.();e&&(window.postMessage({type:Sp,payload:{urlPatterns:e.urlPatterns,urlPathEndsWith:e.urlPathEndsWith,silenceThreshold:e.silenceThreshold}},"*"),this.monitorInitialized=true);}handleMessage(e){if(this.adapter.getSiteId()!==ho)return;const t=e.data;if(t&&t.type===Ap){if(!this.settings.enabled)return;this.checkAndRetry();}}async checkAndRetry(){await new Promise(e=>setTimeout(e,500));const e=os.query("ucs-conversation",{shadow:true});if(!e||!e.shadowRoot)return;const t=e.shadowRoot,n=t.querySelector(".turn.last")||t.querySelector(".turn:last-child");if(!n)return;const r=n.querySelector("ucs-summary");if(!r)return;if(!this.findBannedAnswer(r))return;const o=n.querySelector(".question-block");if(!o)return void console.warn("[PolicyRetry] User question block not found");const i=this.adapter.extractUserQueryText(o);if(!i)return void console.warn("[PolicyRetry] Empty user question");const a=await this.sha256(i),s=this.retryCounts.get(a)||0;if(ssetTimeout(e,100));if(!this.adapter.insertPrompt(e))return void console.error("[PolicyRetry] Failed to insert prompt");await new Promise(e=>setTimeout(e,300));const t=this.adapter.getSubmitButtonSelectors(),n=os.query(t,{shadow:true});if(n)n.click();else {const e=this.adapter.findTextarea();e?(e.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keypress",{key:"Enter",code:"Enter",keyCode:13,bubbles:true})),e.dispatchEvent(new KeyboardEvent("keyup",{key:"Enter",code:"Enter",keyCode:13,bubbles:true}))):console.error("[PolicyRetry] Submit button and editor not found");}}async sha256(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}}class lA{static HYDRATION_TIMEOUT_MS=5e3;static SESSION_READY_TIMEOUT_MS=3e3;static SESSION_READY_POLL_MS=100;adapter;settings;isRecording=false;isRestoring=false;currentSessionId=null;listeningContainer=null;scrollHandler=null;userInteractionHandler=null;lastSaveTime=0;ignoreScrollUntil=0;positionKeeperRaF=0;restoredTop;constructor(e,t){this.adapter=e,this.settings=t;}async waitForHydration(e=lA.HYDRATION_TIMEOUT_MS){return !!gk.getState()._hasHydrated||new Promise(t=>{let n=false,r=0;const o=e=>{n||(n=true,window.clearTimeout(r),i(),t(e));},i=gk.subscribe(e=>{e._hasHydrated&&o(true);});r=window.setTimeout(()=>{gk.setState({_hasHydrated:true}),o(false);},e);})}updateSettings(e){this.settings=e,!this.settings.persistence&&this.isRecording?this.stopRecording():this.settings.persistence&&!this.isRecording&&this.startRecording();}startRecording(){if(this.isRecording)return;this.isRecording=true,this.currentSessionId=null,this.scrollHandler=e=>this.handleScroll(e);const e=this.adapter.getScrollContainer();e&&(e.addEventListener("scroll",this.scrollHandler,{passive:true}),this.listeningContainer=e),this.ignoreScrollUntil=Date.now()+2e3,this.userInteractionHandler=e=>{if("keydown"===e.type){const t=e.key;if(!["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(t))return}if("wheel"===e.type||"touchmove"===e.type){const t=e.composedPath?.()?.[0];if(t){const e=t.getRootNode?.();if(e&&e!==document)return}}this.ignoreScrollUntil>0&&(this.ignoreScrollUntil=0),this.positionKeeperRaF&&this.stopPositionKeeper();},window.addEventListener("wheel",this.userInteractionHandler,{passive:true}),window.addEventListener("touchmove",this.userInteractionHandler,{passive:true}),window.addEventListener("keydown",this.userInteractionHandler,{passive:true}),window.addEventListener("scroll",this.scrollHandler,{capture:true,passive:true}),window.addEventListener("visibilitychange",this.scrollHandler),window.addEventListener("beforeunload",this.scrollHandler);}stopRecording(){this.isRecording&&(this.isRecording=false,this.currentSessionId=null,this.scrollHandler&&(this.listeningContainer&&(this.listeningContainer.removeEventListener("scroll",this.scrollHandler),this.listeningContainer=null),window.removeEventListener("scroll",this.scrollHandler,{capture:true}),window.removeEventListener("visibilitychange",this.scrollHandler),window.removeEventListener("beforeunload",this.scrollHandler),this.scrollHandler=null),this.userInteractionHandler&&(window.removeEventListener("wheel",this.userInteractionHandler),window.removeEventListener("touchmove",this.userInteractionHandler),window.removeEventListener("keydown",this.userInteractionHandler),this.userInteractionHandler=null),this.stopPositionKeeper());}restartRecording(){this.stopRecording(),this.startRecording();}handleScroll(e){if(!this.settings.persistence)return;if("scroll"===e.type){const t=this.adapter.getScrollContainer(),n=e.target;if(t&&n&&n!==document&&n!==window&&n!==t)return}const t=Date.now();("beforeunload"===e.type||"visibilitychange"===e.type||t-this.lastSaveTime>1e3)&&(this.saveProgress(),this.lastSaveTime=t);}getKey(e=this.getSessionId()){const t=e||"unknown";return `${this.adapter.getSiteId()}:${t}`}getSessionId(){return this.adapter.getSessionId()?.trim()||""}canUseCurrentSession(e=this.getSessionId()){return !!e&&this.adapter.isUserConversationPage()}lockCurrentSessionId(e){e&&(this.currentSessionId||(this.currentSessionId=e));}async waitForReadySessionId(e=lA.SESSION_READY_TIMEOUT_MS){const t=Date.now()+e;for(;Date.now()<=t;){const e=this.getSessionId();if(this.canUseCurrentSession(e))return e;await new Promise(e=>window.setTimeout(e,lA.SESSION_READY_POLL_MS));}const n=this.getSessionId();return this.canUseCurrentSession(n)?n:""}saveProgress(){if(!this.isRecording)return;if(this.isRestoring)return;const e=this.getSessionId();if(this.currentSessionId&&e&&e!==this.currentSessionId)return;if(Date.now(){e?.(`${se("exportLoading")} ${t}`);}})).success)return !1;const t=r.top;document.documentElement.dataset.ophelPositionLock=String(t),await dw(this.adapter,t),this.restoredTop=t,o=!0;}catch{return delete document.documentElement.dataset.ophelPositionLock,!1}}return o}finally{o&&void 0!==this.restoredTop&&this.startPositionKeeper(this.restoredTop),setTimeout(()=>{this.isRestoring=false;},1e3);}}cleanup(){const e=this.settings.cleanupDays||7;pk().cleanup(e);}startPositionKeeper(e){this.stopPositionKeeper();const t=Date.now();document.documentElement.dataset.ophelPositionLock=String(e),document.documentElement.dataset.ophelPositionLockLastBlock=String(t);const n=()=>{const r=Date.now(),o=r-t;if(o>15e3)return void this.stopPositionKeeper();if(o>2e3){const e=Number(document.documentElement.dataset.ophelPositionLockLastBlock||"0");if(e>0&&r-e>2e3)return void this.stopPositionKeeper()}const i=this.adapter.getScrollContainer();if(i){const t=document.documentElement.dataset.ophelPositionLock;if(void 0!==t){const n=Number(t);!isNaN(n)&&Math.abs(n-e)>5&&(e=n);}Math.abs(i.scrollTop-e)>5&&(i.scrollTop=e);}this.positionKeeperRaF=requestAnimationFrame(n);};this.positionKeeperRaF=requestAnimationFrame(n);}stopPositionKeeper(){this.positionKeeperRaF&&(cancelAnimationFrame(this.positionKeeperRaF),this.positionKeeperRaF=0,delete document.documentElement.dataset.ophelPositionLock,delete document.documentElement.dataset.ophelPositionLockLastBlock);}}class cA{adapter;settings;enabled=false;constructor(e,t){this.adapter=e,this.settings=t,this.init();}updateSettings(e){const t=this.settings.panel?.preventAutoScroll;this.settings=e,!t&&e.panel?.preventAutoScroll?this.enable():t&&!e.panel?.preventAutoScroll&&this.disable();}init(){this.settings.panel?.preventAutoScroll&&this.enable();}enable(){this.enabled||(this.enabled=true,this.toggleMainWorldHijack(true));}disable(){this.enabled&&(this.enabled=false,this.toggleMainWorldHijack(false));}stop(){this.disable();}toggleMainWorldHijack(e){window.postMessage({type:"OPHEL_SCROLL_LOCK_TOGGLE",enabled:e},"*");}}class dA{adapter;settings;isRunning=false;intervalId=null;titleObserver=null;expectedTitle=null;isApplyingManagedTitle=false;titleSyncTimer=null;aiState="idle";lastAiState="idle";currentNetworkGenerationPending=false;currentNetworkGenerationConfirmed=false;generationConfirmationIntervalId=null;currentGenerationUsesDomCompletion=false;currentDomCompletionObservedStart=false;domCompletionIntervalId=null;domCompletionTrackingStartedAt=0;userSawCompletion=false;completionViewed=false;lastConversationTitle=null;staleManagedTitleAfterRouteChange=null;staleConversationTitleAfterRouteChange=null;notificationAudio=null;notificationRepeatTimer=null;notificationPlaybackId=0;boundHandleMessage;boundVisibilityHandler;boundFocusHandler;boundBlurHandler;constructor(e,t){this.adapter=e,this.settings=t,this.boundHandleMessage=this.handleMessage.bind(this),this.boundVisibilityHandler=this.onVisibilityChange.bind(this),this.boundFocusHandler=this.onWindowFocus.bind(this),this.boundBlurHandler=this.onWindowBlur.bind(this),window.addEventListener("message",this.boundHandleMessage),document.addEventListener("visibilitychange",this.boundVisibilityHandler),window.addEventListener("focus",this.boundFocusHandler),window.addEventListener("blur",this.boundBlurHandler);}updateSettings(e){const t=this.settings.renameInterval,n=this.settings.showNotification,r=this.settings.notificationSound,o=this.settings.notificationSoundPreset,i=this.settings.notificationVolume,a=this.settings.notificationRepeatCount,s=this.settings.notificationRepeatInterval;this.settings=e,n===this.settings.showNotification&&r===this.settings.notificationSound&&o===this.settings.notificationSoundPreset&&i===this.settings.notificationVolume&&a===this.settings.notificationRepeatCount&&s===this.settings.notificationRepeatInterval||this.stopNotificationPlayback(),this.settings.autoRename&&!this.isRunning?this.start():!this.settings.autoRename&&this.isRunning&&this.stop(),this.isRunning&&t!==this.settings.renameInterval&&this.setInterval(this.settings.renameInterval||5),this.isRunning&&this.updateTabName(true);}start(){if(!this.settings.autoRename)return;if(this.isRunning)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;this.isRunning=true,this.startTitleObserver(),this.updateTabName();const e=1e3*(this.settings.renameInterval||5);this.intervalId=setInterval(()=>this.updateTabName(),e);const t=this.adapter.getNetworkMonitorConfig?this.adapter.getNetworkMonitorConfig():null;t&&window.postMessage({type:Sp,payload:{urlPatterns:t.urlPatterns,urlPathEndsWith:t.urlPathEndsWith,silenceThreshold:t.silenceThreshold,requestBodyRules:t.requestBodyRules}},"*");}stop(){this.isRunning&&(this.isRunning=false,this.resetGenerationConfirmationState(),this.stopTitleObserver(),this.expectedTitle=null,this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null,za(),this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null));}destroy(){this.stop(),this.stopNotificationPlayback(),this.resetGenerationConfirmationState(),this.stopTitleObserver(),window.removeEventListener("message",this.boundHandleMessage),document.removeEventListener("visibilitychange",this.boundVisibilityHandler),window.removeEventListener("focus",this.boundFocusHandler),window.removeEventListener("blur",this.boundBlurHandler);}setInterval(e){if(!this.isRunning)return;const t=1e3*e;this.intervalId&&clearInterval(this.intervalId),this.intervalId=setInterval(()=>this.updateTabName(),t);}togglePrivacyMode(){return this.settings.privacyMode=!this.settings.privacyMode,this.updateTabName(true),this.settings.privacyMode}resetConversationTitleCache(){const e=Pa(document.title),t=Pa(this.expectedTitle)||Pa(Ba()),n=Pa(this.lastConversationTitle),r=e&&e===t?Oa(e,{expectedManagedTitle:t,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat}):null;this.lastConversationTitle=null,this.expectedTitle=null,za(),e&&e===t?(this.staleManagedTitleAfterRouteChange=e,this.staleConversationTitleAfterRouteChange=n||r):(this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null);}updateTabName(e=false){if(!this.isRunning&&!e)return;if(this.adapter.supportsTabRename&&!this.adapter.supportsTabRename())return;if(this.settings.privacyMode){const t=this.settings.privacyTitle||"Google";return void this.applyManagedTitle(t,e)}const t=this.getCleanConversationTitle(),n=this.isCurrentlyGenerating();"generating"===this.lastAiState&&!n&&this.isUserAway()&&"completed"!==this.aiState&&this.sendCompletionNotification(),this.lastAiState=n?"generating":"idle";const r=this.computeStatusPrefix(n),o=this.adapter.getName(),i=this.settings.titleFormat??"{status}{title}",a=i.includes("{model}")&&this.adapter.getModelName?.()||"",s=function(e,t){const n=Pa(t.modelName)?`[${Pa(t.modelName)}]`:"";return (n?e:Fa(e)).replace(/\{status\}/g,t.statusPrefix).replace(/\{title\}/g,t.conversationTitle).replace(/\{model\}/g,n).replace(/\{site\}/g,t.siteName).replace(/\s+/g," ").trim()}(i,{statusPrefix:r,conversationTitle:t||o,modelName:a,siteName:o});s&&this.applyManagedTitle(s,e);}computeStatusPrefix(e){return false===this.settings.showStatus?"":e?"⏳ ":this.settings.hideStatusWhenRead&&("completed"!==this.aiState||this.completionViewed)?"":"✅ "}applyManagedTitle(e,t=false){this.expectedTitle=e,function(e){"undefined"!=typeof document&&document.documentElement?.setAttribute(Na,e);}(e),(t||document.title!==e)&&(this.isApplyingManagedTitle=true,document.title=e,queueMicrotask(()=>{this.isApplyingManagedTitle=false;}));}startTitleObserver(){if(this.titleObserver||"undefined"==typeof MutationObserver)return;this.titleObserver=new MutationObserver(()=>{this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&(null!==this.titleSyncTimer&&window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=window.setTimeout(()=>{this.titleSyncTimer=null,this.isRunning&&this.settings.autoRename&&(this.isApplyingManagedTitle||this.expectedTitle&&document.title!==this.expectedTitle&&this.updateTabName(true));},0)));}),(()=>{document.head&&(this.titleObserver?.disconnect(),this.titleObserver?.observe(document.head,{childList:true,subtree:true,characterData:true}));})();}stopTitleObserver(){null!==this.titleSyncTimer&&(window.clearTimeout(this.titleSyncTimer),this.titleSyncTimer=null),this.titleObserver?.disconnect(),this.titleObserver=null,this.isApplyingManagedTitle=false;}getCleanConversationTitle(){if(this.adapter.isNewConversation?.())return this.lastConversationTitle=null,null;const e=this.sanitizeAdapterTitleCandidate(this.adapter.getConversationTitle?.());if(e)return this.clearStaleManagedTitleAfterRouteChange(),this.lastConversationTitle=e,e;if(this.expectedTitle&&document.title===this.expectedTitle&&this.lastConversationTitle)return this.lastConversationTitle;const t=this.sanitizeAdapterTitleCandidate(this.adapter.getSessionName?.());return t?(this.clearStaleManagedTitleAfterRouteChange(),this.lastConversationTitle=t,t):this.lastConversationTitle}sanitizeAdapterTitleCandidate(e){return this.shouldIgnoreStaleManagedTitle(e)||this.shouldIgnoreCurrentManagedDocumentTitle(e)?null:Oa(e,{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})}shouldIgnoreStaleManagedTitle(e){return !!this.staleManagedTitleAfterRouteChange&&(Pa(document.title)!==this.staleManagedTitleAfterRouteChange?(this.clearStaleManagedTitleAfterRouteChange(),false):this.isManagedDocumentTitleFallback(e,this.staleManagedTitleAfterRouteChange,this.staleConversationTitleAfterRouteChange))}shouldIgnoreCurrentManagedDocumentTitle(e){return !!this.expectedTitle&&(Pa(document.title)===Pa(this.expectedTitle)&&this.isManagedDocumentTitleFallback(e,this.expectedTitle,this.lastConversationTitle))}isManagedDocumentTitleFallback(e,t,n){const r=Pa(e),o=Pa(t);if(!r||!o)return false;if(r===o)return true;const i=Pa(o.replace(/^(?:[⏳✅]\s*)+/u,""));if(i&&r===i)return true;const a=Oa(o,{expectedManagedTitle:o,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat});return !(!a||r!==a)||Boolean(n&&r===Pa(n))}clearStaleManagedTitleAfterRouteChange(){this.staleManagedTitleAfterRouteChange=null,this.staleConversationTitleAfterRouteChange=null;}isCurrentlyGenerating(){return "completed"!==this.aiState&&("generating"===this.aiState||(this.adapter.isGenerating?.()??false))}requiresDomConfirmationForNetworkGeneration(){return this.adapter.requiresDomConfirmationForNetworkGeneration?.()??false}beginNetworkGeneration(e){this.stopNotificationPlayback(),e?.domCompletionRequired?this.beginDomCompletionDrivenGeneration():(this.resetDomCompletionState(),this.requiresDomConfirmationForNetworkGeneration()?(this.currentNetworkGenerationPending=true,this.currentNetworkGenerationConfirmed=false,this.startGenerationConfirmationPolling()):this.confirmCurrentNetworkGeneration());}confirmCurrentNetworkGeneration(){this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=true,this.clearGenerationConfirmationPolling(),"generating"!==this.aiState&&(this.lastAiState=this.aiState,this.aiState="generating",this.settings.hideStatusWhenRead&&(this.completionViewed=false)),this.updateTabName();}startGenerationConfirmationPolling(){this.clearGenerationConfirmationPolling();const e=()=>{this.currentNetworkGenerationPending&&this.adapter.isGenerating?.()&&this.confirmCurrentNetworkGeneration();};e(),this.currentNetworkGenerationConfirmed||(this.generationConfirmationIntervalId=window.setInterval(e,200));}beginDomCompletionDrivenGeneration(){this.resetGenerationConfirmationState(),this.currentGenerationUsesDomCompletion=true,this.currentDomCompletionObservedStart=false,this.domCompletionTrackingStartedAt=Date.now(),this.completionViewed=false,this.startDomCompletionPolling(),this.updateTabName();}startDomCompletionPolling(){this.clearDomCompletionPolling();const e=()=>{if(!this.currentGenerationUsesDomCompletion)return;const e=this.adapter.isGenerating?.()??false;if(!this.currentDomCompletionObservedStart)return e?(this.currentDomCompletionObservedStart=true,"generating"!==this.aiState&&(this.lastAiState=this.aiState,this.aiState="generating",this.completionViewed=false),void this.updateTabName()):void(Date.now()-this.domCompletionTrackingStartedAt>3e4&&(this.lastAiState=this.aiState,this.aiState="idle",this.userSawCompletion=false,this.completionViewed=false,this.resetDomCompletionState(),this.updateTabName(true)));e||this.finalizeAiCompletion();};e(),this.currentGenerationUsesDomCompletion&&(this.domCompletionIntervalId=window.setInterval(e,150));}clearGenerationConfirmationPolling(){null!==this.generationConfirmationIntervalId&&(window.clearInterval(this.generationConfirmationIntervalId),this.generationConfirmationIntervalId=null);}clearDomCompletionPolling(){null!==this.domCompletionIntervalId&&(window.clearInterval(this.domCompletionIntervalId),this.domCompletionIntervalId=null);}resetDomCompletionState(){this.clearDomCompletionPolling(),this.currentGenerationUsesDomCompletion=false,this.currentDomCompletionObservedStart=false,this.domCompletionTrackingStartedAt=0;}resetGenerationConfirmationState(){this.clearGenerationConfirmationPolling(),this.resetDomCompletionState(),this.currentNetworkGenerationPending=false,this.currentNetworkGenerationConfirmed=false;}handleMessage(e){if(e.origin!==window.location.origin)return;const{type:t,payload:n}=e.data||{};t===Cp?this.beginNetworkGeneration(n):t===Ap&&this.onAiComplete();}isUserAway(){const e=document.hidden,t=document.hasFocus(),n="visible"!==document.visibilityState;return e||!t||n}onVisibilityChange(){const e=this.isUserAway();if(e||this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"!==this.aiState||e||this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true),"completed"===this.aiState&&!e){if(this.completionViewed)return;this.completionViewed=true,this.updateTabName(true);}}onWindowFocus(){this.stopNotificationPlayback({stopCurrentAudio:false}),"generating"===this.aiState&&this.adapter.isGenerating&&!this.adapter.isGenerating()&&(this.userSawCompletion=true),"completed"===this.aiState&&(this.completionViewed||(this.completionViewed=true,this.updateTabName(true)));}onWindowBlur(){}onAiComplete(){if(this.currentGenerationUsesDomCompletion)return;const e=this.requiresDomConfirmationForNetworkGeneration(),t=this.currentNetworkGenerationConfirmed;if(e&&!t)return this.resetGenerationConfirmationState(),this.lastAiState=this.aiState,this.aiState="idle",this.userSawCompletion=false,this.completionViewed=false,void this.updateTabName(true);this.finalizeAiCompletion();}finalizeAiCompletion(){const e="generating"===this.aiState;this.lastAiState=this.aiState,this.aiState="completed";const t=this.settings.notifyWhenFocused,n=this.isUserAway();e&&!this.userSawCompletion&&(n||t)&&this.sendCompletionNotification(),n||(this.completionViewed=true),this.userSawCompletion=false,this.resetGenerationConfirmationState(),this.updateTabName(true);}sendCompletionNotification(){if(this.stopNotificationPlayback(),this.settings.showNotification)try{const e=this.adapter.getName(),t=se("notificationTitle").replace("{site}",e),n=this.lastConversationTitle||Oa(this.adapter.getConversationTitle?.(),{expectedManagedTitle:this.expectedTitle,privacyTitle:this.settings.privacyTitle||"Google",siteName:this.adapter.getName(),titleFormat:this.settings.titleFormat})||se("notificationBody");qi.notify({title:t,message:n});}catch(e){console.error("[TabManager] 通知发送失败:",e);}this.settings.showNotification&&this.settings.notificationSound&&this.playNotificationSound(),this.settings.autoFocus&&qi.focusWindow();}playNotificationSound(){const e=this.settings.notificationSoundPreset||Xr[0].id,t=Xr.find(t=>t.id===e)||Xr[0],n=qi.getNotificationSoundUrl(t.id);if(!n)return void console.warn("[TabManager] Notification sound URL not found for preset:",t.id);const r=this.normalizeNotificationRepeatCount(this.settings.notificationRepeatCount),o=1e3*this.normalizeNotificationRepeatInterval(this.settings.notificationRepeatInterval);this.startNotificationPlayback(n,r,o);}startNotificationPlayback(e,t,n){this.stopNotificationPlayback();const r=++this.notificationPlaybackId,o=t=>{if(r===this.notificationPlaybackId)try{this.notificationAudio||(this.notificationAudio=new Audio);const i=this.settings.notificationVolume??.5;this.notificationAudio.volume=Math.max(.1,Math.min(1,i)),this.notificationAudio.src=e,this.notificationAudio.currentTime=0,this.notificationAudio.onended=()=>{if(r===this.notificationPlaybackId)return t<=1?(this.clearNotificationPlaybackHandlers(),void(this.notificationRepeatTimer=null)):void(this.isUserAway()?this.notificationRepeatTimer=window.setTimeout(()=>{this.notificationRepeatTimer=null,o(t-1);},n):this.stopNotificationPlayback())},this.notificationAudio.onerror=()=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio element error:",{url:e,mediaError:this.notificationAudio?.error}),this.stopNotificationPlayback());},this.notificationAudio.play().catch(t=>{r===this.notificationPlaybackId&&(console.error("[TabManager] Notification audio play rejected:",{url:e,error:t}),this.stopNotificationPlayback());});}catch(i){console.error("[TabManager] 音频初始化失败:",i);}};o(t);}stopNotificationPlayback(e){const t=e?.stopCurrentAudio??true;this.notificationPlaybackId+=1,null!==this.notificationRepeatTimer&&(window.clearTimeout(this.notificationRepeatTimer),this.notificationRepeatTimer=null);try{t&&this.notificationAudio&&(this.clearNotificationPlaybackHandlers(),this.notificationAudio.pause(),this.notificationAudio.currentTime=0);}catch(n){console.error("[TabManager] 音频停止失败:",n);}}clearNotificationPlaybackHandlers(){this.notificationAudio&&(this.notificationAudio.onended=null,this.notificationAudio.onerror=null);}normalizeNotificationRepeatCount(e){return Number.isFinite(e)?Math.max(1,Math.min(10,Math.round(e))):1}normalizeNotificationRepeatInterval(e){return Number.isFinite(e)?Math.max(1,Math.min(60,e)):3}isActive(){return this.isRunning}}const uA="gh-usage-monitor-style",hA="gh-usage-monitor-host",gA={count:0,updatedAt:Date.now(),resetAt:Date.now()},pA=e=>e.replace(/[\u200B\u200C\u200D\uFEFF\u00A0]/g,"").replace(/\s+/g," ").trim(),mA=/[\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g,fA=/[A-Za-z0-9]/g,bA=/[^\sA-Za-z0-9\u3400-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/g;class yA{adapter;siteId;settings;root=null;slot=null;activeAnchor=null;mounted=false;mountTimer=null;renderTimer=null;renderInFlight=false;rerenderRequested=false;midnightTimer=null;pendingTimer=null;pendingSend=null;unwatchStorage=null;activeRecordKey="";currentRecord={...gA};injectedStyleRoots=new Set;handleViewportChange=()=>{this.settings.enabled&&this.scheduleRender(0);};handleDocumentClick=e=>{if(!this.settings.enabled)return;const t=this.resolveEditor();t&&this.isSubmitButtonClick(e,t)&&this.schedulePendingSend(t);};handleDocumentKeydown=e=>{if(!this.settings.enabled)return;if(!this.isSubmitShortcut(e))return;const t=this.resolveEditorFromTarget(e.target);t&&this.schedulePendingSend(t);};handleDocumentInput=e=>{if(!this.settings.enabled)return;this.resolveEditorFromTarget(e.target)&&(this.ensureMounted(),this.scheduleRender(60));};handleDocumentFocus=()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));};constructor(e,t,n){this.adapter=e,this.settings=this.normalizeSettings(t),this.siteId=n;}start(){if(this.settings.enabled){if(this.mounted)return this.ensureMounted(),void this.scheduleRender(0);this.mounted=true,this.ensureStyles(),document.addEventListener("click",this.handleDocumentClick,true),document.addEventListener("keydown",this.handleDocumentKeydown,true),document.addEventListener("input",this.handleDocumentInput,true),document.addEventListener("focusin",this.handleDocumentFocus,true),window.addEventListener("resize",this.handleViewportChange,true),window.addEventListener("scroll",this.handleViewportChange,true),this.unwatchStorage=Pk(e=>{const t=e.records[this.getRecordKey()];this.currentRecord=t?{count:Math.max(0,Math.floor(t.count||0)),updatedAt:t.updatedAt||Date.now(),resetAt:t.resetAt||Date.now()}:{count:0,updatedAt:Date.now(),resetAt:Date.now()},this.scheduleRender(0);}),this.startMountLoop(),this.scheduleMidnightReset(),this.syncCounterRecord(true),this.ensureMounted(),this.scheduleRender(0);}}stop(){if(!this.mounted)return this.removeRoot(),void this.removeStyles();this.mounted=false,document.removeEventListener("click",this.handleDocumentClick,true),document.removeEventListener("keydown",this.handleDocumentKeydown,true),document.removeEventListener("input",this.handleDocumentInput,true),document.removeEventListener("focusin",this.handleDocumentFocus,true),window.removeEventListener("resize",this.handleViewportChange,true),window.removeEventListener("scroll",this.handleViewportChange,true),null!==this.mountTimer&&(window.clearInterval(this.mountTimer),this.mountTimer=null),null!==this.renderTimer&&(window.clearTimeout(this.renderTimer),this.renderTimer=null),null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.pendingSend=null,this.unwatchStorage?.(),this.unwatchStorage=null,this.removeRoot(),this.removeStyles();}destroy(){this.stop();}updateSettings(e){this.settings=this.normalizeSettings(e),this.settings.enabled?this.mounted?(this.activeRecordKey="",this.scheduleMidnightReset(),this.ensureMounted(),this.syncCounterRecord(true),this.scheduleRender(0)):this.start():this.stop();}handleUrlChange(){this.settings.enabled&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null),this.activeRecordKey="",this.adapter.findTextarea(),this.ensureMounted(true),this.syncCounterRecord(true),[80,220,500,1e3].forEach(e=>window.setTimeout(()=>{this.settings.enabled&&(this.ensureMounted(),this.scheduleRender(0));},e)));}normalizeSettings(e){return {enabled:e?.enabled??false,dailyLimit:Math.max(1,Math.floor(e?.dailyLimit??100)),autoResetEnabled:e?.autoResetEnabled??false}}startMountLoop(){null===this.mountTimer&&(this.mountTimer=window.setInterval(()=>{(this.ensureMounted()||this.root)&&this.scheduleRender(0);},1e3));}ensureMounted(e=false){if(!this.settings.enabled)return false;const t=this.resolveEditor();if(!t)return (e||this.activeAnchor&&!this.activeAnchor.isConnected)&&this.removeRoot(),false;const n=this.resolveMountAnchor(t);if(!n?.parentElement)return false;this.ensureStylesForTarget(n),this.root||(this.root=document.createElement("div"),this.root.className=hA),this.slot||(this.slot=document.createElement("div"),this.slot.className=`${hA}-slot`);const r=e||this.activeAnchor!==n||!this.root.isConnected||!this.slot.isConnected||this.slot.parentElement!==n.parentElement||this.slot.nextSibling!==n;return r&&((n.parentElement&&this.slot.parentElement!==n.parentElement||n.parentElement&&this.slot.nextSibling!==n)&&n.parentElement.insertBefore(this.slot,n),this.root.parentElement!==this.slot&&this.slot.appendChild(this.root),this.activeAnchor=n),this.root.dataset.theme=this.detectThemeMode(),this.applySlotLayout(n),r}removeRoot(){this.activeAnchor=null,this.root?.remove(),this.root=null,this.slot?.remove(),this.slot=null;}bindPanelControls(){if(!this.root)return;const e=this.root.querySelector('[data-action="reset-counter"]');e&&(e.onclick=async e=>{e.preventDefault(),e.stopPropagation(),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t={count:0,updatedAt:Date.now(),resetAt:Date.now()},n=await Tk();return n.records[e]=t,await Mk(n),t}(this.getRecordKey()),this.scheduleRender(0);});}ensureStyles(){if(document.getElementById(uA))return;const e=document.createElement("style");e.id=uA,e.textContent=this.getUsageMonitorStyles(),document.head.appendChild(e);}ensureStylesForTarget(e){const t=e.getRootNode();t instanceof ShadowRoot&&(os.cssToShadow(t,this.getUsageMonitorStyles(),uA),this.injectedStyleRoots.add(t));}getUsageMonitorStyles(){return `\n .${hA} {\n box-sizing: border-box;\n width: 100%;\n max-width: 100%;\n margin: 0;\n pointer-events: auto;\n }\n\n .${hA}-slot {\n width: 100%;\n display: flex;\n align-items: flex-start;\n overflow: visible;\n pointer-events: none;\n margin: 0 0 8px 0;\n }\n\n .${hA} * {\n box-sizing: border-box;\n }\n\n .${hA} .gh-usage-monitor-panel {\n pointer-events: auto;\n border: 1px solid var(--gh-card-border, var(--gh-border, #e5e7eb));\n border-radius: 14px;\n padding: 10px 12px;\n background: var(--gh-card-bg, var(--gh-bg, #ffffff));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.1));\n color: var(--gh-text, #1f2937);\n font-size: 12px;\n line-height: 1.45;\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-panel {\n border-color: var(--gh-card-border, var(--gh-border, #333333));\n background: var(--gh-card-bg, var(--gh-bg, #1e1e1e));\n box-shadow: var(--gh-shadow-sm, 0 1px 3px rgba(0, 0, 0, 0.3));\n color: var(--gh-text, #e3e3e3);\n }\n\n .${hA} .gh-usage-monitor-top {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n margin-bottom: 8px;\n }\n\n .${hA} .gh-usage-monitor-title {\n font-weight: 600;\n letter-spacing: 0.01em;\n }\n\n .${hA} .gh-usage-monitor-meta {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .${hA} .gh-usage-monitor-count {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${hA} .gh-usage-monitor-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 2px 8px;\n border-radius: 999px;\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #f9fafb));\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.2;\n white-space: nowrap;\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-badge {\n background: var(--gh-user-query-bg, var(--gh-bg-secondary, #0b0b0b));\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${hA} .gh-usage-monitor-reset {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease, opacity 160ms ease;\n }\n\n .${hA} .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${hA} .gh-usage-monitor-control {\n appearance: none;\n border: 1px solid var(--gh-input-border, var(--gh-border, #e5e7eb));\n border-radius: 999px;\n background: transparent;\n color: inherit;\n font-size: 11px;\n line-height: 1.2;\n padding: 4px 9px;\n cursor: pointer;\n transition: background-color 160ms ease, border-color 160ms ease;\n }\n\n .${hA} .gh-usage-monitor-control:hover {\n background: var(--gh-hover, #f3f4f6);\n border-color: var(--gh-border-active, #6366f1);\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-reset {\n border-color: var(--gh-input-border, var(--gh-border, #333333));\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-reset:hover {\n background: var(--gh-hover, #262626);\n }\n\n .${hA} .gh-usage-monitor-progress {\n position: relative;\n height: 6px;\n border-radius: 999px;\n overflow: hidden;\n background: var(--gh-border, #e5e7eb);\n margin-bottom: 8px;\n }\n\n .${hA} .gh-usage-monitor-progress-bar {\n height: 100%;\n width: 0;\n border-radius: inherit;\n background: var(--gh-primary, #4285f4);\n transition: width 160ms ease, background-color 160ms ease;\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-progress {\n background: var(--gh-border, #333333);\n }\n\n .${hA}[data-level="warning"] .gh-usage-monitor-progress-bar {\n background: var(--gh-secondary, #34a853);\n }\n\n .${hA}[data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${hA}[data-level="danger"] .gh-usage-monitor-progress-bar {\n background: var(--gh-danger, #ef4444);\n }\n\n .${hA}[data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${hA}[data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${hA}[data-theme="dark"][data-level="normal"] .gh-usage-monitor-count {\n color: var(--gh-primary, #4285f4);\n }\n\n .${hA}[data-theme="dark"][data-level="warning"] .gh-usage-monitor-count {\n color: var(--gh-secondary, #34a853);\n }\n\n .${hA}[data-theme="dark"][data-level="danger"] .gh-usage-monitor-count {\n color: var(--gh-danger, #ef4444);\n }\n\n .${hA} .gh-usage-monitor-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 6px 12px;\n }\n\n .${hA} .gh-usage-monitor-item {\n display: flex;\n align-items: baseline;\n justify-content: space-between;\n gap: 10px;\n }\n\n .${hA} .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #6b7280);\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-label {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n .${hA} .gh-usage-monitor-value {\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n white-space: nowrap;\n }\n\n .${hA} .gh-usage-monitor-footnote {\n margin-top: 8px;\n color: var(--gh-text-secondary, #6b7280);\n font-size: 11px;\n line-height: 1.45;\n }\n\n .${hA}[data-theme="dark"] .gh-usage-monitor-footnote {\n color: var(--gh-text-secondary, #a0a0a0);\n }\n\n @media (max-width: 640px) {\n .${hA} .gh-usage-monitor-grid {\n grid-template-columns: 1fr;\n }\n }\n `}removeStyles(){document.getElementById(uA)?.remove();for(const e of this.injectedStyleRoots)e.getElementById(uA)?.remove();this.injectedStyleRoots.clear();}applySlotLayout(e){if(!this.root||!this.slot||!e?.isConnected)return;const t=e.getBoundingClientRect(),n=this.slot.parentElement?.getBoundingClientRect(),r=Math.max(280,Math.min(t.width,window.innerWidth-16)),o=n?Math.max(0,t.left-n.left):0;this.slot.style.justifyContent="flex-start",this.slot.style.minHeight="0",this.slot.style.marginBottom="8px",this.root.style.width=`${r}px`,this.root.style.maxWidth="100%",this.root.style.marginLeft=`${o}px`,this.root.style.alignSelf="flex-start";const i=this.root.offsetHeight;this.slot.style.height=`${i+8}px`;}scheduleMidnightReset(){if(null!==this.midnightTimer&&(window.clearTimeout(this.midnightTimer),this.midnightTimer=null),!this.settings.autoResetEnabled)return;const e=new Date,t=new Date(e);t.setHours(24,0,0,50);const n=Math.max(1e3,t.getTime()-e.getTime());this.midnightTimer=window.setTimeout(()=>{this.syncCounterRecord(true),this.scheduleRender(0),this.scheduleMidnightReset();},n);}scheduleRender(e=0){this.settings.enabled&&(null!==this.renderTimer&&window.clearTimeout(this.renderTimer),this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.render();},e));}async render(){if(this.settings.enabled&&(this.root||(this.ensureMounted(),this.root)))if(this.renderInFlight)this.rerenderRequested=true;else {this.renderInFlight=true;try{await this.syncCounterRecord();const e=this.getEstimateSnapshot(),t=this.currentRecord.count,n=Math.max(1,this.settings.dailyLimit),r=t/n,o=Math.min(100,Math.max(0,100*r)),i=r>=1?"danger":r>=.8?"warning":"normal";this.root.dataset.level=i,this.root.dataset.theme=this.detectThemeMode();const a=se("usageMonitorSettingsTitle"),s=this.settings.autoResetEnabled?se("usageMonitorTodayUsed"):se("usageMonitorLocallyUsed"),l=se("usageMonitorInputChars"),c=se("usageMonitorLoadedConversationTokens"),d=se("usageMonitorLoadedOutputTokens"),u=se("usageMonitorRequestTokens"),h=se("usageMonitorRoundTripTokens"),g=se("usageMonitorRoundTripDesc"),p=se("usageMonitorResetButton"),m=this.settings.autoResetEnabled?null:se("usageMonitorManualMode"),f=se("usageMonitorContextChars");this.root.replaceChildren(this.buildUsageMonitorPanel({title:a,usageLabel:s,resetButtonLabel:p,roundTripDesc:g,inputCharsLabel:l,loadedConversationLabel:c,loadedOutputLabel:d,requestTokensLabel:u,roundTripLabel:h,contextCharsLabel:f,manualModeLabel:m,count:t,limit:n,percent:o,estimate:e})),this.bindPanelControls(),this.activeAnchor&&this.applySlotLayout(this.activeAnchor);}finally{this.renderInFlight=false,this.rerenderRequested&&(this.rerenderRequested=false,this.scheduleRender(0));}}}async syncCounterRecord(e=false){const t=this.getRecordKey();(e||this.activeRecordKey!==t)&&(this.activeRecordKey=t,this.currentRecord=await async function(e){const t=await Tk(),n=Sk(t.records[e]);return t.records[e]||(t.records[e]=n,await Mk(t)),n}(t));}getRecordKey(){const e=this.adapter.getCurrentCid?.()||"default";return this.settings.autoResetEnabled?`${this.siteId}::${e}::day::${((e=new Date)=>`${e.getFullYear()}-${`${e.getMonth()+1}`.padStart(2,"0")}-${`${e.getDate()}`.padStart(2,"0")}`)()}`:`${this.siteId}::${e}::manual`}resolveEditor(){const e=this.collectEditorCandidates();return e.length>0?e.sort((e,t)=>this.scoreEditorCandidate(t)-this.scoreEditorCandidate(e))[0]:this.adapter.findTextarea()||this.adapter.getTextareaElement()}collectEditorCandidates(){const e=new Set,t=[];for(const n of this.adapter.getTextareaSelectors()){let r=[];try{r=os.query(n,{all:!0,shadow:!0})||[];}catch{continue}for(const n of r)n instanceof HTMLElement&&(e.has(n)||(e.add(n),this.adapter.isValidTextarea(n)&&t.push(n)));}return t}scoreEditorCandidate(e){if(!e.isConnected)return Number.NEGATIVE_INFINITY;const t=e.getBoundingClientRect();if(t.width<=0||t.height<=0)return Number.NEGATIVE_INFINITY;let n=0;(e===document.activeElement||e.contains(document.activeElement))&&(n+=1e3);const r=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e);r&&r.isConnected&&(n+=400),n+=t.top/Math.max(window.innerHeight,1)*120;const o=(e.getAttribute("aria-label")||"").toLowerCase(),i=(e.getAttribute("placeholder")||e.placeholder||"").toLowerCase();return /prompt|message|chat|发送|输入|ask|query/.test(`${o} ${i}`)&&(n+=120),n}resolveEditorFromTarget(e){if(!(e instanceof Element))return this.resolveEditor();for(const n of this.adapter.getTextareaSelectors())try{if(e.matches(n))return e;const t=os.closestComposed(e,n);if(t instanceof HTMLElement)return t}catch{continue}const t=this.resolveEditor();return t&&this.containsInComposedTree(t,e)?t:null}resolveMountAnchor(e){const t=this.adapter.findSubmitButton(e)||this.findSubmitButtonBySelectors(e),n=[os.closestComposed(e,"form"),t?os.closestComposed(t,"form"):null,this.findClosestCommonAncestor(e,t),os.closestComposed(e,'[role="form"]')].filter(Boolean),r=this.pickBestMountCandidate(n,e,t);if(r)return r;const o=[os.closestComposed(e,".chat-input-editor-container"),os.closestComposed(e,".chat-editor"),os.closestComposed(e,".input-area-container"),os.closestComposed(e,".input-area"),os.closestComposed(e,".composer"),os.closestComposed(e,".footer-input-wrap"),os.closestComposed(e,".input-container"),os.closestComposed(e,".editor-container"),os.getComposedParentElement(e),e.parentElement].filter(Boolean);return this.pickBestMountCandidate(o,e,t)}pickBestMountCandidate(e,t,n){const r=Array.from(new Set(e)).filter(e=>{if(!e?.parentElement)return false;if(e===document.body||e===document.documentElement)return false;if(e.isContentEditable)return false;const t=e.getBoundingClientRect();return t.width>0&&t.height>0}).map(e=>({candidate:e,score:this.scoreMountCandidate(e,t,n)})).sort((e,t)=>t.score-e.score);return r[0]?.candidate||null}scoreMountCandidate(e,t,n){const r=e.getBoundingClientRect(),o=t.getBoundingClientRect(),i=Math.max(1,r.width*r.height);let a=0;const s=this.containsInComposedTree(e,t),l=!!n&&this.containsInComposedTree(e,n);"form"===e.tagName.toLowerCase()&&(a+=520),"form"===e.getAttribute("role")&&(a+=320),s&&(a+=160),l&&(a+=180),s&&l&&(a+=260),e===t.parentElement&&(a-=260);a-=.2*(Math.abs(r.top-o.top)+Math.abs(r.left-o.left)+Math.abs(r.bottom-o.bottom)),a-=i/5e3,r.height<1.4*o.height&&(a-=140);const c=e.parentElement;if(c){const e=window.getComputedStyle(c);if(e.display.includes("flex")&&!e.flexDirection.startsWith("column")&&this.containsInComposedTree(c,t)&&(!n||this.containsInComposedTree(c,n))){const e=c.getBoundingClientRect(),t=Math.max(1,e.width*e.height);t<2.2*i&&t{this.confirmPendingSend();},120)));}async confirmPendingSend(){if(!this.pendingSend)return void(null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));const e=this.pendingSend,t=this.resolveEditor(),n=this.getEditorText(t),r=this.getUserMessageCount(),o=this.adapter.isGenerating?.()??false,i=Date.now()-e.startedAt,a=r>e.preUserCount,s=o&&!e.preGenerating,l=e.normalizedText.length>0&&0===n.length,c=e.normalizedText.length>0&&n.length>0&&n!==e.normalizedText;if(a||s||l&&o||c&&o){this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null);const e=this.getEstimateSnapshot();return await async function(e){const t=Ck(e);if(!t)return;const n=await Tk();n.events=Ak([...n.events,t]),await Mk(n);}({id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),siteId:this.siteId,cid:this.adapter.getCurrentCid?.()||"default",sessionId:this.adapter.getSessionId?.()||"",countDelta:1,requestTokens:e.requestTokens,roundTripTokens:e.roundTripMid,loadedConversationTokens:e.loadedConversationTokens,loadedOutputTokens:e.loadedOutputTokens}),await this.syncCounterRecord(),this.currentRecord=await async function(e){const t=await Tk(),n=Sk(t.records[e]),r={count:n.count+1,updatedAt:Date.now(),resetAt:n.resetAt};return t.records[e]=r,await Mk(t),r}(this.getRecordKey()),void this.scheduleRender(0)}i>4e3&&(this.pendingSend=null,null!==this.pendingTimer&&(window.clearInterval(this.pendingTimer),this.pendingTimer=null));}getUserMessageCount(){const e=this.adapter.getUserQuerySelector();if(!e)return 0;try{return (os.query(e,{all:!0,shadow:!0})||[]).filter(e=>e instanceof HTMLElement&&e.isConnected).length}catch{return 0}}getEditorText(e){return e?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?pA(e.value||""):pA(e.textContent||""):""}getEstimateSnapshot(){const e=this.resolveEditor(),t=this.getEditorText(e),n=this.getLoadedConversationStats(),r=t.length,o=this.estimateTokens(t),i=this.estimateTokens([n.conversationText,t].filter(Boolean).join("\n")),a=i>0?i+Math.max(32,Math.ceil(.5*i)):0,s=i>0?i+Math.max(128,Math.ceil(2*i)):0,l=a>0||s>0?Math.round((a+s)/2):0;return {inputChars:r,loadedConversationChars:n.conversationChars,loadedConversationTokens:n.conversationTokens,loadedOutputChars:n.outputChars,loadedOutputTokens:n.outputTokens,requestTokens:Math.max(i,o),roundTripMin:a,roundTripMax:s,roundTripMid:l}}getLoadedConversationStats(){const e=this.adapter.getChatContentSelectors();if(!e.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};let t=[];try{t=os.query(e,{all:!0,shadow:!0})||[];}catch{t=[];}if(0===t.length)return {conversationText:"",conversationChars:0,conversationTokens:0,outputChars:0,outputTokens:0};const n=this.adapter.getUserQuerySelector(),r=Array.from(new Set(t)),o=[],i=[];r.forEach(e=>{const t=!!n&&this.matchesSelector(e,n),r=t?this.adapter.extractUserQueryMarkdown(e):this.adapter.extractAssistantResponseText(e),a=pA(r||e.textContent||"");a&&(o.push(a),t||i.push(a));});const a=o.join("\n"),s=i.join("\n");return {conversationText:a,conversationChars:a.length,conversationTokens:this.estimateTokens(a),outputChars:s.length,outputTokens:this.estimateTokens(s)}}matchesSelector(e,t){try{return e.matches(t)}catch{return false}}estimateTokens(e){if(!e)return 0;const t=(e.match(mA)||[]).length,n=(e.match(fA)||[]).length,r=(e.match(bA)||[]).length;return Math.max(0,Math.ceil(1.2*t+n/4+r/2))}detectThemeMode(){const e=document.documentElement.className;if(/\bdark\b/i.test(e))return "dark";if(/\blight\b/i.test(e))return "light";const t=document.body.className;if(/\bdark-theme\b/i.test(t))return "dark";if(/\blight-theme\b/i.test(t))return "light";const n=document.body.dataset.theme||document.documentElement.dataset.theme;return "dark"===n?"dark":"light"===n?"light":window.matchMedia?.("(prefers-color-scheme: dark)")?.matches?"dark":"light"}buildUsageMonitorPanel({title:e,usageLabel:t,resetButtonLabel:n,roundTripDesc:r,inputCharsLabel:o,loadedConversationLabel:i,loadedOutputLabel:a,requestTokensLabel:s,roundTripLabel:l,contextCharsLabel:c,manualModeLabel:d,count:u,limit:h,percent:g,estimate:p}){const m=document.createElement("div");m.className="gh-usage-monitor-panel";const f=document.createElement("div");f.className="gh-usage-monitor-top";const b=document.createElement("div");b.className="gh-usage-monitor-title",b.textContent=e;const y=document.createElement("div");if(y.className="gh-usage-monitor-meta",d){const e=document.createElement("span");e.className="gh-usage-monitor-badge",e.textContent=d,y.appendChild(e);}const v=document.createElement("div");v.className="gh-usage-monitor-count",v.textContent=`${t}: ${u} / ${h}`;const w=document.createElement("button");w.type="button",w.className="gh-usage-monitor-reset",w.dataset.action="reset-counter",w.textContent=n,y.append(v,w),f.append(b,y);const x=document.createElement("div");x.className="gh-usage-monitor-progress";const k=document.createElement("div");k.className="gh-usage-monitor-progress-bar",k.style.width=`${g.toFixed(1)}%`,x.appendChild(k);const S=document.createElement("div");S.className="gh-usage-monitor-grid",S.append(this.createUsageMonitorItem(o,`${p.inputChars} chars`),this.createUsageMonitorItem(i,`${p.loadedConversationTokens} tokens`),this.createUsageMonitorItem(a,`${p.loadedOutputTokens} tokens`),this.createUsageMonitorItem(s,`${p.requestTokens} tokens`),this.createUsageMonitorItem(l,`${p.roundTripMin}-${p.roundTripMax}`),this.createUsageMonitorItem(c,`${p.loadedConversationChars} chars`));const C=document.createElement("div");return C.className="gh-usage-monitor-footnote",C.textContent=r,m.append(f,x,S,C),m}createUsageMonitorItem(e,t){const n=document.createElement("div");n.className="gh-usage-monitor-item";const r=document.createElement("span");r.className="gh-usage-monitor-label",r.textContent=e;const o=document.createElement("span");return o.className="gh-usage-monitor-value",o.textContent=t,n.append(r,o),n}}const vA=[/^\s*#{1,6}\s+\S/m,/^\s*```/m,/^\s*(?:>|>)\s+\S/m,/^\s*[-*]\s+\S/m,/^\s*\d+\.\s+\S/m],wA=[/\*\*[^*]+\*\*/,/`[^`]+`/,/\[.+\]\(.+\)/],xA=[/(^|[^\\])\$\$[\s\S]+?\$\$/m,/\\\[[\s\S]+?\\\]/m],kA=[/(^|[^\\$])\$[^\s$](?:[^$\n]*[^\s$])?\$(?!\$)/,/\\\([^\n]+?\\\)/],SA="gh-user-query-markdown-style",CA="\n/* ============= 用户提问 Markdown 渲染样式 ============= */\n.gh-user-query-markdown {\n font-size: 15px;\n line-height: 1.6;\n color: inherit;\n /* 默认:浅色主题代码块(透明叠加,叠加在气泡背景之上,适配任意站点/主题) */\n --gh-user-query-code-bg: rgba(0, 0, 0, 0.06);\n --gh-user-query-code-border: rgba(0, 0, 0, 0.08);\n --gh-user-query-code-fg: #24292e;\n --gh-user-query-code-comment: #6a737d;\n --gh-user-query-code-keyword: #d73a49;\n --gh-user-query-code-string: #032f62;\n --gh-user-query-code-number: #005cc5;\n --gh-user-query-code-title: #6f42c1;\n --gh-user-query-code-type: #d73a49;\n --gh-user-query-code-variable: #e36209;\n --gh-user-query-code-scrollbar: rgba(0, 0, 0, 0.2);\n --gh-user-query-code-scrollbar-hover: rgba(0, 0, 0, 0.35);\n}\n\n.gh-user-query-markdown.gh-markdown-preview {\n color: inherit;\n}\n\n/* 为无原生气泡背景的站点(DeepSeek、Kimi 等)提供统一气泡底色\n * Gemini 的用户气泡由外层原生元素(user-query)提供背景,排除在外 */\n.gh-user-query-markdown:not(.gh-user-query-markdown-gemini) {\n background: rgba(0, 0, 0, 0.04);\n}\n\n/* 通用深色模式覆盖(覆盖非 Gemini 站点) */\nhtml.dark .gh-user-query-markdown,\nbody.dark .gh-user-query-markdown,\nhtml[data-theme='dark'] .gh-user-query-markdown,\nbody[data-theme='dark'] .gh-user-query-markdown,\nhtml[yb-theme-mode='dark'] .gh-user-query-markdown {\n --gh-user-query-code-bg: rgba(255, 255, 255, 0.09);\n --gh-user-query-code-border: rgba(255, 255, 255, 0.1);\n --gh-user-query-code-fg: #e6edf3;\n --gh-user-query-code-comment: #8b949e;\n --gh-user-query-code-keyword: #ff7b72;\n --gh-user-query-code-string: #a5d6ff;\n --gh-user-query-code-number: #79c0ff;\n --gh-user-query-code-title: #d2a8ff;\n --gh-user-query-code-type: #7ee787;\n --gh-user-query-code-variable: #ffa657;\n --gh-user-query-code-scrollbar: rgba(255, 255, 255, 0.2);\n --gh-user-query-code-scrollbar-hover: rgba(255, 255, 255, 0.35);\n}\nhtml.dark .gh-user-query-markdown:not(.gh-user-query-markdown-gemini),\nbody.dark .gh-user-query-markdown:not(.gh-user-query-markdown-gemini),\nhtml[data-theme='dark'] .gh-user-query-markdown:not(.gh-user-query-markdown-gemini),\nbody[data-theme='dark'] .gh-user-query-markdown:not(.gh-user-query-markdown-gemini),\nhtml[yb-theme-mode='dark'] .gh-user-query-markdown:not(.gh-user-query-markdown-gemini) {\n background: rgba(255, 255, 255, 0.05);\n}\n\n.gh-user-query-markdown.gh-user-query-markdown-qianwen {\n color: #111827 !important;\n background: #f3f6fb !important;\n border: 1px solid rgba(17, 24, 39, 0.06) !important;\n box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04) !important;\n --gh-user-query-code-bg: rgba(15, 23, 42, 0.07);\n --gh-user-query-code-border: rgba(15, 23, 42, 0.12);\n --gh-user-query-code-fg: #111827;\n --gh-user-query-code-comment: #64748b;\n --gh-user-query-code-keyword: #b91c1c;\n --gh-user-query-code-string: #075985;\n --gh-user-query-code-number: #1d4ed8;\n --gh-user-query-code-title: #6d28d9;\n --gh-user-query-code-type: #047857;\n --gh-user-query-code-variable: #c2410c;\n}\n\n.gh-user-query-markdown.gh-user-query-markdown-qianwen,\n.gh-user-query-markdown.gh-user-query-markdown-qianwen\n *:not(pre):not(code):not(svg):not(path):not(.hljs):not([class*='hljs-']) {\n color: #111827 !important;\n}\n\nhtml.dark .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nbody.dark .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nhtml[data-theme='dark'] .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nbody[data-theme='dark'] .gh-user-query-markdown.gh-user-query-markdown-qianwen {\n color: #f8fafc !important;\n background: #1f2937 !important;\n border-color: rgba(255, 255, 255, 0.12) !important;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.18) !important;\n --gh-user-query-code-bg: rgba(255, 255, 255, 0.1);\n --gh-user-query-code-border: rgba(255, 255, 255, 0.14);\n --gh-user-query-code-fg: #f8fafc;\n}\n\nhtml.dark .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nhtml.dark\n .gh-user-query-markdown.gh-user-query-markdown-qianwen\n *:not(pre):not(code):not(svg):not(path):not(.hljs):not([class*='hljs-']),\nbody.dark .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nbody.dark\n .gh-user-query-markdown.gh-user-query-markdown-qianwen\n *:not(pre):not(code):not(svg):not(path):not(.hljs):not([class*='hljs-']),\nhtml[data-theme='dark'] .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nhtml[data-theme='dark']\n .gh-user-query-markdown.gh-user-query-markdown-qianwen\n *:not(pre):not(code):not(svg):not(path):not(.hljs):not([class*='hljs-']),\nbody[data-theme='dark'] .gh-user-query-markdown.gh-user-query-markdown-qianwen,\nbody[data-theme='dark']\n .gh-user-query-markdown.gh-user-query-markdown-qianwen\n *:not(pre):not(code):not(svg):not(path):not(.hljs):not([class*='hljs-']) {\n color: #f8fafc !important;\n}\n\n.gh-user-query-markdown.gh-user-query-markdown-gemini {\n font-family: 'Google Sans', Roboto, 'Helvetica Neue', Arial, sans-serif !important;\n --gh-user-query-code-bg: rgba(0, 0, 0, 0.06);\n --gh-user-query-code-border: rgba(0, 0, 0, 0.08);\n --gh-user-query-code-fg: #24292e;\n --gh-user-query-code-comment: #6a737d;\n --gh-user-query-code-keyword: #d73a49;\n --gh-user-query-code-string: #032f62;\n --gh-user-query-code-number: #005cc5;\n --gh-user-query-code-title: #6f42c1;\n --gh-user-query-code-type: #d73a49;\n --gh-user-query-code-variable: #e36209;\n --gh-user-query-code-scrollbar: rgba(0, 0, 0, 0.2);\n --gh-user-query-code-scrollbar-hover: rgba(0, 0, 0, 0.35);\n}\n\nbody.dark-theme .gh-user-query-markdown.gh-user-query-markdown-gemini,\nhtml[dark-theme] .gh-user-query-markdown.gh-user-query-markdown-gemini {\n --gh-user-query-code-bg: rgba(255, 255, 255, 0.09);\n --gh-user-query-code-border: rgba(255, 255, 255, 0.1);\n --gh-user-query-code-fg: #e6edf3;\n --gh-user-query-code-comment: #8b949e;\n --gh-user-query-code-keyword: #ff7b72;\n --gh-user-query-code-string: #a5d6ff;\n --gh-user-query-code-number: #79c0ff;\n --gh-user-query-code-title: #d2a8ff;\n --gh-user-query-code-type: #7ee787;\n --gh-user-query-code-variable: #ffa657;\n --gh-user-query-code-scrollbar: rgba(255, 255, 255, 0.2);\n --gh-user-query-code-scrollbar-hover: rgba(255, 255, 255, 0.35);\n}\n\n.gh-user-query-markdown.gh-user-query-markdown-gemini pre,\n.gh-user-query-markdown.gh-user-query-markdown-gemini code {\n font-family: 'Roboto Mono', 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace !important;\n}\n\n/* 图片宽度不大于消息气泡 */\n.gh-user-query-markdown img {\n max-width: 100%;\n}\n\n/* 代码块外层包裹器 - 作为定位祖先,不参与滚动,使复制按钮始终固定在右上角 */\n.gh-user-query-markdown .gh-code-wrapper {\n position: relative;\n margin: 0.5em 0;\n}\n\n/* 代码块样式 - 透明叠加背景,在任意气泡背景上自动形成视觉层次 */\n.gh-user-query-markdown pre {\n margin: 0;\n padding: 0.75em;\n padding-right: 0.5em;\n background: var(--gh-user-query-code-bg);\n border: 1px solid var(--gh-user-query-code-border);\n color: var(--gh-user-query-code-fg);\n border-radius: 6px;\n font-size: 0.95em;\n max-height: 200px;\n overflow: auto;\n}\n\n/* 美化滚动条 */\n.gh-user-query-markdown pre::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-track {\n background: transparent;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-thumb {\n background: var(--gh-user-query-code-scrollbar);\n border-radius: 3px;\n}\n.gh-user-query-markdown pre::-webkit-scrollbar-thumb:hover {\n background: var(--gh-user-query-code-scrollbar-hover);\n}\n\n.gh-user-query-markdown pre code {\n background: transparent !important;\n color: var(--gh-user-query-code-fg) !important;\n padding: 0;\n display: block;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n overflow: visible; /* 覆盖 .hljs 的 overflow-x: auto,让 pre 控制滚动 */\n}\n\n.gh-user-query-markdown pre .hljs-comment,\n.gh-user-query-markdown pre .hljs-quote {\n color: var(--gh-user-query-code-comment) !important;\n}\n.gh-user-query-markdown pre .hljs-keyword,\n.gh-user-query-markdown pre .hljs-selector-tag,\n.gh-user-query-markdown pre .hljs-doctag {\n color: var(--gh-user-query-code-keyword) !important;\n}\n.gh-user-query-markdown pre .hljs-string,\n.gh-user-query-markdown pre .hljs-regexp {\n color: var(--gh-user-query-code-string) !important;\n}\n.gh-user-query-markdown pre .hljs-number,\n.gh-user-query-markdown pre .hljs-literal,\n.gh-user-query-markdown pre .hljs-attr,\n.gh-user-query-markdown pre .hljs-attribute {\n color: var(--gh-user-query-code-number) !important;\n}\n.gh-user-query-markdown pre .hljs-title,\n.gh-user-query-markdown pre .hljs-section,\n.gh-user-query-markdown pre .hljs-selector-id {\n color: var(--gh-user-query-code-title) !important;\n}\n.gh-user-query-markdown pre .hljs-type,\n.gh-user-query-markdown pre .hljs-class .hljs-title {\n color: var(--gh-user-query-code-type) !important;\n}\n.gh-user-query-markdown pre .hljs-variable,\n.gh-user-query-markdown pre .hljs-template-variable,\n.gh-user-query-markdown pre .hljs-built_in {\n color: var(--gh-user-query-code-variable) !important;\n}\n\n/* 行内代码 */\n.gh-user-query-markdown.gh-markdown-preview :not(pre) > code:not(.hljs),\n.gh-user-query-markdown :not(pre) > code {\n background: var(--gh-user-query-code-bg) !important;\n color: var(--gh-user-query-code-fg) !important;\n padding: 0.2em 0.4em;\n border-radius: 4px;\n font-size: 0.9em;\n}\n\n/* 代码块复制按钮 - 绝对定位于 .gh-code-wrapper 右上角,wrapper 不滚动故按钮始终可见 */\n.gh-user-query-markdown .gh-code-copy-btn {\n position: absolute;\n top: 6px;\n right: 6px;\n width: 24px;\n height: 24px;\n padding: 0;\n background: rgba(255, 255, 255, 0.9);\n border: 1px solid rgba(0, 0, 0, 0.1);\n border-radius: 4px;\n color: #666;\n font-size: 12px;\n cursor: pointer;\n opacity: 0.2;\n pointer-events: none;\n transition: opacity 0.2s, background 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 1;\n}\n.gh-user-query-markdown .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n pointer-events: auto;\n}\n.gh-user-query-markdown .gh-code-copy-btn:hover {\n background: #4285f4;\n color: white;\n border-color: #4285f4;\n}\n\n/* 标题间距优化 */\n.gh-user-query-markdown h1,\n.gh-user-query-markdown h2,\n.gh-user-query-markdown h3,\n.gh-user-query-markdown h4,\n.gh-user-query-markdown h5,\n.gh-user-query-markdown h6 {\n margin: 0.5em 0 0.3em;\n line-height: 1.3;\n}\n\n.gh-user-query-markdown h1 { font-size: 1.3em; }\n.gh-user-query-markdown h2 { font-size: 1.2em; }\n.gh-user-query-markdown h3 { font-size: 1.1em; }\n\n/* 列表样式 */\n.gh-user-query-markdown ul,\n.gh-user-query-markdown ol {\n margin: 0.4em 0;\n padding-left: 1.5em;\n}\n\n.gh-user-query-markdown li {\n margin: 0.2em 0;\n}\n\n/* 引用块 */\n.gh-user-query-markdown blockquote {\n margin: 0.5em 0;\n padding: 0.5em 1em;\n border-left: 3px solid #4285f4;\n background: rgba(0, 0, 0, 0.03);\n color: inherit;\n border-radius: 0 4px 4px 0;\n}\n\n/* 表格优化 */\n.gh-user-query-markdown table {\n margin: 0.5em 0;\n font-size: 0.9em;\n}\n\n/* 分隔线 */\n.gh-user-query-markdown hr {\n margin: 0.5em 0;\n border: none;\n border-top: 1px solid #e5e7eb;\n}\n\n/* 深色模式适配 */\nbody.dark-theme .gh-user-query-markdown :not(pre) > code {\n background: rgba(255, 255, 255, 0.12);\n}\nbody.dark-theme .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nbody.dark-theme .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nbody.dark-theme .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n\n/* Gemini Enterprise 深色模式 */\nhtml[dark-theme] .gh-user-query-markdown :not(pre) > code {\n background: rgba(255, 255, 255, 0.12);\n}\nhtml[dark-theme] .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nhtml[dark-theme] .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nhtml[dark-theme] .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n\n/* ChatGPT 深色模式(使用 html.dark 类) */\nhtml.dark .gh-user-query-markdown :not(pre) > code {\n background: rgba(255, 255, 255, 0.12);\n}\nhtml.dark .gh-user-query-markdown .gh-code-copy-btn {\n background: rgba(0, 0, 0, 0.5);\n border-color: rgba(255, 255, 255, 0.1);\n color: #aaa;\n}\nhtml.dark .gh-user-query-markdown blockquote {\n background: rgba(255, 255, 255, 0.05);\n}\nhtml.dark .gh-user-query-markdown hr {\n border-top-color: #4b5563;\n}\n";function AA(e){const t=e.trim();return !!t&&(vA.some(e=>e.test(t))||wA.some(e=>e.test(t))||function(e){const t=function(e){return e.replace(/```[\s\S]*?```/g,"").replace(/`[^`\n]*`/g,"")}(e);return xA.some(e=>e.test(t))||kA.some(e=>e.test(t))}(t))}class EA{adapter;enabled;processedElements=new WeakMap;stopWatch=null;rescanTimer=null;injectedShadowRoots=new WeakSet;codeCopyHandler=null;constructor(e,t){this.adapter=e,this.enabled=t,t&&this.init();}init(){const e=this.adapter.getUserQuerySelector();if(!e)return void console.warn("[UserQueryMarkdownRenderer] No user query selector found for this site");if(this.adapter.usesShadowDOM())this.startRescanTimer();else {this.injectGlobalStyles(),this.initCodeCopyHandler(),this.stopWatch=os.each(e,e=>{this.processQueryElement(e);},{shadow:true});const t=this.adapter.getSiteId();t!==mo&&t!==wo&&t!==vo||this.startRescanTimer();}}injectGlobalStyles(){if(document.getElementById(SA))return;const e=document.createElement("style");e.id=SA,e.textContent=["\n/* highlight.js GitHub Dark 主题\n 面板(Shadow DOM)通过 var() 跟随 Ophel 主题变量;\n 主文档注入(用户提问)var() 不可用,fallback 为 #1e1e1e */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview :not(pre) > code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview .gh-code-wrapper {\n position: relative;\n margin: 12px 0;\n}\n.gh-markdown-preview pre {\n margin: 0;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n",Wh(),CA].filter(Boolean).join("\n"),document.head.appendChild(e);}injectStyleToShadowRoot(e){if(this.injectedShadowRoots.has(e))return;if(e.querySelector(`#${SA}`))return;const t=document.createElement("style");t.id=SA,t.textContent=["\n/* highlight.js GitHub Dark 主题\n 面板(Shadow DOM)通过 var() 跟随 Ophel 主题变量;\n 主文档注入(用户提问)var() 不可用,fallback 为 #1e1e1e */\n.hljs {\n background: var(--gh-bg-tertiary, #1e1e1e);\n color: var(--gh-text, #e6edf3);\n padding: 12px;\n border-radius: 6px;\n overflow-x: auto;\n font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;\n font-size: 13px;\n line-height: 1.5;\n /* 代码块自动换行 */\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n.hljs-comment,\n.hljs-quote { color: #8b949e; font-style: italic; }\n.hljs-keyword,\n.hljs-selector-tag { color: #ff7b72; }\n.hljs-string,\n.hljs-doctag { color: #a5d6ff; }\n.hljs-number,\n.hljs-literal { color: #79c0ff; }\n.hljs-title,\n.hljs-section,\n.hljs-selector-id { color: #d2a8ff; font-weight: bold; }\n.hljs-function > .hljs-title { color: #d2a8ff; }\n.hljs-type,\n.hljs-class .hljs-title { color: #7ee787; }\n.hljs-attribute { color: #79c0ff; }\n.hljs-variable,\n.hljs-template-variable { color: #ffa657; }\n.hljs-built_in { color: #ffa657; }\n.hljs-addition { color: #aff5b4; background: rgba(46, 160, 67, 0.15); }\n.hljs-deletion { color: #ffdcd7; background: rgba(248, 81, 73, 0.15); }\n\n/* 变量占位符高亮 */\n.gh-variable-highlight {\n background: rgba(56, 139, 253, 0.2);\n color: #58a6ff;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 500;\n}\n\n/* Markdown 渲染样式 */\n.gh-markdown-preview {\n line-height: 1.6;\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview h1,\n.gh-markdown-preview h2,\n.gh-markdown-preview h3 {\n margin: 16px 0 8px;\n font-weight: 600;\n border-bottom: 1px solid var(--gh-border, #30363d);\n padding-bottom: 4px;\n}\n.gh-markdown-preview h1 { font-size: 1.5em; }\n.gh-markdown-preview h2 { font-size: 1.3em; }\n.gh-markdown-preview h3 { font-size: 1.1em; }\n.gh-markdown-preview p { margin: 8px 0; }\n.gh-markdown-preview :not(pre) > code:not(.hljs) {\n background: var(--gh-bg-tertiary, #343942);\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 13px;\n}\n.gh-markdown-preview .gh-code-wrapper {\n position: relative;\n margin: 12px 0;\n}\n.gh-markdown-preview pre {\n margin: 0;\n max-width: 100%;\n overflow: hidden;\n}\n.gh-markdown-preview pre code {\n display: block;\n max-width: 100%;\n overflow-x: auto;\n white-space: pre-wrap;\n word-wrap: break-word;\n word-break: break-all;\n}\n/* 代码块复制按钮 */\n.gh-code-copy-btn {\n position: absolute;\n top: 8px;\n right: 8px;\n padding: 4px 8px;\n background: var(--gh-bg-secondary, #2d333b);\n border: 1px solid var(--gh-border, #444c56);\n border-radius: 4px;\n color: var(--gh-text-secondary, #8b949e);\n font-size: 12px;\n cursor: pointer;\n opacity: 0;\n transition: opacity 0.2s;\n}\n.gh-markdown-preview .gh-code-wrapper:hover .gh-code-copy-btn {\n opacity: 1;\n}\n.gh-code-copy-btn:hover {\n background: var(--gh-hover, #373e47);\n color: var(--gh-text, #e6edf3);\n}\n.gh-markdown-preview blockquote {\n border-left: 3px solid var(--gh-primary, #4285f4);\n margin: 12px 0;\n padding: 8px 16px;\n background: var(--gh-bg-secondary, #161b22);\n color: var(--gh-text-secondary, #8b949e);\n}\n.gh-markdown-preview ul,\n.gh-markdown-preview ol {\n margin: 8px 0;\n padding-left: 24px;\n}\n.gh-markdown-preview li { margin: 4px 0; }\n.gh-markdown-preview a {\n color: var(--gh-primary, #58a6ff);\n text-decoration: none;\n}\n.gh-markdown-preview a:hover { text-decoration: underline; }\n\n/* 任务列表样式 */\n.gh-markdown-preview .task-list-item {\n list-style: none;\n margin-left: -20px;\n}\n.gh-markdown-preview .task-list-item input[type=\"checkbox\"] {\n margin-right: 8px;\n pointer-events: none;\n}\n\n/* 高亮 ==text== */\n.gh-markdown-preview mark {\n background: rgba(255, 235, 59, 0.4);\n color: inherit;\n padding: 2px 4px;\n border-radius: 3px;\n}\n\n/* 容器样式 :::info, :::warning, :::danger */\n.gh-container {\n margin: 12px 0;\n padding: 12px 16px;\n border-radius: 6px;\n border-left: 4px solid;\n}\n.gh-container-info {\n background: rgba(56, 139, 253, 0.1);\n border-color: #388bfd;\n}\n.gh-container-warning {\n background: rgba(255, 166, 87, 0.1);\n border-color: #ffa657;\n}\n.gh-container-danger {\n background: rgba(248, 81, 73, 0.1);\n border-color: #f85149;\n}\n",Wh(),CA].filter(Boolean).join("\n"),e.prepend(t),this.injectedShadowRoots.add(e),e.addEventListener("click",e=>this.handleCodeCopy(e));}handleCodeCopy(e){const t=e.target.closest(".gh-code-copy-btn");if(t&&t.closest(".gh-user-query-markdown")){e.preventDefault(),e.stopPropagation();const n=t.nextElementSibling?.textContent||"";navigator.clipboard.writeText(n).then(()=>{mp(t,{size:14});}).catch(e=>{console.error("[UserQueryMarkdownRenderer] Copy failed:",e);});}}initCodeCopyHandler(){this.codeCopyHandler||(this.codeCopyHandler=e=>this.handleCodeCopy(e),document.addEventListener("click",this.codeCopyHandler,true));}startRescanTimer(){this.rescanTimer||(setTimeout(()=>{this.enabled&&this.rescan();},1e3),this.rescanTimer=window.setInterval(()=>{this.enabled&&this.rescan();},2e3));}rescan(){if(document.hidden||!document.hasFocus())return;const e=this.adapter.getUserQuerySelector();if(!e)return;const t=os.query(e,{all:true,shadow:true});for(const n of t)this.processQueryElement(n);}processQueryElement(e){const t=this.adapter.extractUserQueryMarkdown(e);if(!t)return;if(!AA(t))return;if(this.processedElements.get(e)===t)return;const n=Hh(t,false,{enableMath:true});if(this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&this.injectStyleToShadowRoot(t.shadowRoot);}const r=this.adapter.replaceUserQueryContent(e,n);let o=e.querySelector(".gh-user-query-markdown");if(!o&&this.adapter.usesShadowDOM()){const t=e.querySelector("ucs-fast-markdown");t?.shadowRoot&&(o=t.shadowRoot.querySelector(".gh-user-query-markdown"));}if(o)return fp(o,{size:14,color:"#6b7280"}),void this.processedElements.set(e,t);r&&this.processedElements.set(e,t);}updateSettings(e){this.enabled!==e&&(this.enabled=e,e?this.init():this.stop());}stop(){this.stopWatch&&(this.stopWatch(),this.stopWatch=null),this.rescanTimer&&(clearInterval(this.rescanTimer),this.rescanTimer=null);}destroy(){this.stop(),this.processedElements=new WeakMap,this.injectedShadowRoots=new WeakSet;const e=document.getElementById(SA);e&&e.remove(),this.codeCopyHandler&&(document.removeEventListener("click",this.codeCopyHandler,true),this.codeCopyHandler=null);}}const TA=/^https:\/\/lh3\.googleusercontent\.com\//i,MA="ophel-watermark-loading-style",_A="watermark-not-detected",IA=["[data-image-attachment-index]","single-image.generated-image","generated-image",".generated-image-container",".image-container.replace-fife-images-at-export"].join(", ");class LA{static WATERMARK_BG_PATHS={48:"assets/userscript/ophel-watermark-bg-48.png",96:"assets/userscript/ophel-watermark-bg-96.png"};static WATERMARK_CONFIGS={48:{logoSize:48,marginRight:32,marginBottom:32},96:{logoSize:96,marginRight:64,marginBottom:64}};static ALPHA_THRESHOLD=.002;static MAX_ALPHA=.99;static LOGO_VALUE=255;static DETECTION_MIN_SCORE=.012;static DETECTION_MIN_NORMALIZED_SCORE=.09;static DETECTION_MIN_IMPROVEMENT=.01;static DETECTION_MIN_NORMALIZED_IMPROVEMENT=.04;static DETECTION_MAX_DARKENING=.12;static MAX_VALIDATION_CANDIDATES=4;alphaMaps={};bgImages={};processingQueue=new Set;processingMap=new Map;processedDataUrlCache=new Map;enabled=false;stopObserver=null;mainWorldMessageListener=null;actionButtonListener=null;userscriptOriginalFetch=null;constructor(){this.alphaMaps={},this.bgImages={},this.processingQueue=new Set,this.processingMap=new Map,this.processedDataUrlCache=new Map;}start(){this.enabled||(this.enabled=true,this.enableUserscriptFetchInterception(),this.processExistingImages(),this.startObserver());}stop(){this.enabled&&(this.enabled=false,this.disableUserscriptFetchInterception(),this.teardownActionButtonInterception(),this.processingMap.clear(),this.processingQueue.clear(),this.clearAllProcessingIndicators(),this.removeProcessingIndicatorStyles(),this.stopObserver&&(this.stopObserver(),this.stopObserver=null));}isGeminiStandardSite(){return "gemini.google.com"===window.location.hostname}shouldInterceptGeminiImageUrl(e){return TA.test(e)}isLikelyGeneratedImage(e){const t=e.currentSrc||e.src||"";if(!t)return false;const n=e.naturalWidth||e.width||0,r=e.naturalHeight||e.height||0;return !(n<192||r<192)&&(this.shouldInterceptGeminiImageUrl(t)||t.startsWith("data:image/")||t.startsWith("blob:"))}isSupportedGeminiImageSource(e){return !!e&&(this.shouldInterceptGeminiImageUrl(e)||e.startsWith("data:image/")||e.startsWith("blob:"))}getImageSourceForAction(e){const t=e.getAttribute("data-ophel-wm-source")||"";if(t)return t;return e.currentSrc||e.src||""}normalizePossibleUrl(e){if(!e)return "";if(e.startsWith("data:image/")||e.startsWith("blob:"))return e;try{return new URL(e,window.location.href).toString()}catch{return e}}getNormalizedGeminiPath(e=window.location.pathname){return e.replace(/^\/u\/\d+/,"")}isGeminiConversationPath(e=this.getNormalizedGeminiPath()){return "/app"===e||"/app/"===e||e.startsWith("/app/")}isGeminiSharedImagePath(e=this.getNormalizedGeminiPath()){return "/share"===e||"/share/"===e||e.startsWith("/share/")}isGeminiInlineDisplayPath(e=this.getNormalizedGeminiPath()){return this.isGeminiConversationPath(e)||this.isGeminiSharedImagePath(e)}isUserscriptInlineDisplaySource(e){return !!e&&this.isGeminiInlineDisplayPath()&&(e.startsWith("blob:")||e.startsWith("data:image/"))}getWatermarkConfigBySize(e){return {...LA.WATERMARK_CONFIGS[e]}}shouldUseConversationPreviewWatermark(e){if(!e||!this.isGeminiConversationPath())return false;const t=this.normalizePossibleUrl(e);return !!this.shouldInterceptGeminiImageUrl(t)&&t.includes("/gg/")}shouldSkipAutoProcessingSource(e){return !(!e.startsWith("blob:")&&!e.startsWith("data:image/"))&&(!this.isUserscriptInlineDisplaySource(e)&&null!==this.userscriptOriginalFetch)}ensureProcessingIndicatorStyles(){if(document.getElementById(MA))return;if(!document.head)return;const e=document.createElement("style");e.id=MA,e.textContent='\n [data-ophel-wm-loading="1"] {\n isolation: isolate;\n }\n\n .ophel-wm-loading-indicator {\n position: absolute;\n bottom: 20px;\n right: 20px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: 999px;\n background: rgba(15, 23, 42, 0.72);\n box-shadow: 0 10px 24px rgba(15, 23, 42, 0.22);\n backdrop-filter: blur(8px);\n -webkit-backdrop-filter: blur(8px);\n pointer-events: none;\n z-index: 2;\n }\n\n .ophel-wm-loading-indicator::after {\n content: "";\n width: 12px;\n height: 12px;\n border-radius: 50%;\n border: 2px solid rgba(255, 255, 255, 0.35);\n border-top-color: rgba(255, 255, 255, 1);\n animation: ophel-wm-loading-spin 0.72s linear infinite;\n }\n\n @keyframes ophel-wm-loading-spin {\n from {\n transform: rotate(0deg);\n }\n\n to {\n transform: rotate(360deg);\n }\n }\n ',document.head.appendChild(e);}removeProcessingIndicatorStyles(){document.getElementById(MA)?.remove();}findProcessingIndicatorHost(e){const t=e.closest(IA);return t instanceof HTMLElement?t:e.parentElement instanceof HTMLElement?e.parentElement:e}restoreProcessingIndicatorHost(e){e.removeAttribute("data-ophel-wm-loading"),e.removeAttribute("data-ophel-wm-loading-count"),e.querySelector(".ophel-wm-loading-indicator")?.remove(),"1"===e.dataset.ophelWmLoadingManagedPosition&&(e.style.position=e.dataset.ophelWmLoadingOriginalPosition||"",delete e.dataset.ophelWmLoadingManagedPosition,delete e.dataset.ophelWmLoadingOriginalPosition);}showImageProcessingIndicator(e){const t=this.findProcessingIndicatorHost(e);if(!t)return null;this.ensureProcessingIndicatorStyles();const n=Number(t.dataset.ophelWmLoadingCount||"0");if(n<=0){"static"===window.getComputedStyle(t).position&&(t.dataset.ophelWmLoadingManagedPosition="1",t.dataset.ophelWmLoadingOriginalPosition=t.style.position||"",t.style.position="relative"),t.setAttribute("data-ophel-wm-loading","1");const e=document.createElement("div");e.className="ophel-wm-loading-indicator",e.setAttribute("aria-hidden","true"),e.title=se("watermarkProcessing"),t.appendChild(e);}return t.dataset.ophelWmLoadingCount=String(Math.max(0,n)+1),t}hideImageProcessingIndicator(e){if(!e)return;const t=Number(e.dataset.ophelWmLoadingCount||"0");t>1?e.dataset.ophelWmLoadingCount=String(t-1):this.restoreProcessingIndicatorHost(e);}clearAllProcessingIndicators(){document.querySelectorAll('[data-ophel-wm-loading="1"]').forEach(e=>{this.restoreProcessingIndicatorHost(e);});}extractSupportedUrlFromNode(e){const t=[],n=[],r=[],o=e=>{if(!e)return;const o=this.normalizePossibleUrl(e);this.isSupportedGeminiImageSource(o)&&(this.shouldInterceptGeminiImageUrl(o)?t.push(o):o.startsWith("blob:")?n.push(o):o.startsWith("data:image/")&&r.push(o));const i=e.match(/https?:\/\/[^\s"'<>]*googleusercontent\.com[^\s"'<>]*/gi);if(i&&0!==i.length)for(const n of i){const e=this.normalizePossibleUrl(n);this.shouldInterceptGeminiImageUrl(e)&&t.push(e);}};for(const i of Array.from(e.attributes))o(i?.value||"");return e instanceof HTMLAnchorElement&&e.href&&o(e.href),e instanceof HTMLImageElement&&o(e.currentSrc||e.src||""),t[0]||n[0]||r[0]||""}getRequestUrl(e){if("string"==typeof e)return e;if(e&&"object"==typeof e&&"url"in e){const t=e;if("string"==typeof t.url)return t.url}return ""}toggleMainWorldFetchInterception(e){this.isGeminiStandardSite()&&window.postMessage({type:"OPHEL_WATERMARK_FETCH_TOGGLE",enabled:e},"*");}setupMainWorldBridge(){!this.mainWorldMessageListener&&this.isGeminiStandardSite()&&(this.mainWorldMessageListener=e=>{if(e.source!==window)return;const t=e.data;if(!t||"OPHEL_WATERMARK_PROCESS_REQUEST"!==t.type)return;const n=t.requestId||"",r=t.url||"",o=t.arrayBuffer,i=t.mimeType||"";n&&r&&this.handleMainWorldProcessRequest(n,r,o,i);},window.addEventListener("message",this.mainWorldMessageListener));}teardownMainWorldBridge(){this.mainWorldMessageListener&&(window.removeEventListener("message",this.mainWorldMessageListener),this.mainWorldMessageListener=null);}postMainWorldProcessResponse(e){window.postMessage({type:"OPHEL_WATERMARK_PROCESS_RESPONSE",...e},"*");}async handleMainWorldProcessRequest(e,t,n,r){if(this.enabled&&this.shouldInterceptGeminiImageUrl(t))try{const o=n?new Blob([n],{type:r||"image/png"}):void 0,i=o?await this.processImageBlobToDataUrl(o,t):await this.getProcessedDataUrl(t);this.postMainWorldProcessResponse({requestId:e,success:!0,dataUrl:i});}catch(o){this.postMainWorldProcessResponse({requestId:e,success:false,error:o instanceof Error?o.message:"Unknown processing error"});}else this.postMainWorldProcessResponse({requestId:e,success:false,error:"Watermark interceptor disabled"});}getUserscriptPageWindow(){return "undefined"!=typeof unsafeWindow&&unsafeWindow&&unsafeWindow!==window?unsafeWindow:window}enableUserscriptFetchInterception(){if(this.userscriptOriginalFetch||!this.isGeminiStandardSite())return;const e=this.getUserscriptPageWindow();this.userscriptOriginalFetch=e.fetch.bind(e),e.fetch=async(...t)=>{const n=this.getRequestUrl(t[0]);if(!this.enabled||!n||!this.shouldInterceptGeminiImageUrl(n))return this.userscriptOriginalFetch.apply(e,t);try{const e=await this.getProcessedDataUrl(n),t=await this.dataUrlToBlob(e);return new Response(t,{status:200,statusText:"OK",headers:new Headers({"Content-Type":t.type||"image/png"})})}catch{return this.userscriptOriginalFetch.apply(e,t)}};}disableUserscriptFetchInterception(){if(!this.userscriptOriginalFetch)return;this.getUserscriptPageWindow().fetch=this.userscriptOriginalFetch,this.userscriptOriginalFetch=null;}setupActionButtonInterception(){}teardownActionButtonInterception(){this.actionButtonListener&&(document.removeEventListener("click",this.actionButtonListener,true),this.actionButtonListener=null);}isActionButtonElement(e,t){const n=[e.getAttribute("aria-label")||"",e.getAttribute("data-tooltip")||"",e.getAttribute("mattooltip")||"",e.getAttribute("title")||"",(e.textContent||"").trim()].join(" ").trim().trim().toLowerCase();return "copy"===t?n.includes("copy")||n.includes("copy image")||n.includes("copy full")||n.includes("复制")||n.includes("複製"):n.includes("download")||n.includes("save image")||n.includes("full size")||n.includes("下载")||n.includes("下載")}findImageAction(e){const t=("function"==typeof e.composedPath?e.composedPath():[]).filter(e=>e instanceof Element),n=e.target instanceof Element?e.target:null,r=[];if(n){const e=n.closest("button,[role='button']");e&&r.push(e);}for(const i of t)i instanceof HTMLElement&&(i.matches("button")||"button"===i.getAttribute("role"))&&r.push(i);const o=Array.from(new Set(r));if(0===o.length)return null;for(const i of o){if(this.isActionButtonElement(i,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(i,"download"))return {action:"download",button:i};for(const e of Array.from(i.querySelectorAll("[aria-label],[data-tooltip],[mattooltip]"))){if(this.isActionButtonElement(e,"copy"))return {action:"copy",button:i};if(this.isActionButtonElement(e,"download"))return {action:"download",button:i}}}return null}findRelatedGeminiImage(e){let t=e;for(let a=0;a<6&&t;a++){const e=Array.from(t.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}t=t.parentElement;}const n=e.getBoundingClientRect(),r=n.left+n.width/2,o=n.top+n.height/2,i=document.elementFromPoint(r,o)?.closest("generated-image, .generated-image-container");if(i){const e=Array.from(i.querySelectorAll("img"));for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findBestVisibleGeminiImage(){const e=Array.from(document.querySelectorAll("img")).filter(e=>!!this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(this.getImageSourceForAction(e))).filter(e=>{const t=e.getBoundingClientRect();return t.width>120&&t.height>120&&t.bottom>0&&t.right>0});return 0===e.length?null:(e.sort((e,t)=>{const n=e.getBoundingClientRect(),r=t.getBoundingClientRect();return r.width*r.height-n.width*n.height}),e[0]||null)}findRelatedGeminiImageFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];for(const n of t){if(!(n instanceof Element))continue;if(n instanceof HTMLImageElement){const e=this.getImageSourceForAction(n);if(this.isValidGeminiImage(n)&&this.isSupportedGeminiImageSource(e))return n}const e=Array.from(n.querySelectorAll?.("img")||[]);for(const t of e){const e=this.getImageSourceForAction(t);if(this.isValidGeminiImage(t)&&this.isSupportedGeminiImageSource(e))return t}}return null}findGeminiSourceUrlFromEvent(e){const t="function"==typeof e.composedPath?e.composedPath():[];let n="",r="";for(const o of t){if(!(o instanceof Element))continue;const e=this.extractSupportedUrlFromNode(o);if(e){if(this.shouldInterceptGeminiImageUrl(e))return e;!n&&e.startsWith("blob:")&&(n=e),!r&&e.startsWith("data:image/")&&(r=e);}}return n||r||""}async resolveActionDataUrl(e){return this.isUserscriptInlineDisplaySource(e)?this.getProcessedInlineDisplayDataUrl(e):e.startsWith("data:image/")?e:e.startsWith("blob:")?this.processImageSourceToDataUrl(e):this.getProcessedDataUrl(e)}async writeImageToClipboard(e){const t=await this.dataUrlToBlob(e);if("undefined"==typeof ClipboardItem||!navigator.clipboard?.write)throw new Error("Clipboard API unavailable");const n=new ClipboardItem({[t.type||"image/png"]:t});await navigator.clipboard.write([n]);}triggerDownloadFromDataUrl(e){const t=document.createElement("a");t.href=e,t.download=`gemini-image-${Date.now()}.png`,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove();}shouldUseNativeGeminiAction(){return null!==this.userscriptOriginalFetch}async resolveProcessedDataUrlForAction(e,t){if(e.startsWith("data:image/"))return e;if(e.startsWith("blob:"))return this.resolveActionDataUrl(e);try{return await this.getProcessedDataUrl(e,{bypassCache:!0,requireNonPreviewSource:!0})}catch(n){const r=n instanceof Error?n.message:"";if("copy"===t&&"fullsize-source-unavailable"===r)return this.getProcessedDataUrl(e,{bypassCache:true,requireNonPreviewSource:false});throw n}}async handleActionButtonClick(e){if(!this.enabled||!this.isGeminiStandardSite())return;const t=this.findImageAction(e);if(!t)return;if(this.shouldUseNativeGeminiAction())return;const n=this.findRelatedGeminiImageFromEvent(e)||this.findRelatedGeminiImage(t.button)||this.findBestVisibleGeminiImage(),r=this.findGeminiSourceUrlFromEvent(e)||(n?this.getImageSourceForAction(n):"");if(!r)return;if(!this.isSupportedGeminiImageSource(r))return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();const o=n?this.showImageProcessingIndicator(n):null;try{const e=await this.resolveProcessedDataUrlForAction(r,t.action);if(!e)return;n&&n.setAttribute("data-ophel-wm-processed","1"),"copy"===t.action?await this.writeImageToClipboard(e):this.triggerDownloadFromDataUrl(e);}catch{return}finally{this.hideImageProcessingIndicator(o);}}calculateAlphaMap(e){const{width:t,height:n,data:r}=e,o=new Float32Array(t*n);for(let i=0;i1024&&t>1024?this.getWatermarkConfigBySize(96):this.getWatermarkConfigBySize(48)}calculateWatermarkPosition(e,t,n){const{logoSize:r,marginRight:o,marginBottom:i}=n;return {x:e-o-r,y:t-i-r,width:r,height:r}}isWatermarkPositionInsideImage(e,t,n){return n.x>=0&&n.y>=0&&n.x+n.width<=e&&n.y+n.height<=t}getPixelLuminance(e,t){return (.2126*e[t]+.7152*e[t+1]+.0722*e[t+2])/255}measureWatermarkCandidate(e,t,n){let r=0,o=0;for(let m=0;m0?r/o:0,a=Math.max(8,Math.round(n.width/4)),s=Math.max(0,n.x-a),l=Math.max(0,n.y-a),c=Math.min(e.width,n.x+n.width+a),d=Math.min(e.height,n.y+n.height+a);let u=0,h=0;for(let m=l;m=n.x&&t=n.y&&m0?u/h:i,p=i-g;return {insideMean:i,outsideMean:g,score:p,normalizedScore:p/Math.max(.08,1-Math.min(g,.98))}}hasDetectableWatermark(e){return e.score>=LA.DETECTION_MIN_SCORE||e.normalizedScore>=LA.DETECTION_MIN_NORMALIZED_SCORE}cloneImageData(e){return new ImageData(new Uint8ClampedArray(e.data),e.width,e.height)}getInlineDisplayWatermarkConfigs(e,t,n){const r=this.detectWatermarkConfig(e,t,n),o=48===r.logoSize?96:48;return [r,this.getWatermarkConfigBySize(o)].filter((e,t,n)=>n.findIndex(t=>t.logoSize===e.logoSize)===t)}getWatermarkSearchOffsets(e){const t=96===e?12:8,n=96===e?24:16,r=[0];for(let o=t;o<=n;o+=t)r.push(-o,o);return r}isWatermarkRemovalValid(e,t){const n=e.score-t.score,r=e.normalizedScore-t.normalizedScore,o=Math.max(.65*e.score,.018),i=Math.max(.65*e.normalizedScore,.05),a=e.outsideMean-t.insideMean;return this.hasDetectableWatermark(e)&&(n>=LA.DETECTION_MIN_IMPROVEMENT||r>=LA.DETECTION_MIN_NORMALIZED_IMPROVEMENT)&&t.score<=o&&t.normalizedScore<=i&&a<=LA.DETECTION_MAX_DARKENING}async buildInlineDisplayWatermarkCandidates(e,t){const n=this.getInlineDisplayWatermarkConfigs(e.width,e.height,t),r=await Promise.all(n.map(e=>this.getAlphaMap(e.logoSize))),o=[],i=new Set;return n.forEach((t,n)=>{const a=this.calculateWatermarkPosition(e.width,e.height,t),s=this.getWatermarkSearchOffsets(t.logoSize),l=r[n];for(const r of s)for(const n of s){const s={x:a.x+n,y:a.y+r,width:a.width,height:a.height};if(!this.isWatermarkPositionInsideImage(e.width,e.height,s))continue;const c=`${s.x}:${s.y}:${s.width}`;i.has(c)||(i.add(c),o.push({config:t,position:s,alphaMap:l,metrics:this.measureWatermarkCandidate(e,l,s)}));}}),o.sort((e,t)=>t.metrics.normalizedScore!==e.metrics.normalizedScore?t.metrics.normalizedScore-e.metrics.normalizedScore:t.metrics.score!==e.metrics.score?t.metrics.score-e.metrics.score:e.config.logoSize-t.config.logoSize),o}async resolveValidatedInlineDisplayRemoval(e,t){const n=await this.buildInlineDisplayWatermarkCandidates(e,t);let r=0;for(const o of n){if(!this.hasDetectableWatermark(o.metrics))break;const t=this.cloneImageData(e);this.removeWatermark(t,o.alphaMap,o.position);const n=this.measureWatermarkCandidate(t,o.alphaMap,o.position);if(this.isWatermarkRemovalValid(o.metrics,n))return t;if(r+=1,r>=LA.MAX_VALIDATION_CANDIDATES)break}return null}getWatermarkBgUrl(e){return 48===e?window.__OPHEL_USERSCRIPT_ASSET_URLS__?.watermarkBg48||"":window.__OPHEL_USERSCRIPT_ASSET_URLS__?.watermarkBg96||""}async loadBgImage(e){return this.bgImages[e]?this.bgImages[e]:new Promise((t,n)=>{const r=this.getWatermarkBgUrl(e);if(!r)return void n(new Error(`Missing watermark background asset for size ${e}`));const o=new Image;o.onload=()=>{this.bgImages[e]=o,t(o);},o.onerror=n,o.src=r;})}async getAlphaMap(e){if(this.alphaMaps[e])return this.alphaMaps[e];const t=await this.loadBgImage(e),n=document.createElement("canvas");n.width=e,n.height=e;const r=n.getContext("2d");if(!r)throw new Error("Could not get canvas context");r.drawImage(t,0,0);const o=r.getImageData(0,0,e,e),i=this.calculateAlphaMap(o);return this.alphaMaps[e]=i,i}loadImageFromSource(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e;})}async dataUrlToBlob(e){const t=e.match(/^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,([\s\S]*)$/i);if(!t)throw new Error("Invalid data URL");const n=t[1]||"application/octet-stream",r=!!t[2],o=t[3]||"";if(!r)return new Blob([decodeURIComponent(o)],{type:n});const i=o.replace(/\s+/g,""),a=atob(i),s=new Uint8Array(a.length);for(let l=0;l{e&&(n.includes(e)||n.push(e));},o=e=>{for(const t of (e=>{const t=e.search(/[?#]/),n=-1===t?e.length:t,r=e.lastIndexOf("/",n),o=e.lastIndexOf("=",n);if(-1===o||o{const t=e.toLowerCase();return !/^s\d+$/.test(t)&&!/^w\d+$/.test(t)&&!/^h\d+$/.test(t)}).filter(e=>"d"!==e.toLowerCase()),s=a.filter(e=>"rj"!==e.toLowerCase()),l=[["s0","d",...s],["s0",...s],["s0","d",...a],["s0",...a]],c=[];for(const d of l){const t=d.join("-"),r=`${e.slice(0,o+1)}${t}${e.slice(n)}`;c.includes(r)||c.push(r);}return c})(e))r(t);};return t.includes("/gg/")?(o(t.replace("/gg/","/rd-gg-dl/")),o(t.replace("/gg/","/rd-gg/")),o(t),n):t.includes("/rd-gg/")?(o(t.replace("/rd-gg/","/rd-gg-dl/")),o(t),o(t.replace("/rd-gg/","/gg/")),n):t.includes("/rd-gg-dl/")?(o(t),o(t.replace("/rd-gg-dl/","/rd-gg/")),o(t.replace("/rd-gg-dl/","/gg/")),n):(o(t),n)}async fetchOriginalBlobSingle(e){return async function(e){return new Promise((t,n)=>{GM_xmlhttpRequest({method:"GET",url:e,headers:{Referer:"https://gemini.google.com/",Origin:"https://gemini.google.com"},responseType:"blob",onload:e=>{e.status>=200&&e.status<300?t(e.response):n(new Error(`HTTP ${e.status}`));},onerror:e=>n(new Error(e?.message||"GM_xmlhttpRequest failed"))});})}(e)}async fetchOriginalBlob(e,t){const n=this.shouldInterceptGeminiImageUrl(e)?this.buildRemoteFetchCandidates(e):[e];let r=null;for(const i of n)try{const e=await this.fetchOriginalBlobSingle(i);if(t?.requireNonPreviewSource&&/\/gg\//.test(i))throw new Error("fullsize-source-unavailable");return e}catch(o){r=o;}throw r instanceof Error?r:new Error("Failed to fetch original image")}async processLoadedImageToDataUrl(e,t,n){const r=document.createElement("canvas");r.width=e.width,r.height=e.height;const o=r.getContext("2d");if(!o)throw new Error("Could not get canvas context");o.drawImage(e,0,0);const i=o.getImageData(0,0,r.width,r.height);if(n?.requireDetectableWatermark&&this.isUserscriptInlineDisplaySource(t)){const e=await this.resolveValidatedInlineDisplayRemoval(i,t);if(!e)throw new Error(_A);return o.putImageData(e,0,0),r.toDataURL("image/png")}const a=this.detectWatermarkConfig(r.width,r.height,t),s=this.calculateWatermarkPosition(r.width,r.height,a),l=await this.getAlphaMap(a.logoSize);if(n?.requireDetectableWatermark&&this.isWatermarkPositionInsideImage(r.width,r.height,s)){const e=this.measureWatermarkCandidate(i,l,s);if(!this.hasDetectableWatermark(e))throw new Error(_A)}return this.removeWatermark(i,l,s),o.putImageData(i,0,0),r.toDataURL("image/png")}async processImageSourceToDataUrl(e,t){const n=await this.loadImageFromSource(e);return this.processLoadedImageToDataUrl(n,e,t)}async processImageBlobToDataUrl(e,t){const n=URL.createObjectURL(e);try{const e=await this.loadImageFromSource(n);return await this.processLoadedImageToDataUrl(e,t)}finally{URL.revokeObjectURL(n);}}async getProcessedDataUrl(e,t){const n=this.replaceWithNormalSize(e);if(!t?.bypassCache){const e=this.processedDataUrlCache.get(n);if(e)return e}if(!t?.bypassCache){const e=this.processingMap.get(n);if(e)return e}const r=(async()=>{const e=await this.fetchOriginalBlob(n,{requireNonPreviewSource:t?.requireNonPreviewSource}),r=await this.processImageBlobToDataUrl(e,n);return t?.bypassCache||(this.processedDataUrlCache.set(n,r),this.trimProcessedDataUrlCache()),r})();if(!t?.bypassCache){this.processingMap.set(n,r);try{return await r}finally{this.processingMap.delete(n);}}return r}trimProcessedDataUrlCache(){if(this.processedDataUrlCache.size<=100)return;const e=this.processedDataUrlCache.keys().next().value;e&&this.processedDataUrlCache.delete(e);}async getProcessedInlineDisplayDataUrl(e){const t=`inline-display:${e}`,n=this.processedDataUrlCache.get(t);if(n)return n;const r=this.processingMap.get(t);if(r)return r;const o=(async()=>{const n=await this.processImageSourceToDataUrl(e,{requireDetectableWatermark:true});return this.processedDataUrlCache.set(t,n),this.trimProcessedDataUrlCache(),n})();this.processingMap.set(t,o);try{return await o}finally{this.processingMap.delete(t);}}async getProcessedDisplayDataUrl(e){if(this.isUserscriptInlineDisplaySource(e))return this.getProcessedInlineDisplayDataUrl(e);if(!this.shouldInterceptGeminiImageUrl(e))return this.resolveActionDataUrl(e);const t=this.replaceWithNormalSize(e),n=this.processedDataUrlCache.get(t);if(n)return n;const r=`display:${t}`,o=this.processingMap.get(r);if(o)return o;const i=(async()=>{const e=await this.fetchOriginalBlobSingle(t),n=await this.processImageBlobToDataUrl(e,t);return this.processedDataUrlCache.set(t,n),this.trimProcessedDataUrlCache(),n})();this.processingMap.set(r,i);try{return await i}finally{this.processingMap.delete(r);}}isValidGeminiImage(e){return !!e.closest("generated-image,.generated-image-container")||this.isLikelyGeneratedImage(e)}findGeminiImages(){return [...document.querySelectorAll("img")].filter(e=>{const t=this.getImageSourceForAction(e),n=e.getAttribute("data-ophel-wm-skip-source")||"",r="skipped"===e.dataset.watermarkProcessed&&n===t;return this.isValidGeminiImage(e)&&this.isSupportedGeminiImageSource(t)&&!this.shouldSkipAutoProcessingSource(t)&&"true"!==e.dataset.watermarkProcessed&&"processing"!==e.dataset.watermarkProcessed&&!r})}async processExistingImages(){const e=this.findGeminiImages();for(const t of e)this.processSingleImage(t);}async processSingleImage(e){const t=e.currentSrc||e.src;if(!t||!this.isSupportedGeminiImageSource(t))return;if(this.shouldSkipAutoProcessingSource(t))return;if(this.processingQueue.has(t))return;this.processingQueue.add(t),e.dataset.watermarkProcessed="processing";const n=this.showImageProcessingIndicator(e),r=t.startsWith("data:image/")||t.startsWith("blob:")?t:this.replaceWithNormalSize(t);try{const t=await this.getProcessedDisplayDataUrl(r);e.src=t,e.dataset.watermarkProcessed="true",e.setAttribute("data-ophel-wm-source",r),e.setAttribute("data-ophel-wm-processed","1"),e.removeAttribute("data-ophel-wm-skip-source");}catch(o){if((o instanceof Error?o.message:"")===_A)return e.dataset.watermarkProcessed="skipped",e.setAttribute("data-ophel-wm-skip-source",r),e.removeAttribute("data-ophel-wm-source"),void e.removeAttribute("data-ophel-wm-processed");e.dataset.watermarkProcessed="error",e.removeAttribute("data-ophel-wm-processed");}finally{this.hideImageProcessingIndicator(n),this.processingQueue.delete(t);}}replaceWithNormalSize(e){if(!e)return e;if(e.startsWith("data:image/")||e.startsWith("blob:"))return e;if(!this.shouldInterceptGeminiImageUrl(e))return e;const t=e.search(/[?#]/),n=-1===t?e.length:t,r=e.lastIndexOf("/",n),o=e.lastIndexOf("=",n);if(-1===o||o{const t=e.toLowerCase();return !/^s\d+$/.test(t)&&(!/^w\d+$/.test(t)&&(!/^h\d+$/.test(t)&&"rj"!==t))})].join("-");return `${e.slice(0,o+1)}${a}${e.slice(n)}`}startObserver(){const e=new MutationObserver(e=>{let t=false;for(const n of e)n.addedNodes.length>0&&(t=true);t&&this.processExistingImages();});e.observe(document.body,{childList:true,subtree:true}),this.stopObserver=()=>e.disconnect();}}let NA={assistantMermaidRenderer:null,themeManager:null,copyManager:null,layoutManager:null,markdownFixer:null,tabManager:null,watermarkRemover:null,readingHistoryManager:null,modelLocker:null,scrollLockManager:null,userQueryMarkdownRenderer:null,policyRetryManager:null,usageCounterManager:null},DA=null,qA=null;function RA(e){return e.content?.assistantMermaid??true}async function PA(e){const{adapter:t,settings:n}=e;if("fallback"!==t.getAssistantMermaidSupportMode())return NA.assistantMermaidRenderer?.stop(),void(NA.assistantMermaidRenderer=null);RA(n)?NA.assistantMermaidRenderer?NA.assistantMermaidRenderer.updateSettings(true):(qA||(qA=(async()=>{"fallback"===t.getAssistantMermaidSupportMode()&&RA(Ti())&&(NA.assistantMermaidRenderer?NA.assistantMermaidRenderer.updateSettings(true):NA.assistantMermaidRenderer=new OC(t,true));})().finally(()=>{qA=null;})),await qA):NA.assistantMermaidRenderer?.updateSettings(false);}function zA(e){const{adapter:t,settings:n,siteId:r}=e,o=Xo(n,r),i=Wv({mode:o.mode,adapter:t,lightPresetId:o.lightStyleId||"google-gradient",darkPresetId:o.darkStyleId||"classic-dark",syncNativePageTheme:n.theme?.syncNativePageTheme??true,apply:true});return NA.themeManager=i,i}async function BA(e){const{adapter:t,settings:n,siteId:r}=e,o=Xo(n,r);if("system"===o.mode&&NA.themeManager)return void(await NA.themeManager.setMode("system"));const i="system"===o.mode?window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":"dark"===o.mode?"dark":"light";if(!t.supportsHostThemeSync())return void NA.themeManager?.applyTheme(i);const a=document.documentElement.className,s=/\bdark\b/i.test(a),l=/\blight\b/i.test(a),c=document.body.className,d=/\bdark-theme\b/i.test(c),u=document.body.style.colorScheme;let h="light";s||d||"dark"===u?h="dark":l&&(h="light"),h!==i&&(NA.themeManager&&NA.themeManager.applyTheme(i),t&&"function"==typeof t.toggleTheme&&await t.toggleTheme(i));}function OA(e,t){switch(t){case lo:return e.content?.markdownFix??false;case po:return e.aistudio?.markdownFix??false;case co:return e.chatgpt?.markdownFix??false;default:return false}}function FA(e){const{adapter:t,settings:n,siteId:r}=e,o=t.getMarkdownFixerConfig(),i=OA(n,r);o&&i&&(NA.markdownFixer=new iA(o),NA.markdownFixer.start(),console.warn(`[Ophel] MarkdownFixer started for ${t.getName()}`));}function $A(e){const{adapter:t,settings:n,siteId:r}=e,o=ei(n,r),i=ni(n,r),a=ri(n,r).enabled,s=oi(n,r),l=!!t.getCleanModeConfig()&&s.enabled;(o?.enabled||i?.enabled||a||l)&&(NA.layoutManager=new XC(t,o),o?.enabled&&NA.layoutManager.apply(),i?.enabled&&NA.layoutManager.updateUserQueryConfig(i),a&&NA.layoutManager.updateZenMode(true),l&&NA.layoutManager.updateCleanMode(true));}function UA(e){const{adapter:t,settings:n}=e;n.content&&(NA.copyManager=new jC(n.content,t),n.content.formulaCopy&&NA.copyManager.initFormulaCopy(),n.content.tableCopy&&NA.copyManager.initTableCopy());}function jA(e){const{adapter:t,settings:n}=e;n.tab&&(NA.tabManager=new dA(t,n.tab),NA.tabManager.start());}function HA(e){const{adapter:t,settings:n,siteId:r}=e;NA.usageCounterManager=new yA(t,n.usageMonitor,r),NA.usageCounterManager.start();}function WA(e){const{settings:t,siteId:n}=e;n!==lo&&n!==ho||!t.content?.watermarkRemoval||(NA.watermarkRemover=new LA,NA.watermarkRemover.start());}async function GA(e){const{adapter:t,settings:n}=e;if(n.readingHistory?.persistence){DA&&(clearTimeout(DA),DA=null);const e=e=>{NA.readingHistoryManager||(NA.readingHistoryManager=new lA(t,e.readingHistory),NA.readingHistoryManager.startRecording(),NA.readingHistoryManager.cleanup());};if(await(ii||(ii=new Promise(e=>{"undefined"!=typeof chrome&&chrome.storage?.local?chrome.storage.local.get(jo,t=>{const n=t?.[jo];if(void 0===n)return void e(false);const r="number"==typeof n?n:Number(n);Number.isFinite(r)?Date.now()-r<=5e3?e(true):chrome.storage.local.remove(jo,()=>e(false)):e(true);}):e(false);}),ii))||li())return void(DA=setTimeout(()=>{DA=null;const t=Ti();t.readingHistory?.persistence&&!NA.readingHistoryManager&&e(t);},5e3));if(e(n),n.readingHistory.autoRestore){const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Di);return {showToast:e}},void 0);NA.readingHistoryManager.restoreProgress(t=>e(t,3e3)).then(t=>{t&&e(se("restoredPosition"),2e3);});}NA.readingHistoryManager.cleanup();}}function QA(e){const{adapter:t,settings:n,siteId:r}=e,o=ti(n,r);NA.modelLocker=new aA(t,o),o.enabled&&o.keyword&&NA.modelLocker.start();}function VA(e){const{adapter:t,settings:n}=e;NA.scrollLockManager=new cA(t,n);}function KA(e){const{adapter:t,settings:n}=e;NA.userQueryMarkdownRenderer=new EA(t,n.content?.userQueryMarkdown??true);}function ZA(e){const{adapter:t,settings:n,siteId:r}=e;r===ho&&(NA.policyRetryManager=new sA(t,n.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3}));}const YA=Object.freeze(Object.defineProperty({__proto__:null,initAssistantMermaidRenderer:PA,initCopyManager:UA,initCoreModules:async function(e){return zA(e),setTimeout(()=>BA(e),1e3),FA(e),$A(e),UA(e),jA(e),WA(e),HA(e),await GA(e),QA(e),VA(e),KA(e),await PA(e),ZA(e),NA},initLayoutManager:$A,initMarkdownFixer:FA,initModelLocker:QA,initPolicyRetryManager:ZA,initReadingHistoryManager:GA,initScrollLockManager:VA,initTabManager:jA,initThemeManager:zA,initUrlChangeObserver:function(e){const{adapter:t}=e;let n=window.location.pathname,o=null;const i=async()=>{const e=window.location.pathname;e!==n&&(n=e,console.warn("[Ophel] URL changed, reinitializing modules..."),o&&(clearTimeout(o),o=null),NA.readingHistoryManager&&(NA.readingHistoryManager.stopRecording(),o=setTimeout(async()=>{o=null;const{showToast:e}=await r(async()=>{const{showToast:e}=await Promise.resolve().then(()=>Di);return {showToast:e}},void 0);if(!li()){await(NA.readingHistoryManager?.restoreProgress(t=>e(t,3e3)))&&e(se("restoredPosition"),2e3);}NA.readingHistoryManager?.startRecording();},1500)),window.dispatchEvent(new Event("gh-url-change")),NA.tabManager&&(NA.tabManager.resetConversationTitleCache(),[300,800,1500].forEach(e=>setTimeout(()=>NA.tabManager?.updateTabName(true),e))),t.findTextarea(),NA.usageCounterManager?.handleUrlChange(),NA.modelLocker?.relock(300));};window.addEventListener("popstate",i);const a=history.pushState,s=history.replaceState;history.pushState=function(...e){a.apply(this,e),i();},history.replaceState=function(...e){s.apply(this,e),i();},setInterval(i,1e3);},initUsageCounterManager:HA,initUserQueryMarkdownRenderer:KA,initWatermarkRemover:WA,subscribeModuleUpdates:function(e){const{adapter:t,siteId:n}=e;let r=Ti().language;Mi(e=>{e.language&&e.language!==r&&(r=e.language,ie(e.language),NA.assistantMermaidRenderer?.refreshLocalizedTexts(),NA.layoutManager?.refreshLocalizedTexts());const o=Xo(e,n);o&&NA.themeManager&&(NA.themeManager.setNativeThemeOverrideEnabled(e.theme?.syncNativePageTheme??true),NA.themeManager.setPresets(o.lightStyleId||"google-gradient",o.darkStyleId||"classic-dark"));const i=ti(e,n);i&&NA.modelLocker&&NA.modelLocker.updateConfig(i),e&&NA.scrollLockManager&&NA.scrollLockManager.updateSettings(e);const a=t.getMarkdownFixerConfig(),s=OA(e,n);a&&s?(NA.markdownFixer||(NA.markdownFixer=new iA(a)),NA.markdownFixer.start()):NA.markdownFixer?.stop();const l=ei(e,n),c=ni(e,n),d=ri(e,n).enabled,u=oi(e,n),h=!!t.getCleanModeConfig()&&u.enabled;NA.layoutManager?(NA.layoutManager.updateConfig(l),NA.layoutManager.updateUserQueryConfig(c),NA.layoutManager.updateZenMode(d),NA.layoutManager.updateCleanMode(h)):(l?.enabled||c?.enabled||d||h)&&(NA.layoutManager=new XC(t,l),l?.enabled&&NA.layoutManager.apply(),c?.enabled&&NA.layoutManager.updateUserQueryConfig(c),d&&NA.layoutManager.updateZenMode(true),h&&NA.layoutManager.updateCleanMode(true)),!e||n!==lo&&n!==ho||(e.content?.watermarkRemoval?(NA.watermarkRemover||(NA.watermarkRemover=new LA),NA.watermarkRemover.start()):NA.watermarkRemover?.stop()),e?.tab&&(NA.tabManager?NA.tabManager.updateSettings(e.tab):(NA.tabManager=new dA(t,e.tab),NA.tabManager.start())),e?.usageMonitor&&(NA.usageCounterManager?NA.usageCounterManager.updateSettings(e.usageMonitor):(NA.usageCounterManager=new yA(t,e.usageMonitor,n),NA.usageCounterManager.start())),e?.readingHistory&&(NA.readingHistoryManager?NA.readingHistoryManager.updateSettings(e.readingHistory):e.readingHistory.persistence&&(NA.readingHistoryManager=new lA(t,e.readingHistory),NA.readingHistoryManager.startRecording())),e?.content&&(NA.copyManager?NA.copyManager.updateSettings(e.content):(NA.copyManager=new jC(e.content),e.content.formulaCopy&&NA.copyManager.initFormulaCopy(),e.content.tableCopy&&NA.copyManager.initTableCopy()),e.content.userQueryMarkdown?NA.userQueryMarkdownRenderer?NA.userQueryMarkdownRenderer.updateSettings(true):NA.userQueryMarkdownRenderer=new EA(t,true):NA.userQueryMarkdownRenderer?.updateSettings(false)),PA({adapter:t,settings:e}).catch(e=>{console.error("[Ophel] Assistant Mermaid renderer update failed:",e);}),e?.geminiEnterprise&&n===ho&&NA.policyRetryManager&&NA.policyRetryManager.updateSettings(e.geminiEnterprise?.policyRetry||{enabled:false,maxRetries:3});});},syncHostThemeWithSettings:BA},Symbol.toStringTag,{value:"Module"})); })();